@feizk/logger 1.7.0 → 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/dist/index.mjs CHANGED
@@ -1,201 +1,327 @@
1
- // src/utils.ts
2
- import chalk from "chalk";
3
- var TIMESTAMP_TYPES = {
4
- ISO: "iso",
5
- Locale: "locale",
6
- Custom: "custom"
1
+ // src/constants.ts
2
+ var LOG_LEVEL_PRIORITIES = {
3
+ trace: 0,
4
+ debug: 1,
5
+ info: 2,
6
+ warn: 3,
7
+ error: 4,
8
+ fatal: 5
9
+ };
10
+ var ANSI = {
11
+ reset: "\x1B[0m",
12
+ bold: "\x1B[1m",
13
+ dim: "\x1B[2m",
14
+ red: "\x1B[31m",
15
+ green: "\x1B[32m",
16
+ yellow: "\x1B[33m",
17
+ blue: "\x1B[34m",
18
+ magenta: "\x1B[35m",
19
+ cyan: "\x1B[36m",
20
+ gray: "\x1B[90m",
21
+ white: "\x1B[37m",
22
+ bgRed: "\x1B[41m"
23
+ };
24
+ var LEVEL_COLORS = {
25
+ trace: ANSI.gray,
26
+ debug: ANSI.cyan,
27
+ info: ANSI.blue,
28
+ warn: ANSI.yellow,
29
+ error: ANSI.red,
30
+ fatal: `${ANSI.bgRed}${ANSI.white}${ANSI.bold}`
31
+ };
32
+ var LEVEL_LABELS = {
33
+ trace: "[TRACE]",
34
+ debug: "[DEBUG]",
35
+ info: "[INFO]",
36
+ warn: "[WARN]",
37
+ error: "[ERROR]",
38
+ fatal: "[FATAL]"
7
39
  };
8
- function formatTimestamp(formatTimestampFn, types, date = /* @__PURE__ */ new Date()) {
9
- const [, timestamp] = formatTimestampFn(types, date);
10
- return timestamp;
40
+ var CONSOLE_METHODS = {
41
+ trace: "trace",
42
+ debug: "debug",
43
+ info: "log",
44
+ warn: "warn",
45
+ error: "error",
46
+ fatal: "error"
47
+ };
48
+ var TIMESTAMP_PRESETS = {
49
+ iso: (date) => date.toISOString(),
50
+ locale: (date) => date.toLocaleString()
51
+ };
52
+
53
+ // src/utils.ts
54
+ var coloredLabelCache = /* @__PURE__ */ new Map();
55
+ function getColoredLabel(level, enableColors) {
56
+ const cacheKey = `${level}:${enableColors}`;
57
+ const cached = coloredLabelCache.get(cacheKey);
58
+ if (cached !== void 0) return cached;
59
+ const label = LEVEL_LABELS[level];
60
+ if (!enableColors) {
61
+ coloredLabelCache.set(cacheKey, label);
62
+ return label;
63
+ }
64
+ const color = LEVEL_COLORS[level];
65
+ const result = `${color}${label}${ANSI.reset}`;
66
+ coloredLabelCache.set(cacheKey, result);
67
+ return result;
11
68
  }
12
- function getColor(level, enableColors) {
13
- if (!enableColors) return level;
14
- const colors = {
15
- "[INFO]": chalk.blue(level),
16
- "[WARN]": chalk.yellow(level),
17
- "[ERROR]": chalk.red(level),
18
- "[DEBUG]": chalk.gray(level)
19
- };
20
- return colors[level] || level;
69
+ function formatTimestamp(option, date = /* @__PURE__ */ new Date()) {
70
+ if (typeof option === "function") {
71
+ return option(date);
72
+ }
73
+ const preset = TIMESTAMP_PRESETS[option];
74
+ return preset(date);
21
75
  }
22
- function getDiscordColor(level) {
23
- const colors = {
24
- debug: 9807270,
25
- info: 3447003,
26
- warn: 15965202,
27
- error: 15158332
76
+ function formatJson(entry) {
77
+ const message = entry.args.map((arg) => {
78
+ if (typeof arg === "string") return arg;
79
+ try {
80
+ return JSON.stringify(arg);
81
+ } catch {
82
+ return String(arg);
83
+ }
84
+ }).join(" ");
85
+ const output = {
86
+ level: entry.level,
87
+ timestamp: entry.timestamp,
88
+ message
28
89
  };
29
- return colors[level];
30
- }
31
- function generateId() {
32
- return Math.random().toString(36).substr(2, 8).toUpperCase();
33
- }
34
- function formatLog(level, timestamp, args, options) {
35
- const { formatLog: formatLog2, enableColors = true } = options;
36
- const coloredLevel = getColor(level, enableColors);
37
- if (formatLog2) {
38
- return [formatLog2(coloredLevel, timestamp, args)];
90
+ if (entry.prefix) {
91
+ output.prefix = entry.prefix;
92
+ }
93
+ if (Object.keys(entry.context).length > 0) {
94
+ output.context = entry.context;
39
95
  }
40
- return [`${coloredLevel} ${timestamp}`, ...args];
96
+ return JSON.stringify(output);
97
+ }
98
+ function buildMessage(args) {
99
+ return args.map((arg) => {
100
+ if (typeof arg === "string") return arg;
101
+ try {
102
+ return JSON.stringify(arg);
103
+ } catch {
104
+ return String(arg);
105
+ }
106
+ }).join(" ");
41
107
  }
42
108
 
43
109
  // src/logger.ts
44
- var defaultFormatTimestamp = (types, date = /* @__PURE__ */ new Date()) => [types.ISO, date.toISOString()];
45
- var LOG_LEVEL_PRIORITIES = {
46
- debug: 0,
47
- info: 1,
48
- warn: 2,
49
- error: 3
50
- };
51
- var Logger = class {
110
+ var Logger = class _Logger {
111
+ /**
112
+ * Create a new Logger instance.
113
+ * @param options - Configuration options
114
+ */
52
115
  constructor(options = {}) {
53
- this.discordQueue = [];
54
- this.isProcessing = false;
55
116
  this.options = {
117
+ level: options.level ?? "debug",
118
+ silent: options.silent ?? false,
56
119
  enableColors: options.enableColors ?? true,
57
- formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,
58
- formatLog: options.formatLog,
59
- discord: options.discord
120
+ timestamp: options.timestamp ?? "iso",
121
+ formatter: options.formatter,
122
+ json: options.json ?? false,
123
+ transports: [...options.transports ?? []],
124
+ prefix: options.prefix,
125
+ context: { ...options.context ?? {} }
60
126
  };
61
- this.level = options.level ?? "debug";
127
+ this.transports = this.options.transports;
128
+ this.prefix = this.options.prefix;
129
+ this.context = this.options.context;
62
130
  }
131
+ // ============================================================================
132
+ // Public Log Methods
133
+ // ============================================================================
63
134
  /**
64
- * Sets the minimum log level for filtering messages.
65
- * @param level - The log level to set.
135
+ * Log a trace message (most verbose).
136
+ * @param args - Arguments to log
137
+ */
138
+ trace(...args) {
139
+ this.log("trace", args);
140
+ }
141
+ /**
142
+ * Log a debug message.
143
+ * @param args - Arguments to log
144
+ */
145
+ debug(...args) {
146
+ this.log("debug", args);
147
+ }
148
+ /**
149
+ * Log an info message.
150
+ * @param args - Arguments to log
151
+ */
152
+ info(...args) {
153
+ this.log("info", args);
154
+ }
155
+ /**
156
+ * Log a warning message.
157
+ * @param args - Arguments to log
158
+ */
159
+ warn(...args) {
160
+ this.log("warn", args);
161
+ }
162
+ /**
163
+ * Log an error message.
164
+ * @param args - Arguments to log
165
+ */
166
+ error(...args) {
167
+ this.log("error", args);
168
+ }
169
+ /**
170
+ * Log a fatal message (most severe).
171
+ * @param args - Arguments to log
172
+ */
173
+ fatal(...args) {
174
+ this.log("fatal", args);
175
+ }
176
+ // ============================================================================
177
+ // Level Management
178
+ // ============================================================================
179
+ /**
180
+ * Set the minimum log level.
181
+ * @param level - The log level to set
66
182
  */
67
183
  setLevel(level) {
68
- this.level = level;
184
+ this.options.level = level;
69
185
  }
70
186
  /**
71
- * Sends a log message to Discord via webhook if configured.
72
- * @param level - The log level.
73
- * @param timestamp - The formatted timestamp.
74
- * @param args - The log arguments.
187
+ * Get the current log level.
188
+ * @returns The current log level
75
189
  */
76
- sendToDiscord(level, timestamp, args) {
77
- const discord = this.options.discord;
78
- if (!discord?.enable) return;
79
- try {
80
- new URL(discord.webhookURL);
81
- } catch {
82
- return;
83
- }
84
- const message = args.map((arg) => typeof arg === "string" ? arg : JSON.stringify(arg)).join(" ");
85
- const title = `${level.toUpperCase()}-${generateId()}`;
86
- const embed = discord.formatEmbed ? discord.formatEmbed(level, timestamp, message) : {
87
- title,
88
- description: message,
89
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
90
- color: getDiscordColor(level)
91
- };
92
- this.discordQueue.push({ embed, retryCount: 0 });
93
- if (!this.isProcessing) {
94
- this.isProcessing = true;
95
- setTimeout(() => this.processQueue(), 0);
96
- }
190
+ getLevel() {
191
+ return this.options.level;
97
192
  }
193
+ // ============================================================================
194
+ // Transport Management
195
+ // ============================================================================
98
196
  /**
99
- * Processes the Discord queue by sending batches of embeds.
197
+ * Add a transport to the logger.
198
+ * @param transport - The transport to add
100
199
  */
101
- processQueue() {
102
- if (this.discordQueue.length === 0) {
103
- this.isProcessing = false;
104
- return;
200
+ addTransport(transport) {
201
+ this.transports.push(transport);
202
+ }
203
+ /**
204
+ * Remove a transport from the logger.
205
+ * @param transport - The transport to remove
206
+ */
207
+ removeTransport(transport) {
208
+ const index = this.transports.indexOf(transport);
209
+ if (index !== -1) {
210
+ this.transports.splice(index, 1);
105
211
  }
106
- this.isProcessing = true;
107
- const discord = this.options.discord;
108
- const batchSize = discord.batchSize ?? 10;
109
- const batch = this.discordQueue.splice(0, batchSize);
110
- this.sendBatch(batch.map((item) => item.embed)).then(() => {
111
- const delay = discord.batchDelay ?? 2e3;
112
- this.processTimeout = setTimeout(() => this.processQueue(), delay);
113
- }).catch(() => {
114
- const maxRetries = discord.maxRetries ?? 3;
115
- const retryItems = batch.filter((item) => item.retryCount < maxRetries).map((item) => ({
116
- ...item,
117
- retryCount: item.retryCount + 1
118
- }));
119
- this.discordQueue.unshift(...retryItems);
120
- const retryDelayBase = discord.retryDelayBase ?? 1e3;
121
- const delay = retryDelayBase * Math.pow(2, batch[0]?.retryCount ?? 0);
122
- this.processTimeout = setTimeout(() => this.processQueue(), delay);
123
- });
124
212
  }
213
+ // ============================================================================
214
+ // Child Logger
215
+ // ============================================================================
125
216
  /**
126
- * Sends a batch of embeds to Discord.
127
- * @param embeds - The embeds to send.
217
+ * Create a child logger with additional prefix and context.
218
+ * @param options - Child logger options
219
+ * @returns A new Logger instance
128
220
  */
129
- async sendBatch(embeds) {
130
- const discord = this.options.discord;
131
- await fetch(discord.webhookURL, {
132
- method: "POST",
133
- headers: { "Content-Type": "application/json" },
134
- body: JSON.stringify({ embeds })
221
+ child(options = {}) {
222
+ const combinedPrefix = options.prefix ? this.prefix ? `${this.prefix}:${options.prefix}` : options.prefix : this.prefix;
223
+ const combinedContext = {
224
+ ...this.context,
225
+ ...options.context ?? {}
226
+ };
227
+ return new _Logger({
228
+ level: options.level ?? this.options.level,
229
+ silent: options.silent ?? this.options.silent,
230
+ enableColors: this.options.enableColors,
231
+ timestamp: this.options.timestamp,
232
+ formatter: this.options.formatter,
233
+ json: this.options.json,
234
+ transports: this.transports.slice(),
235
+ prefix: combinedPrefix,
236
+ context: combinedContext
135
237
  });
136
238
  }
239
+ // ============================================================================
240
+ // Cleanup
241
+ // ============================================================================
137
242
  /**
138
- * Checks if a log level should be output based on the current log level.
139
- * @param level - The log level to check.
140
- * @returns True if the message should be logged.
243
+ * Destroy the logger and all its transports.
244
+ * Calls destroy() on all registered transports.
141
245
  */
142
- shouldLog(level) {
143
- return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];
246
+ async destroy() {
247
+ const destroyPromises = this.transports.map(async (transport) => {
248
+ if (typeof transport.destroy === "function") {
249
+ await transport.destroy();
250
+ }
251
+ });
252
+ await Promise.all(destroyPromises);
253
+ this.transports.length = 0;
144
254
  }
255
+ // ============================================================================
256
+ // Private Methods
257
+ // ============================================================================
145
258
  /**
146
- * Logs an info message.
147
- * @param args - The arguments to log.
259
+ * Core logging method - all public methods delegate here.
260
+ * @param level - The log level
261
+ * @param args - The arguments to log
148
262
  */
149
- info(...args) {
150
- if (!this.shouldLog("info")) return;
151
- const timestamp = formatTimestamp(
152
- this.options.formatTimestamp,
153
- TIMESTAMP_TYPES
154
- );
155
- console.log(...formatLog("[INFO]", timestamp, args, this.options));
156
- this.sendToDiscord("info", timestamp, args);
263
+ log(level, args) {
264
+ if (!this.shouldLog(level)) return;
265
+ const entry = {
266
+ level,
267
+ timestamp: formatTimestamp(this.options.timestamp),
268
+ args,
269
+ prefix: this.prefix,
270
+ context: this.context
271
+ };
272
+ if (!this.options.silent) {
273
+ this.writeToConsole(level, entry);
274
+ }
275
+ for (const transport of this.transports) {
276
+ this.dispatchToTransport(transport, entry);
277
+ }
157
278
  }
158
279
  /**
159
- * Logs a warning message.
160
- * @param args - The arguments to log.
280
+ * Write a log entry to the console.
281
+ * @param level - The log level
282
+ * @param entry - The log entry
161
283
  */
162
- warn(...args) {
163
- if (!this.shouldLog("warn")) return;
164
- const timestamp = formatTimestamp(
165
- this.options.formatTimestamp,
166
- TIMESTAMP_TYPES
167
- );
168
- console.log(...formatLog("[WARN]", timestamp, args, this.options));
169
- this.sendToDiscord("warn", timestamp, args);
284
+ writeToConsole(level, entry) {
285
+ const method = CONSOLE_METHODS[level];
286
+ if (this.options.formatter) {
287
+ console[method](this.options.formatter(entry));
288
+ return;
289
+ }
290
+ if (this.options.json) {
291
+ console[method](formatJson(entry));
292
+ return;
293
+ }
294
+ const label = getColoredLabel(entry.level, this.options.enableColors);
295
+ const prefixStr = entry.prefix ? ` [${entry.prefix}]` : "";
296
+ const message = buildMessage(entry.args);
297
+ console[method](`${label} ${entry.timestamp}${prefixStr}`, message);
170
298
  }
171
299
  /**
172
- * Logs an error message.
173
- * @param args - The arguments to log.
300
+ * Dispatch a log entry to a transport.
301
+ * @param transport - The transport
302
+ * @param entry - The log entry
174
303
  */
175
- error(...args) {
176
- if (!this.shouldLog("error")) return;
177
- const timestamp = formatTimestamp(
178
- this.options.formatTimestamp,
179
- TIMESTAMP_TYPES
180
- );
181
- console.log(...formatLog("[ERROR]", timestamp, args, this.options));
182
- this.sendToDiscord("error", timestamp, args);
304
+ dispatchToTransport(transport, entry) {
305
+ try {
306
+ const result = transport.log(entry);
307
+ if (result instanceof Promise) {
308
+ result.catch(() => {
309
+ });
310
+ }
311
+ } catch {
312
+ }
183
313
  }
184
314
  /**
185
- * Logs a debug message.
186
- * @param args - The arguments to log.
315
+ * Check if a log level should be output.
316
+ * @param level - The log level to check
317
+ * @returns True if the message should be logged
187
318
  */
188
- debug(...args) {
189
- if (!this.shouldLog("debug")) return;
190
- const timestamp = formatTimestamp(
191
- this.options.formatTimestamp,
192
- TIMESTAMP_TYPES
193
- );
194
- console.log(...formatLog("[DEBUG]", timestamp, args, this.options));
195
- this.sendToDiscord("debug", timestamp, args);
319
+ shouldLog(level) {
320
+ return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.options.level];
196
321
  }
197
322
  };
198
323
  export {
199
- Logger,
200
- TIMESTAMP_TYPES
324
+ LEVEL_LABELS,
325
+ LOG_LEVEL_PRIORITIES,
326
+ Logger
201
327
  };
package/package.json CHANGED
@@ -1,14 +1,20 @@
1
1
  {
2
2
  "name": "@feizk/logger",
3
- "version": "1.7.0",
4
- "description": "A simple logger package with colored outputs and timestamps",
5
- "main": "dist/index.js",
3
+ "version": "2.0.0",
4
+ "description": "A lightweight, pluggable logger with colored outputs, structured logging, and transport support",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
6
7
  "types": "dist/index.d.ts",
7
8
  "publishConfig": {
8
9
  "access": "public"
9
10
  },
10
- "dependencies": {
11
- "chalk": "^5.3.0"
11
+ "exports": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ },
16
+ "engines": {
17
+ "node": ">=18"
12
18
  },
13
19
  "devDependencies": {
14
20
  "@types/node": "^20.0.0",
@@ -22,7 +28,9 @@
22
28
  "logger",
23
29
  "console",
24
30
  "colors",
25
- "timestamps"
31
+ "timestamps",
32
+ "structured-logging",
33
+ "transports"
26
34
  ],
27
35
  "author": "feizk",
28
36
  "license": "MIT",