logxpert 1.0.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0
4
+ - Replace `moment` with `dayjs`
5
+ - Add ESM entry (`main.mjs`) + `index.d.ts` types
6
+ - Add `log.setLevel/getLevel`, `LOG_LEVEL` env support
7
+ - Add `log.createLogger()` isolated instances and `log.child()`
8
+ - Add structured logging: objects, meta, `Error` stacks, `splat`
9
+ - `files.filename` option, input validation in `settings()`
10
+ - Fix license to `GPL-3.0-only`, add `exports`, `files`, `engines`
11
+ - Add tests (`node --test`) and CI
12
+
13
+ ## 1.0.5
14
+ - Previous CJS-only release with `moment` + `winston`.
package/README.md CHANGED
@@ -1,108 +1,97 @@
1
- # LogXpert
2
-
3
- LogXpert is a powerful logging library for Node.js that provides easy-to-use logging methods with colorful formatted output and optional file logging support
4
-
5
- ## Table of Contents
6
- - [Installation](#installation)
7
- - [Usage](#usage)
8
- - [Basic Logging](#basic-logging)
9
- - [Advanced Logging: File Output & Custom Console Timestamp](#advanced-logging-file-output--custom-console-timestamp)
10
- - [API Reference](#api-reference)
11
- - [Additional Information](#additional-information)
12
- - [License](#license)
13
-
14
- ## Installation
15
-
16
- You can install LogXpert using npm:
17
-
18
- ```sh
19
- npm install logxpert
20
- ```
21
-
22
- ## Usage
23
-
24
- ### Basic Logging
25
-
26
- Import LogXpert in your project and use it to log messages:
27
-
28
- ```js
29
- const log = require('logxpert');
30
-
31
- // Log a general message
32
- log('This is a general log message.');
33
-
34
- // Log an error message
35
- log.error('This is an error message.');
36
-
37
- // Log a warning message
38
- log.warn('This is a warning message.');
39
-
40
- // Log an informational message
41
- log.info('This is an informational message.');
42
-
43
- // Log a debug message
44
- log.debug('This is a debug message.');
45
- ```
46
-
47
- ### Advanced Logging: File Output & Custom Console Timestamp
48
-
49
- LogXpert supports file logging using [winston](https://github.com/winstonjs/winston) and [winston-daily-rotate-file](https://github.com/winstonjs/winston-daily-rotate-file).
50
-
51
- Example configuration:
52
-
53
- ```js
54
- const log = require('logxpert');
55
-
56
- log.settings({
57
- console: {
58
- enableTimestamp: true,
59
- // You can now include decoration characters as desired:
60
- timestampFormat: "This is the date: [YYYY-MM-DD HH:mm:ss] - ",
61
- timestampPrefix: '',
62
- timestampSuffix: ''
63
- },
64
- files: {
65
- folder: 'logs',
66
- filesName: 'YYYY-MM-DD',
67
- maxFile: '14d',
68
- maxSize: '20m',
69
- zippedArchive: false
70
- }
71
- });
72
- ```
73
-
74
- ## API Reference
75
-
76
- - **log(message: string):**
77
- Logs a general message using the `info` level.
78
-
79
- - **log.error(message: string):**
80
- Logs an error message.
81
-
82
- - **log.warn(message: string):**
83
- Logs a warning message.
84
-
85
- - **log.info(message: string):**
86
- Logs an informational message.
87
-
88
- - **log.debug(message: string):**
89
- Logs a debug message.
90
-
91
- - **log.settings(options: object):**
92
- Configures file logging and console output options.
93
- **Console Options:**
94
- - `enableTimestamp` (boolean): Enable/disable timestamp (default: `true`).
95
- - `timestampFormat` (string): Format for the timestamp including any desired literal text or decoration (default: `'YYYY-MM-DD HH:mm:ss'`).
96
- - `timestampPrefix` (string): Prefix for the timestamp.
97
- - `timestampSuffix` (string): Suffix for the timestamp.
98
-
99
- **Files Options:**
100
- - `folder` (string): Directory where log files will be stored (default: `'logs'`).
101
- - `filesName` (string): Date pattern for the log file name (default: `'YYYY-MM-DD'`).
102
- - `maxFile` (string): Maximum file retention (default: `'14d'`).
103
- - `maxSize` (string): Maximum size per log file (default: `'20m'`).
104
- - `zippedArchive` (boolean): Archive logs in zip format (default: `false`).
105
-
106
- ## License
107
-
108
- This project is licensed under GNU General Public License v3.0. See the [LICENSE](LICENSE) file for details.
1
+ # LogXpert
2
+
3
+ LogXpert is a powerful logging library for Node.js that provides easy-to-use logging methods with colorful formatted output and optional file logging support.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install logxpert
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ CommonJS:
14
+
15
+ ```js
16
+ const log = require('logxpert');
17
+
18
+ log('general message');
19
+ log.error('error message');
20
+ log.warn('warn message');
21
+ log.info('info with meta', { user: 1 });
22
+ log.debug({ structured: 'object' });
23
+ log.error(new Error('boom'));
24
+ ```
25
+
26
+ ESM:
27
+
28
+ ```js
29
+ import log from 'logxpert';
30
+
31
+ log.info('hello');
32
+ ```
33
+
34
+ Set level (`LOG_LEVEL` env also respected):
35
+
36
+ ```js
37
+ log.setLevel('info');
38
+ console.log(log.getLevel());
39
+ ```
40
+
41
+ Isolated instances and child loggers:
42
+
43
+ ```js
44
+ const { createLogger } = require('logxpert');
45
+ const apiLog = createLogger({ level: 'info' });
46
+ apiLog.info('isolated');
47
+
48
+ const child = log.child({ service: 'api' });
49
+ child.info('child message');
50
+ ```
51
+
52
+ ### File output & console timestamp
53
+
54
+ ```js
55
+ log.settings({
56
+ level: 'debug',
57
+ console: {
58
+ enableTimestamp: true,
59
+ timestampFormat: 'YYYY-MM-DD HH:mm:ss',
60
+ timestampPrefix: '',
61
+ timestampSuffix: '',
62
+ colorize: true
63
+ },
64
+ files: {
65
+ folder: 'logs',
66
+ filename: 'application-%DATE%.log',
67
+ filesName: 'YYYY-MM-DD',
68
+ maxFile: '14d',
69
+ maxSize: '20m',
70
+ zippedArchive: false
71
+ }
72
+ });
73
+ ```
74
+
75
+ Close file transports on shutdown:
76
+
77
+ ```js
78
+ log.close();
79
+ ```
80
+
81
+ ## API Reference
82
+
83
+ - **log(message, ...meta):** info level.
84
+ - **log.error/warn/info/debug/http/verbose/silly(message, ...meta)**
85
+ - **log.log(level, message, ...meta)**
86
+ - **log.settings({ console, files, level })**
87
+ - **log.setLevel(level) / log.getLevel()**
88
+ - **log.createLogger(options):** independent instance.
89
+ - **log.child(meta):** child logger with bound context.
90
+ - **log.close():** remove file transport.
91
+
92
+ Console options: `enableTimestamp`, `timestampFormat`, `timestampPrefix`, `timestampSuffix`, `colorize`, `level`.
93
+ Files options: `folder`, `filename`, `filesName`/`datePattern`, `maxFile`/`maxFiles`, `maxSize`, `zippedArchive`, `level`.
94
+
95
+ ## License
96
+
97
+ GPL-3.0-only. See [LICENSE](LICENSE).
package/index.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ export type LogLevel = 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly';
2
+
3
+ export interface ConsoleOptions {
4
+ enableTimestamp?: boolean;
5
+ timestampFormat?: string;
6
+ timestampPrefix?: string;
7
+ timestampSuffix?: string;
8
+ colorize?: boolean;
9
+ level?: LogLevel;
10
+ }
11
+
12
+ export interface FilesOptions {
13
+ folder?: string;
14
+ filesName?: string;
15
+ datePattern?: string;
16
+ filename?: string;
17
+ maxFile?: string;
18
+ maxFiles?: string;
19
+ maxSize?: string;
20
+ zippedArchive?: boolean;
21
+ level?: LogLevel;
22
+ }
23
+
24
+ export interface LogSettingsOptions {
25
+ console?: ConsoleOptions;
26
+ files?: FilesOptions;
27
+ level?: LogLevel;
28
+ }
29
+
30
+ export interface ChildLogger {
31
+ error(message: unknown, ...meta: unknown[]): void;
32
+ warn(message: unknown, ...meta: unknown[]): void;
33
+ info(message: unknown, ...meta: unknown[]): void;
34
+ debug(message: unknown, ...meta: unknown[]): void;
35
+ log(level: LogLevel, message: unknown, ...meta: unknown[]): void;
36
+ }
37
+
38
+ export interface LogXpert {
39
+ (message: unknown, ...meta: unknown[]): void;
40
+ error(message: unknown, ...meta: unknown[]): void;
41
+ warn(message: unknown, ...meta: unknown[]): void;
42
+ info(message: unknown, ...meta: unknown[]): void;
43
+ debug(message: unknown, ...meta: unknown[]): void;
44
+ http(message: unknown, ...meta: unknown[]): void;
45
+ verbose(message: unknown, ...meta: unknown[]): void;
46
+ silly(message: unknown, ...meta: unknown[]): void;
47
+ log(level: LogLevel, message: unknown, ...meta: unknown[]): void;
48
+ settings(options?: LogSettingsOptions): void;
49
+ setLevel(level: LogLevel): void;
50
+ getLevel(): string;
51
+ child(meta?: Record<string, unknown>): ChildLogger;
52
+ close(): void;
53
+ createLogger(options?: LogSettingsOptions): LogXpert;
54
+ }
55
+
56
+ declare const log: LogXpert;
57
+ export default log;
package/main.js CHANGED
@@ -1,197 +1,188 @@
1
- const fs = require('fs');
2
- const moment = require('moment'); // Add moment as a dependency: npm install moment
3
- const { createLogger, format, transports } = require('winston');
4
- require('winston-daily-rotate-file');
5
-
6
- /**
7
- * Helper function to format the timestamp while preserving square brackets.
8
- * It identifies square brackets and formats only the contents within them,
9
- * preserving all other text (including the brackets) as literal.
10
- * If no brackets are provided, the entire string is treated as a Moment.js format.
11
- *
12
- * @param {string} fmt - The user-defined format string.
13
- * @returns {string} - The formatted timestamp.
14
- *
15
- * Example:
16
- * Input: "This is the date: [YYYY-MM-DD HH:mm:ss] - "
17
- * Output: "This is the date: [2025-03-21 15:30:45] - "
18
- */
19
- function formatCustomTimestamp(fmt) {
20
- // If the format contains both [ and ], we use "template mode".
21
- // This allows users to include literal text alongside bracketed date tokens.
22
- if (fmt.includes('[') && fmt.includes(']')) {
23
- return fmt.split(/(\[[^\]]*\])/).map(part => {
24
- if (part.startsWith('[') && part.endsWith(']')) {
25
- // Inside brackets: format the content while keeping the brackets literal.
26
- const inner = part.slice(1, -1);
27
- return '[' + (inner ? moment().format(inner) : '') + ']';
28
- }
29
- // Outside brackets: treat as literal text to avoid mangling letters.
30
- return part;
31
- }).join('');
32
- }
33
- // Standard mode: treat the whole string as a moment format string.
34
- return moment().format(fmt);
35
- }
36
-
37
-
38
- /**
39
- * @typedef {Object} ConsoleOptions
40
- * @property {boolean} [enableTimestamp=true] - Enable or disable timestamp in console logs.
41
- * @property {string} [timestampFormat='YYYY-MM-DD HH:mm:ss'] - Custom format for the timestamp.
42
- * Use square brackets (e.g., [YYYY-MM-DD]) to mark parts that should be formatted.
43
- * Text outside brackets is treated as literal.
44
- * @property {string} [timestampPrefix=''] - Optional text to prepend to the timestamp.
45
- * @property {string} [timestampSuffix=''] - Optional text to append to the timestamp.
46
- */
47
-
48
- /**
49
- * @typedef {Object} FilesOptions
50
- * @property {string} [folder='logs'] - Directory where log files will be stored.
51
- * @property {string} [filesName='YYYY-MM-DD'] - Date pattern used in the log file name.
52
- * @property {string} [maxFile='14d'] - Maximum file retention time.
53
- * @property {string} [maxSize='20m'] - Maximum file size per log file.
54
- * @property {boolean} [zippedArchive=false] - Whether to archive logs as zip.
55
- */
56
-
57
- /**
58
- * @typedef {Object} LogSettingsOptions
59
- * @property {ConsoleOptions} [console] - Options for customizing console output.
60
- * @property {FilesOptions} [files] - Options for configuring file logging.
61
- */
62
-
63
- // Custom format for logger output
64
- const customFormat = format.printf(({ timestamp, level, message }) => {
65
- return timestamp ? `${timestamp} [${level}]: ${message}` : `[${level}]: ${message}`;
66
- });
67
-
68
- // Default console timestamp format
69
- const defaultConsoleFormat = 'YYYY-MM-DD HH:mm:ss';
70
-
71
- // Create the global logger. Its default format will be overridden by the console transport settings.
72
- const logger = createLogger({
73
- level: 'debug',
74
- format: format.combine(
75
- format.timestamp({ format: () => moment().format(defaultConsoleFormat) }),
76
- customFormat
77
- )
78
- });
79
-
80
- // Create default console transport (will be replaced via settings)
81
- let consoleTransport = new transports.Console({
82
- format: format.combine(
83
- format.colorize(),
84
- format.timestamp({ format: () => moment().format(defaultConsoleFormat) }),
85
- customFormat
86
- )
87
- });
88
- logger.add(consoleTransport);
89
-
90
- // Reference to file transport (added via settings)
91
- let fileTransport;
92
-
93
- /**
94
- * Configures logging settings for both console and file transports.
95
- *
96
- * @param {LogSettingsOptions} options - The settings for both console and file logging.
97
- * @example
98
- * // Example: Fully custom console timestamp that preserves decorational brackets,
99
- * // and enabling file logging.
100
- * log.settings({
101
- * console: {
102
- * enableTimestamp: true,
103
- * timestampFormat: "This is the date: [YYYY-MM-DD HH:mm:ss] - "
104
- * },
105
- * files: {
106
- * folder: 'logs',
107
- * filesName: 'YYYY-MM-DD',
108
- * maxFile: '14d',
109
- * maxSize: '20m',
110
- * zippedArchive: false
111
- * }
112
- * });
113
- */
114
- function applySettings(options = {}) {
115
- if (options.console) {
116
- const enableTimestamp = options.console.enableTimestamp !== undefined ? options.console.enableTimestamp : true;
117
- const timestampFormat = options.console.timestampFormat || defaultConsoleFormat;
118
- const timestampPrefix = options.console.timestampPrefix || '';
119
- const timestampSuffix = options.console.timestampSuffix || '';
120
-
121
- // Remove the current console transport
122
- logger.remove(consoleTransport);
123
-
124
- // Build the console format based on the enableTimestamp flag.
125
- const consoleFormat = enableTimestamp
126
- ? format.combine(
127
- format.colorize(),
128
- format.timestamp({ format: () => timestampPrefix + formatCustomTimestamp(timestampFormat) + timestampSuffix }),
129
- customFormat
130
- )
131
- : format.combine(
132
- format((info) => { delete info.timestamp; return info; })(),
133
- format.colorize(),
134
- customFormat
135
- );
136
-
137
- consoleTransport = new transports.Console({
138
- format: consoleFormat
139
- });
140
- logger.add(consoleTransport);
141
- }
142
-
143
- if (options.files) {
144
- const folder = options.files.folder || 'logs';
145
- const datePattern = options.files.filesName || 'YYYY-MM-DD';
146
- const maxFiles = options.files.maxFile || '14d';
147
- const maxSize = options.files.maxSize || '20m';
148
- const zippedArchive = options.files.zippedArchive !== undefined ? options.files.zippedArchive : false;
149
-
150
- if (!fs.existsSync(folder)) {
151
- fs.mkdirSync(folder, { recursive: true });
152
- }
153
-
154
- if (fileTransport) {
155
- logger.remove(fileTransport);
156
- }
157
-
158
- fileTransport = new transports.DailyRotateFile({
159
- filename: `${folder}/application-%DATE%.log`,
160
- datePattern,
161
- zippedArchive,
162
- maxSize,
163
- maxFiles
164
- });
165
- logger.add(fileTransport);
166
- }
167
- }
168
-
169
- /**
170
- * Logs a general message using the info level.
171
- *
172
- * @param {string} message - The message to be logged.
173
- */
174
- function log(message) {
175
- logger.info(message);
176
- }
177
-
178
- log.error = function (message) {
179
- logger.error(message);
180
- };
181
-
182
- log.warn = function (message) {
183
- logger.warn(message);
184
- };
185
-
186
- log.info = function (message) {
187
- logger.info(message);
188
- };
189
-
190
- log.debug = function (message) {
191
- logger.debug(message);
192
- };
193
-
194
- // Expose the settings function for configuring both file logging and console output.
195
- log.settings = applySettings;
196
-
197
- module.exports = log;
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const dayjs = require('dayjs');
4
+ const { createLogger, format, transports } = require('winston');
5
+ require('winston-daily-rotate-file');
6
+
7
+ const VALID_LEVELS = ['error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly'];
8
+ const DEFAULT_CONSOLE_FORMAT = 'YYYY-MM-DD HH:mm:ss';
9
+
10
+ function formatCustomTimestamp(fmt) {
11
+ if (typeof fmt !== 'string' || !fmt) return dayjs().format(DEFAULT_CONSOLE_FORMAT);
12
+ if (fmt.includes('[') && fmt.includes(']')) {
13
+ return fmt.split(/(\[[^\]]*\])/).map((part) => {
14
+ if (part.startsWith('[') && part.endsWith(']')) {
15
+ const inner = part.slice(1, -1);
16
+ return '[' + (inner ? dayjs().format(inner) : '') + ']';
17
+ }
18
+ return part;
19
+ }).join('');
20
+ }
21
+ return dayjs().format(fmt);
22
+ }
23
+
24
+ function formatExtra(meta) {
25
+ const keys = Object.keys(meta).filter((k) => k !== 'splat' && k !== 'ms');
26
+ if (!keys.length) return '';
27
+ try {
28
+ const picked = {};
29
+ for (const k of keys) picked[k] = meta[k];
30
+ return JSON.stringify(picked);
31
+ } catch {
32
+ return '';
33
+ }
34
+ }
35
+
36
+ const prettyFormat = format.printf(({ timestamp, level, message, ...meta }) => {
37
+ const msg = typeof message === 'string' ? message : message == null ? '' : JSON.stringify(message);
38
+ const extra = formatExtra(meta);
39
+ const body = [msg, extra].filter(Boolean).join(' ');
40
+ return timestamp ? `${timestamp} [${level}]: ${body}` : `[${level}]: ${body}`;
41
+ });
42
+
43
+ function assertLevel(level) {
44
+ if (!VALID_LEVELS.includes(level)) throw new Error(`Invalid log level "${level}". Use one of: ${VALID_LEVELS.join(', ')}`);
45
+ }
46
+
47
+ function normalizeFilesOptions(files = {}) {
48
+ const folder = files.folder ?? 'logs';
49
+ if (typeof folder !== 'string' || !folder.trim() || folder.includes('\0')) {
50
+ throw new Error('files.folder must be a non-empty string');
51
+ }
52
+ const datePattern = files.filesName ?? files.datePattern ?? 'YYYY-MM-DD';
53
+ if (typeof datePattern !== 'string' || !datePattern.trim()) {
54
+ throw new Error('files.filesName/datePattern must be a non-empty string');
55
+ }
56
+ let filename = files.filename ?? `application-%DATE%.log`;
57
+ if (typeof filename !== 'string' || !filename.trim()) {
58
+ throw new Error('files.filename must be a non-empty string');
59
+ }
60
+ if (!filename.includes('%DATE%')) {
61
+ const ext = path.extname(filename) || '.log';
62
+ const base = path.basename(filename, ext);
63
+ filename = `${base}-%DATE%${ext}`;
64
+ }
65
+ return {
66
+ folder: path.normalize(folder),
67
+ datePattern,
68
+ filename,
69
+ maxFiles: files.maxFile ?? files.maxFiles ?? '14d',
70
+ maxSize: files.maxSize ?? '20m',
71
+ zippedArchive: files.zippedArchive ?? false,
72
+ level: files.level,
73
+ };
74
+ }
75
+
76
+ function buildConsoleTransport({ enableTimestamp = true, timestampFormat = DEFAULT_CONSOLE_FORMAT, timestampPrefix = '', timestampSuffix = '', colorize = true, level } = {}) {
77
+ const parts = [];
78
+ if (colorize) parts.push(format.colorize());
79
+ if (enableTimestamp) {
80
+ parts.push(format.timestamp({ format: () => `${timestampPrefix}${formatCustomTimestamp(timestampFormat)}${timestampSuffix}` }));
81
+ } else {
82
+ parts.push(format((info) => { delete info.timestamp; return info; })());
83
+ }
84
+ parts.push(format.errors({ stack: true }), format.splat(), prettyFormat);
85
+ return new transports.Console({ format: format.combine(...parts), level });
86
+ }
87
+
88
+ function buildFileTransport({ folder, datePattern, filename, maxFiles, maxSize, zippedArchive, level }) {
89
+ if (!fs.existsSync(folder)) fs.mkdirSync(folder, { recursive: true });
90
+ return new transports.DailyRotateFile({
91
+ filename: path.join(folder, filename),
92
+ datePattern,
93
+ zippedArchive,
94
+ maxSize,
95
+ maxFiles,
96
+ level,
97
+ format: format.combine(format.errors({ stack: true }), format.splat(), format.timestamp(), prettyFormat),
98
+ });
99
+ }
100
+
101
+ function createLoggerInstance(initial = {}) {
102
+ const globalLevel = process.env.LOG_LEVEL || initial.level || 'debug';
103
+ assertLevel(globalLevel);
104
+
105
+ const logger = createLogger({
106
+ level: globalLevel,
107
+ format: format.combine(format.errors({ stack: true }), format.splat()),
108
+ });
109
+
110
+ let consoleTransport = buildConsoleTransport(initial.console);
111
+ consoleTransport.level = initial.console?.level;
112
+ logger.add(consoleTransport);
113
+
114
+ let fileTransport = null;
115
+ let consoleOpts = { ...(initial.console || {}) };
116
+ let filesOpts = null;
117
+
118
+ function applySettings(options = {}) {
119
+ if (options.level !== undefined) {
120
+ assertLevel(options.level);
121
+ logger.level = options.level;
122
+ }
123
+ if (options.console) {
124
+ if (options.console.level !== undefined && options.console.level !== null) assertLevel(options.console.level);
125
+ consoleOpts = { ...consoleOpts, ...options.console };
126
+ logger.remove(consoleTransport);
127
+ consoleTransport = buildConsoleTransport(consoleOpts);
128
+ consoleTransport.level = consoleOpts.level;
129
+ logger.add(consoleTransport);
130
+ }
131
+ if (options.files) {
132
+ const normalized = normalizeFilesOptions(options.files);
133
+ if (normalized.level !== undefined && normalized.level !== null) assertLevel(normalized.level);
134
+ filesOpts = normalized;
135
+ if (fileTransport) logger.remove(fileTransport);
136
+ fileTransport = buildFileTransport(normalized);
137
+ logger.add(fileTransport);
138
+ }
139
+ }
140
+
141
+ function write(level, message, ...meta) {
142
+ if (message instanceof Error) {
143
+ logger.log(level, message.message, { stack: message.stack, ...meta[0] });
144
+ return;
145
+ }
146
+ logger.log(level, message, ...meta);
147
+ }
148
+
149
+ function callable(message, ...meta) {
150
+ write('info', message, ...meta);
151
+ }
152
+
153
+ callable.error = (m, ...a) => write('error', m, ...a);
154
+ callable.warn = (m, ...a) => write('warn', m, ...a);
155
+ callable.info = (m, ...a) => write('info', m, ...a);
156
+ callable.debug = (m, ...a) => write('debug', m, ...a);
157
+ callable.http = (m, ...a) => write('http', m, ...a);
158
+ callable.verbose = (m, ...a) => write('verbose', m, ...a);
159
+ callable.silly = (m, ...a) => write('silly', m, ...a);
160
+ callable.log = (level, m, ...a) => { assertLevel(level); write(level, m, ...a); };
161
+
162
+ callable.settings = applySettings;
163
+ callable.setLevel = (level) => { assertLevel(level); logger.level = level; };
164
+ callable.getLevel = () => logger.level;
165
+ callable.child = (meta = {}) => {
166
+ const child = logger.child(meta);
167
+ return {
168
+ error: (m, ...a) => child.error(m, ...a),
169
+ warn: (m, ...a) => child.warn(m, ...a),
170
+ info: (m, ...a) => child.info(m, ...a),
171
+ debug: (m, ...a) => child.debug(m, ...a),
172
+ log: child.log.bind(child),
173
+ };
174
+ };
175
+ callable.close = () => {
176
+ if (fileTransport) { logger.remove(fileTransport); try { fileTransport.close?.(); } catch {} fileTransport = null; }
177
+ };
178
+ callable.createLogger = (opts = {}) => createLoggerInstance(opts);
179
+ callable._winston = logger;
180
+
181
+ if (initial.files) applySettings({ files: initial.files });
182
+ if (initial.console || initial.level) applySettings({ console: initial.console, level: initial.level });
183
+
184
+ return callable;
185
+ }
186
+
187
+ module.exports = createLoggerInstance();
188
+ module.exports.createLogger = createLoggerInstance;
package/main.mjs ADDED
@@ -0,0 +1,14 @@
1
+ import log from './main.js';
2
+
3
+ export const settings = log.settings;
4
+ export const setLevel = log.setLevel;
5
+ export const getLevel = log.getLevel;
6
+ export const child = log.child;
7
+ export const close = log.close;
8
+ export const createLogger = log.createLogger;
9
+ export const error = log.error;
10
+ export const warn = log.warn;
11
+ export const info = log.info;
12
+ export const debug = log.debug;
13
+
14
+ export default log;
package/package.json CHANGED
@@ -1,14 +1,51 @@
1
- {
2
- "name": "logxpert",
3
- "version": "1.0.5",
4
- "description": "A powerful logging library for Node.js",
5
- "main": "main.js",
6
- "repository": "git+https://github.com/lighscent/LogXpert.git",
7
- "author": "https://github.com/lighscent",
8
- "license": "MIT",
9
- "dependencies": {
10
- "moment": "^2.30.1",
11
- "winston": "^3.19.0",
12
- "winston-daily-rotate-file": "^5.0.0"
13
- }
14
- }
1
+ {
2
+ "name": "logxpert",
3
+ "version": "2.0.0",
4
+ "description": "A powerful logging library for Node.js with colorful output and daily file rotation",
5
+ "main": "main.js",
6
+ "types": "index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "import": "./main.mjs",
11
+ "require": "./main.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "main.js",
17
+ "main.mjs",
18
+ "index.d.ts",
19
+ "README.md",
20
+ "LICENSE",
21
+ "CHANGELOG.md"
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/lighscent/LogXpert.git"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/lighscent/LogXpert/issues"
29
+ },
30
+ "homepage": "https://github.com/lighscent/LogXpert#readme",
31
+ "author": "https://github.com/lighscent",
32
+ "license": "GPL-3.0-only",
33
+ "keywords": [
34
+ "logging",
35
+ "logger",
36
+ "winston",
37
+ "daily-rotate",
38
+ "nodejs"
39
+ ],
40
+ "engines": {
41
+ "node": ">=18"
42
+ },
43
+ "scripts": {
44
+ "test": "node --test test/logger.test.js"
45
+ },
46
+ "dependencies": {
47
+ "dayjs": "^1.11.23",
48
+ "winston": "^3.19.0",
49
+ "winston-daily-rotate-file": "^5.0.0"
50
+ }
51
+ }
@@ -1,128 +0,0 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- We as members, contributors, and leaders pledge to make participation in our
6
- community a harassment-free experience for everyone, regardless of age, body
7
- size, visible or invisible disability, ethnicity, sex characteristics, gender
8
- identity and expression, level of experience, education, socio-economic status,
9
- nationality, personal appearance, race, religion, or sexual identity
10
- and orientation.
11
-
12
- We pledge to act and interact in ways that contribute to an open, welcoming,
13
- diverse, inclusive, and healthy community.
14
-
15
- ## Our Standards
16
-
17
- Examples of behavior that contributes to a positive environment for our
18
- community include:
19
-
20
- * Demonstrating empathy and kindness toward other people
21
- * Being respectful of differing opinions, viewpoints, and experiences
22
- * Giving and gracefully accepting constructive feedback
23
- * Accepting responsibility and apologizing to those affected by our mistakes,
24
- and learning from the experience
25
- * Focusing on what is best not just for us as individuals, but for the
26
- overall community
27
-
28
- Examples of unacceptable behavior include:
29
-
30
- * The use of sexualized language or imagery, and sexual attention or
31
- advances of any kind
32
- * Trolling, insulting or derogatory comments, and personal or political attacks
33
- * Public or private harassment
34
- * Publishing others' private information, such as a physical or email
35
- address, without their explicit permission
36
- * Other conduct which could reasonably be considered inappropriate in a
37
- professional setting
38
-
39
- ## Enforcement Responsibilities
40
-
41
- Community leaders are responsible for clarifying and enforcing our standards of
42
- acceptable behavior and will take appropriate and fair corrective action in
43
- response to any behavior that they deem inappropriate, threatening, offensive,
44
- or harmful.
45
-
46
- Community leaders have the right and responsibility to remove, edit, or reject
47
- comments, commits, code, wiki edits, issues, and other contributions that are
48
- not aligned to this Code of Conduct, and will communicate reasons for moderation
49
- decisions when appropriate.
50
-
51
- ## Scope
52
-
53
- This Code of Conduct applies within all community spaces, and also applies when
54
- an individual is officially representing the community in public spaces.
55
- Examples of representing our community include using an official e-mail address,
56
- posting via an official social media account, or acting as an appointed
57
- representative at an online or offline event.
58
-
59
- ## Enforcement
60
-
61
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
- reported to the community leaders responsible for enforcement at
63
- augustin.pro.prs@gmail.com.
64
- All complaints will be reviewed and investigated promptly and fairly.
65
-
66
- All community leaders are obligated to respect the privacy and security of the
67
- reporter of any incident.
68
-
69
- ## Enforcement Guidelines
70
-
71
- Community leaders will follow these Community Impact Guidelines in determining
72
- the consequences for any action they deem in violation of this Code of Conduct:
73
-
74
- ### 1. Correction
75
-
76
- **Community Impact**: Use of inappropriate language or other behavior deemed
77
- unprofessional or unwelcome in the community.
78
-
79
- **Consequence**: A private, written warning from community leaders, providing
80
- clarity around the nature of the violation and an explanation of why the
81
- behavior was inappropriate. A public apology may be requested.
82
-
83
- ### 2. Warning
84
-
85
- **Community Impact**: A violation through a single incident or series
86
- of actions.
87
-
88
- **Consequence**: A warning with consequences for continued behavior. No
89
- interaction with the people involved, including unsolicited interaction with
90
- those enforcing the Code of Conduct, for a specified period of time. This
91
- includes avoiding interactions in community spaces as well as external channels
92
- like social media. Violating these terms may lead to a temporary or
93
- permanent ban.
94
-
95
- ### 3. Temporary Ban
96
-
97
- **Community Impact**: A serious violation of community standards, including
98
- sustained inappropriate behavior.
99
-
100
- **Consequence**: A temporary ban from any sort of interaction or public
101
- communication with the community for a specified period of time. No public or
102
- private interaction with the people involved, including unsolicited interaction
103
- with those enforcing the Code of Conduct, is allowed during this period.
104
- Violating these terms may lead to a permanent ban.
105
-
106
- ### 4. Permanent Ban
107
-
108
- **Community Impact**: Demonstrating a pattern of violation of community
109
- standards, including sustained inappropriate behavior, harassment of an
110
- individual, or aggression toward or disparagement of classes of individuals.
111
-
112
- **Consequence**: A permanent ban from any sort of public interaction within
113
- the community.
114
-
115
- ## Attribution
116
-
117
- This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
- version 2.0, available at
119
- https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
-
121
- Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
- enforcement ladder](https://github.com/mozilla/diversity).
123
-
124
- [homepage]: https://www.contributor-covenant.org
125
-
126
- For answers to common questions about this code of conduct, see the FAQ at
127
- https://www.contributor-covenant.org/faq. Translations are available at
128
- https://www.contributor-covenant.org/translations.