@aomex/logger 3.30.7 → 3.30.8-alpha.131cf1c.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.js CHANGED
@@ -1,196 +1,562 @@
1
+ import { I18n, Service, createI18n } from "@aomex/common";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import timers from "node:timers/promises";
4
+ import { stripVTControlCharacters, styleText } from "node:util";
5
+ import { dirname, normalize } from "node:path";
6
+ import { appendFile, mkdir } from "node:fs/promises";
7
+ // src/types.ts
8
+ /**
9
+ * 标准日志等级(低 → 高)。选用约定:
10
+ * - `trace`:极细诊断(逐步追踪、协议帧、循环内细节);生产建议在 transport 上门禁关掉
11
+ * - `debug`:开发调试(关键变量、分支走向);生产建议在 transport 上门禁关掉
12
+ * - `info`:正常业务事件(启动、请求完成、任务成功)
13
+ * - `warn`:可恢复异常或需关注的降级(重试、兜底、配置不当)
14
+ * - `error`:请求/任务失败,服务仍可继续(未处理异常、下游失败)
15
+ * - `fatal`:进程级致命错误,随后通常应退出(启动失败、数据损坏)
16
+ *
17
+ * 框架不会按 `NODE_ENV` 自动过滤;未配 `TransportEntry.level` 时六级全开。
18
+ */
19
+ const LOGGER_LEVELS = [
20
+ "trace",
21
+ "debug",
22
+ "info",
23
+ "warn",
24
+ "error",
25
+ "fatal"
26
+ ];
27
+ // src/base-logger-service.ts
28
+ var BaseLoggerService = class extends Service {
29
+ logs = [];
30
+ transportGates = [];
31
+ timer;
32
+ readyPromise;
33
+ bindingsStorage = new AsyncLocalStorage();
34
+ async onInit() {
35
+ await this.ensureReady();
36
+ }
37
+ async onDestroy() {
38
+ await this.flush();
39
+ await Promise.all(this.transportGates.filter((gate) => !gate.disabled).map(({ transport }) => transport.onDestroy()));
40
+ }
41
+ /** 等待内存队列输送完毕,并 flush 各 transport 内部缓冲 */
42
+ async flush() {
43
+ await this.ensureReady();
44
+ while (this.timer || this.logs.length) await timers.setTimeout(50);
45
+ await Promise.all(this.transportGates.filter((gate) => !gate.disabled).map(({ transport }) => transport.flush()));
46
+ }
47
+ /**
48
+ * 极细诊断(逐步追踪、协议细节等)。仅文案;异常请用 `warn` / `error` / `fatal`。
49
+ * 生产是否输出取决于 transport 的 `level` 门禁(框架不按 `NODE_ENV` 自动关)。
50
+ */
51
+ trace(message) {
52
+ this.write("trace", message);
53
+ }
54
+ /**
55
+ * 开发调试(关键变量、分支走向)。仅文案;异常请用 `warn` / `error` / `fatal`。
56
+ * 生产是否输出取决于 transport 的 `level` 门禁(框架不按 `NODE_ENV` 自动关)。
57
+ */
58
+ debug(message) {
59
+ this.write("debug", message);
60
+ }
61
+ /**
62
+ * 正常业务事件(启动就绪、请求/任务成功等)。仅文案;异常请用 `warn` / `error` / `fatal`。
63
+ */
64
+ info(message) {
65
+ this.write("info", message);
66
+ }
67
+ warn(messageOrError, message) {
68
+ this.write("warn", messageOrError, message);
69
+ }
70
+ error(messageOrError, message) {
71
+ this.write("error", messageOrError, message);
72
+ }
73
+ fatal(messageOrError, message) {
74
+ this.write("fatal", messageOrError, message);
75
+ }
76
+ /**
77
+ * 在异步上下文中挂上 `bindings`,回调内(含 `await`)写出的日志都会带上这些字段。
78
+ * 嵌套 `withBindings` 时与外层合并,同名键由内层覆盖。始终返回 `Promise`。
79
+ *
80
+ * ```typescript
81
+ * await logger.withBindings({ requestId: 'req-1' }, async () => {
82
+ * logger.info('ok');
83
+ * });
84
+ * ```
85
+ */
86
+ async withBindings(bindings, callback) {
87
+ const parent = this.bindingsStorage.getStore();
88
+ const merged = parent ? {
89
+ ...parent,
90
+ ...bindings
91
+ } : { ...bindings };
92
+ return this.bindingsStorage.run(merged, callback);
93
+ }
94
+ /** 当前异步上下文中的 bindings(浅拷贝);无上下文时为空对象 */
95
+ bindings() {
96
+ return { ...this.bindingsStorage.getStore() ?? {} };
97
+ }
98
+ /**
99
+ * 写入一条日志。子类自定义方法时可复用。
100
+ *
101
+ * - `write('info', 'hello')`
102
+ * - `write('warn', err)` / `write('error', err)` — `err` 为 `unknown`(含 `catch` 值)
103
+ * - `write('error', err, 'checkout failed')`
104
+ */
105
+ write(level, messageOrError, message) {
106
+ const normalized = this.normalizeLogArgs(messageOrError, message);
107
+ const store = this.bindingsStorage.getStore();
108
+ const bindings = store != null && Object.keys(store).length > 0 ? { ...store } : void 0;
109
+ this.logs.push({
110
+ timestamp: /* @__PURE__ */ new Date(),
111
+ level,
112
+ message: normalized.message,
113
+ ...normalized.exception ? { exception: normalized.exception } : {},
114
+ ...bindings ? { bindings } : {}
115
+ });
116
+ this.timer ||= setTimeout(async () => {
117
+ try {
118
+ await this.consume();
119
+ } finally {
120
+ this.timer = void 0;
121
+ }
122
+ });
123
+ }
124
+ /**
125
+ * 将任意抛出值序列化为 `exception` 字段(`Error` 走完整 stack/cause,其它值降级)。
126
+ */
127
+ serializeUnknown(value, seen = /* @__PURE__ */ new WeakSet()) {
128
+ if (Error.isError(value)) {
129
+ if (seen.has(value)) return {
130
+ type: value.name || "Error",
131
+ message: "[Circular]"
132
+ };
133
+ seen.add(value);
134
+ const out = {
135
+ type: value.name || "Error",
136
+ message: value.message
137
+ };
138
+ if (value.stack) out.stack = value.stack;
139
+ if (value.cause !== void 0) out.cause = this.serializeUnknown(value.cause, seen);
140
+ return out;
141
+ }
142
+ if (typeof value === "string") return {
143
+ type: "string",
144
+ message: value
145
+ };
146
+ if (typeof value === "object" && value !== null) {
147
+ if (seen.has(value)) return {
148
+ type: "Object",
149
+ message: "[Circular]"
150
+ };
151
+ seen.add(value);
152
+ const type = value.constructor?.name || "Object";
153
+ let message;
154
+ try {
155
+ message = JSON.stringify(value) ?? String(value);
156
+ } catch {
157
+ message = Object.prototype.toString.call(value);
158
+ }
159
+ return {
160
+ type,
161
+ message
162
+ };
163
+ }
164
+ if (value === void 0) return {
165
+ type: "undefined",
166
+ message: "undefined"
167
+ };
168
+ if (value === null) return {
169
+ type: "null",
170
+ message: "null"
171
+ };
172
+ return {
173
+ type: typeof value,
174
+ message: String(value)
175
+ };
176
+ }
177
+ /** `Error` 专用入口,等价于 `serializeUnknown(err)` */
178
+ serializeError(err, seen = /* @__PURE__ */ new WeakSet()) {
179
+ return this.serializeUnknown(err, seen);
180
+ }
181
+ /**
182
+ * - 仅传 `string` → 普通文案,不挂 `exception`
183
+ * - 传 `unknown`(可再跟 message)→ 序列化到 `exception`
184
+ */
185
+ normalizeLogArgs(messageOrError, message) {
186
+ if (typeof messageOrError === "string" && message === void 0) return { message: messageOrError };
187
+ const exception = this.serializeUnknown(messageOrError);
188
+ return {
189
+ message: message ?? exception.message,
190
+ exception
191
+ };
192
+ }
193
+ /** 将 gate 解析为闭区间下标 */
194
+ resolveLevelGate(gate) {
195
+ if (gate == null) return {
196
+ minIndex: 0,
197
+ maxIndex: LOGGER_LEVELS.length - 1
198
+ };
199
+ if (typeof gate === "string") return {
200
+ minIndex: LOGGER_LEVELS.indexOf(gate),
201
+ maxIndex: LOGGER_LEVELS.length - 1
202
+ };
203
+ return {
204
+ minIndex: gate.min ? LOGGER_LEVELS.indexOf(gate.min) : 0,
205
+ maxIndex: gate.max ? LOGGER_LEVELS.indexOf(gate.max) : LOGGER_LEVELS.length - 1
206
+ };
207
+ }
208
+ /** 判断某等级是否落在 gate 闭区间内 */
209
+ isLevelEnabled(level, gate) {
210
+ const index = LOGGER_LEVELS.indexOf(level);
211
+ const { minIndex, maxIndex } = this.resolveLevelGate(gate);
212
+ return index >= minIndex && index <= maxIndex;
213
+ }
214
+ /**
215
+ * 创建 transports 并等待各自 `onInit`。可重入,只执行一次。
216
+ */
217
+ ensureReady() {
218
+ this.readyPromise ??= (async () => {
219
+ this.transportGates = this.createTransports().map(({ transport, level, disabled }) => ({
220
+ transport,
221
+ level,
222
+ disabled: disabled === true
223
+ }));
224
+ await Promise.all(this.transportGates.filter((gate) => !gate.disabled).map(({ transport }) => transport.onInit()));
225
+ })();
226
+ return this.readyPromise;
227
+ }
228
+ async consume() {
229
+ await this.ensureReady();
230
+ let log = this.logs.shift();
231
+ while (log) {
232
+ const results = await Promise.allSettled(this.transportGates.map(async ({ transport, level, disabled }) => {
233
+ if (disabled) return;
234
+ if (this.isLevelEnabled(log.level, level)) await transport.consume(log);
235
+ }));
236
+ for (let i = 0; i < results.length; i++) {
237
+ const result = results[i];
238
+ if (result.status !== "rejected") continue;
239
+ const err = result.reason;
240
+ const detail = Error.isError(err) ? err.stack ?? err.message : String(err);
241
+ console.error(`[aomex/logger] transport ${this.transportGates[i].transport.constructor.name} consume failed: ${detail}`);
242
+ }
243
+ log = this.logs.shift();
244
+ }
245
+ }
246
+ };
1
247
  // src/transports/transport.ts
2
248
  var Transport = class {
3
- /**
4
- * 解析日期。返回 年、月、日、时、分、秒
5
- */
6
- dateToJSON(date) {
7
- return {
8
- year: date.getFullYear().toString(),
9
- month: (date.getMonth() + 1).toString().padStart(2, "0"),
10
- day: date.getDate().toString().padStart(2, "0"),
11
- hour: date.getHours().toString().padStart(2, "0"),
12
- minute: date.getMinutes().toString().padStart(2, "0"),
13
- second: date.getSeconds().toString().padStart(2, "0")
14
- };
15
- }
16
- /**
17
- * 时间字符串:`年-月-日 时:分:秒`
18
- */
19
- dateToString(date) {
20
- const parsed = this.dateToJSON(date);
21
- return `${parsed.year}-${parsed.month}-${parsed.day} ${parsed.hour}:${parsed.minute}:${parsed.second}`;
22
- }
249
+ /**
250
+ * 异步初始化。`BaseLoggerService` 在首次投递 / 服务 `onInit` 时会等待全部 transport 完成。
251
+ * 默认无操作。
252
+ */
253
+ async onInit() {}
254
+ /**
255
+ * 刷出 transport 内部缓冲(若有)。默认无操作。
256
+ */
257
+ async flush() {}
258
+ /**
259
+ * 异步销毁。服务 `onDestroy` 在 `flush` 之后会等待全部 transport 完成。
260
+ * 默认无操作。
261
+ */
262
+ async onDestroy() {}
263
+ /**
264
+ * 解析日期。返回 年、月、日、时、分、秒
265
+ */
266
+ dateToJSON(date) {
267
+ return {
268
+ year: date.getFullYear().toString(),
269
+ month: (date.getMonth() + 1).toString().padStart(2, "0"),
270
+ day: date.getDate().toString().padStart(2, "0"),
271
+ hour: date.getHours().toString().padStart(2, "0"),
272
+ minute: date.getMinutes().toString().padStart(2, "0"),
273
+ second: date.getSeconds().toString().padStart(2, "0")
274
+ };
275
+ }
276
+ /**
277
+ * 时间字符串:`年-月-日 时:分:秒`
278
+ */
279
+ dateToString(date) {
280
+ const parsed = this.dateToJSON(date);
281
+ return `${parsed.year}-${parsed.month}-${parsed.day} ${parsed.hour}:${parsed.minute}:${parsed.second}`;
282
+ }
283
+ /**
284
+ * 格式化单条日志。
285
+ * - `text`:`[level] time message`,有 `bindings` / `exception` 时追加
286
+ * - `json`:NDJSON(`time` / `level` / `message`,可选 `exception` / `bindings`)
287
+ */
288
+ formatLog(log, format = "text") {
289
+ if (format === "json") return JSON.stringify({
290
+ time: log.timestamp.toISOString(),
291
+ level: log.level,
292
+ message: log.message,
293
+ ...log.exception ? { exception: log.exception } : {},
294
+ ...log.bindings ? { bindings: log.bindings } : {}
295
+ });
296
+ let line = `[${log.level}] ${this.dateToString(log.timestamp)} ${log.message}`;
297
+ if (log.bindings) line += ` ${JSON.stringify(log.bindings)}`;
298
+ if (log.exception?.stack) line += `\n${log.exception.stack}`;
299
+ else if (log.exception) line += `\n${log.exception.type}: ${log.exception.message}`;
300
+ return line;
301
+ }
23
302
  };
24
-
25
303
  // src/transports/custom-transport.ts
304
+ /**
305
+ * 自定义消费逻辑;`this` 绑定为 Transport,可复用 `formatLog` / `dateToString`。
306
+ *
307
+ * ```typescript
308
+ * new CustomTransport({
309
+ * consume(log) {
310
+ * // 例如推到自建队列、写数据库等
311
+ * console.log(this.formatLog(log, 'json'));
312
+ * },
313
+ * });
314
+ * ```
315
+ */
26
316
  var CustomTransport = class extends Transport {
27
- consumeHandle;
28
- constructor(opts) {
29
- super();
30
- this.consumeHandle = opts.consume.bind(this);
31
- }
32
- async consume(log) {
33
- return this.consumeHandle(log);
34
- }
317
+ consumeHandle;
318
+ constructor(opts) {
319
+ super();
320
+ this.consumeHandle = opts.consume;
321
+ }
322
+ async consume(log) {
323
+ await this.consumeHandle.call(this, log);
324
+ }
35
325
  };
36
-
37
326
  // src/transports/console-transport.ts
38
- import { styleText } from "util";
327
+ /** 默认等级配色 */
328
+ const DEFAULT_LEVEL_COLORS = {
329
+ trace: "gray",
330
+ debug: "blueBright",
331
+ info: "green",
332
+ warn: "yellow",
333
+ error: "red",
334
+ fatal: "magentaBright"
335
+ };
336
+ const DEFAULT_STDERR_LEVELS = ["error", "fatal"];
39
337
  var ConsoleTransport = class extends Transport {
40
- colors;
41
- writer;
42
- constructor(opts = {}) {
43
- super();
44
- this.colors = opts.colors || {};
45
- this.writer = opts.output || process.stdout;
46
- }
47
- async consume(log) {
48
- const color = this.colors[log.level];
49
- const time = this.dateToString(log.timestamp);
50
- const level = `[${log.level}]`;
51
- this.writer.write(
52
- `${color ? styleText(color, level) : level} ${color ? styleText(color, time) : time} ${log.content}
53
- `
54
- );
55
- }
338
+ format;
339
+ colorize;
340
+ colors;
341
+ stdout;
342
+ stderr;
343
+ stderrLevelSet;
344
+ /** 若构造时显式传入 `output`,则所有等级走同一流 */
345
+ forcedOutput;
346
+ constructor(opts = {}) {
347
+ super();
348
+ this.format = opts.format ?? "text";
349
+ this.stdout = opts.stdout ?? process.stdout;
350
+ this.stderr = opts.stderr ?? process.stderr;
351
+ this.forcedOutput = opts.output;
352
+ this.colors = {
353
+ ...DEFAULT_LEVEL_COLORS,
354
+ ...opts.colors
355
+ };
356
+ this.stderrLevelSet = new Set(opts.stderrLevels ?? DEFAULT_STDERR_LEVELS);
357
+ const primary = this.forcedOutput ?? this.stdout;
358
+ this.colorize = opts.colorize ?? (this.format === "text" && primary.isTTY === true);
359
+ }
360
+ async consume(log) {
361
+ this.resolveWriter(log.level).write(this.render(log) + "\n");
362
+ }
363
+ resolveWriter(level) {
364
+ if (this.forcedOutput) return this.forcedOutput;
365
+ return this.stderrLevelSet.has(level) ? this.stderr : this.stdout;
366
+ }
367
+ render(log) {
368
+ if (this.format === "json" || !this.colorize) return this.formatLog(log, this.format);
369
+ const color = this.colors[log.level];
370
+ const time = this.dateToString(log.timestamp);
371
+ const level = `[${log.level}]`;
372
+ const bindings = log.bindings != null ? ` ${JSON.stringify(log.bindings)}` : "";
373
+ const head = color ? `${styleText(color, level)} ${styleText(color, time)} ${log.message}${bindings}` : `${level} ${time} ${log.message}${bindings}`;
374
+ if (log.exception?.stack) return `${head}\n${log.exception.stack}`;
375
+ if (log.exception) return `${head}\n${log.exception.type}: ${log.exception.message}`;
376
+ return head;
377
+ }
56
378
  };
57
-
379
+ // src/i18n/locales/zh-cn.ts
380
+ const zh = I18n.define({
381
+ invalid_log_file_path: "日志文件路径不合法",
382
+ webhook_request_timed_out: "Webhook 请求超时",
383
+ webhook_request_failed: "Webhook 请求失败({{status}} {{statusText}})"
384
+ });
385
+ // src/i18n/locales/en-us.ts
386
+ const en = I18n.satisfies(zh).define({
387
+ invalid_log_file_path: "Invalid log file path",
388
+ webhook_request_timed_out: "Webhook request timed out",
389
+ webhook_request_failed: "Webhook request failed ({{status}} {{statusText}})"
390
+ });
391
+ // src/i18n/index.ts
392
+ const i18n = createI18n({
393
+ zh,
394
+ en,
395
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
396
+ });
58
397
  // src/transports/file-transport.ts
59
- import { dirname } from "path";
60
- import { stripVTControlCharacters } from "util";
61
- import { appendFile, mkdir } from "fs/promises";
398
+ /**
399
+ * 追加写入本地日志文件;目录不存在时自动创建。
400
+ *
401
+ * ```typescript
402
+ * // 使用默认路径:./logs/{year}-{month}-{day}/{level}.log
403
+ * new FileTransport();
404
+ *
405
+ * new FileTransport({
406
+ * file: './logs/app.log',
407
+ * format: 'json',
408
+ * });
409
+ *
410
+ * new FileTransport({
411
+ * file: (log) => `./logs/${log.level}.log`,
412
+ * });
413
+ * ```
414
+ */
62
415
  var FileTransport = class extends Transport {
63
- file;
64
- fileMode;
65
- dirMode;
66
- constructor(opts) {
67
- super();
68
- this.file = opts.file;
69
- this.fileMode = opts.fileMode;
70
- this.dirMode = opts.dirMode;
71
- }
72
- async consume(log) {
73
- let file;
74
- if (typeof this.file === "function") {
75
- file = this.file(log);
76
- } else {
77
- file = this.file;
78
- for (const [key, value] of Object.entries(this.dateToJSON(log.timestamp))) {
79
- file = file.replaceAll(`{${key}}`, value);
80
- }
81
- }
82
- await mkdir(dirname(file), { recursive: true, mode: this.dirMode });
83
- await appendFile(file, this.getContent(log), { mode: this.fileMode });
84
- }
85
- getContent(log) {
86
- return `
87
- [${log.level}] ${this.dateToString(log.timestamp)} ${stripVTControlCharacters(log.content)}
88
- `;
89
- }
416
+ file;
417
+ fileMode;
418
+ dirMode;
419
+ format;
420
+ ensuredDirs = /* @__PURE__ */ new Set();
421
+ constructor(opts = {}) {
422
+ super();
423
+ this.file = opts.file ?? "./logs/{year}-{month}-{day}/{level}.log";
424
+ this.format = opts.format ?? "text";
425
+ this.fileMode = opts.fileMode;
426
+ this.dirMode = opts.dirMode;
427
+ }
428
+ async consume(log) {
429
+ const file = this.resolveFilePath(log);
430
+ const dir = dirname(file);
431
+ if (!this.ensuredDirs.has(dir)) {
432
+ await mkdir(dir, {
433
+ recursive: true,
434
+ mode: this.dirMode
435
+ });
436
+ this.ensuredDirs.add(dir);
437
+ }
438
+ await appendFile(file, this.getContent(log), { mode: this.fileMode });
439
+ }
440
+ resolveFilePath(log) {
441
+ let file;
442
+ if (typeof this.file === "function") file = this.file(log);
443
+ else {
444
+ file = this.file;
445
+ for (const [key, value] of Object.entries(this.dateToJSON(log.timestamp))) file = file.replaceAll(`{${key}}`, value);
446
+ file = file.replaceAll("{level}", log.level);
447
+ }
448
+ if (!file || file.includes("\0")) throw new Error(i18n.t("invalid_log_file_path"));
449
+ return normalize(file);
450
+ }
451
+ getContent(log) {
452
+ if (this.format === "json") return `${this.formatLog(log, "json")}\n`;
453
+ const plain = {
454
+ ...log,
455
+ message: stripVTControlCharacters(log.message)
456
+ };
457
+ return `${this.formatLog(plain, "text")}\n`;
458
+ }
90
459
  };
91
-
92
- // src/transports/index.ts
93
- var transports = {
94
- File: FileTransport,
95
- Console: ConsoleTransport,
96
- Custom: CustomTransport
97
- };
98
-
99
- // src/logger.ts
100
- import timers from "timers/promises";
101
- var Logger = class _Logger {
102
- static transports = transports;
103
- static create = (opts) => {
104
- return new _Logger(opts);
105
- };
106
- levels;
107
- logs = [];
108
- transportAndLevels;
109
- timer;
110
- transports;
111
- constructor(opts) {
112
- this.levels = opts.levels;
113
- this.transportAndLevels = (opts.transports || []).map(({ transport, level }) => {
114
- return {
115
- transport,
116
- levels: this.transformLevel(level)
117
- };
118
- });
119
- this.levels.forEach((level) => {
120
- Object.defineProperty(this, level, {
121
- value: this.log.bind(this, level)
122
- });
123
- });
124
- this.transports = {
125
- add: (opts2) => {
126
- this.transportAndLevels.push({
127
- transport: opts2.transport,
128
- levels: this.transformLevel(opts2.level)
129
- });
130
- },
131
- remove: (strip) => {
132
- this.transportAndLevels = this.transportAndLevels.filter(
133
- ({ transport, levels }) => {
134
- return !strip(transport, levels);
135
- }
136
- );
137
- },
138
- count: (level) => {
139
- let counter = 0;
140
- for (const { levels } of this.transportAndLevels) {
141
- if (levels.includes(level)) ++counter;
142
- }
143
- return counter;
144
- }
145
- };
146
- }
147
- /**
148
- * 保证日志(异步)输送完毕
149
- */
150
- async complete() {
151
- while (true) {
152
- if (!this.timer) return;
153
- if (!this.logs.length) return;
154
- await timers.setTimeout(50);
155
- }
156
- }
157
- log(level, content) {
158
- this.logs.push({
159
- timestamp: /* @__PURE__ */ new Date(),
160
- content,
161
- level
162
- });
163
- this.timer ||= setTimeout(async () => {
164
- await this.consume();
165
- this.timer = void 0;
166
- });
167
- }
168
- async consume() {
169
- let log = this.logs.shift();
170
- while (log) {
171
- const targetLevel = log.level;
172
- await Promise.all(
173
- this.transportAndLevels.map(async ({ transport, levels }) => {
174
- if (levels.includes(targetLevel)) {
175
- await transport.consume(log);
176
- }
177
- })
178
- );
179
- log = this.logs.shift();
180
- }
181
- }
182
- transformLevel(level) {
183
- if (typeof level !== "object") {
184
- return level === "all" ? [...this.levels] : [];
185
- }
186
- if (Array.isArray(level)) return [...new Set(level)];
187
- const min = level.from ? this.levels.findIndex((l) => l === level.from) : 0;
188
- const max = level.to ? this.levels.findIndex((l) => l === level.to) + 1 : this.levels.length;
189
- return this.levels.slice(min, max);
190
- }
460
+ // src/transports/stream-transport.ts
461
+ /**
462
+ * 写入任意 Writable 流。
463
+ *
464
+ * ```typescript
465
+ * import { PassThrough } from 'node:stream';
466
+ *
467
+ * new StreamTransport({
468
+ * stream: process.stdout,
469
+ * format: 'json',
470
+ * });
471
+ *
472
+ * const sink = new PassThrough();
473
+ * new StreamTransport({ stream: sink });
474
+ * ```
475
+ */
476
+ var StreamTransport = class extends Transport {
477
+ stream;
478
+ format;
479
+ constructor(opts) {
480
+ super();
481
+ this.stream = opts.stream;
482
+ this.format = opts.format ?? "text";
483
+ }
484
+ async consume(log) {
485
+ const line = `${this.formatLog(log, this.format)}\n`;
486
+ await new Promise((resolve, reject) => {
487
+ this.stream.write(line, (err) => {
488
+ if (err) reject(err);
489
+ else resolve();
490
+ });
491
+ });
492
+ }
191
493
  };
192
- export {
193
- Logger,
194
- Transport
494
+ // src/transports/webhook-transport.ts
495
+ /**
496
+ * 通过 HTTP 将日志推送到 Webhook 地址
497
+ *
498
+ * ```typescript
499
+ * new WebhookTransport({
500
+ * url: process.env.ALERT_WEBHOOK_URL!,
501
+ * });
502
+ *
503
+ * new WebhookTransport({
504
+ * url: 'https://example.com/hook',
505
+ * headers: { Authorization: 'Bearer xxx' },
506
+ * format: (log) => JSON.stringify({ text: log.message }),
507
+ * });
508
+ * ```
509
+ */
510
+ var WebhookTransport = class extends Transport {
511
+ url;
512
+ method;
513
+ headers;
514
+ format;
515
+ timeoutMs;
516
+ constructor(opts) {
517
+ super();
518
+ this.url = String(opts.url);
519
+ this.method = opts.method ?? "POST";
520
+ this.headers = opts.headers;
521
+ this.format = opts.format ?? "json";
522
+ this.timeoutMs = opts.timeoutMs ?? 3e4;
523
+ }
524
+ async consume(log) {
525
+ const { body, contentType } = await this.buildBody(log);
526
+ const headers = new Headers(this.headers);
527
+ if (contentType && !headers.has("Content-Type")) headers.set("Content-Type", contentType);
528
+ const controller = new AbortController();
529
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
530
+ try {
531
+ const res = await fetch(this.url, {
532
+ method: this.method,
533
+ headers,
534
+ body,
535
+ signal: controller.signal
536
+ });
537
+ if (!res.ok) throw new Error(i18n.t("webhook_request_failed", {
538
+ status: String(res.status),
539
+ statusText: res.statusText
540
+ }));
541
+ } catch (err) {
542
+ if (Error.isError(err) && err.name === "AbortError") throw new Error(i18n.t("webhook_request_timed_out"));
543
+ throw err;
544
+ } finally {
545
+ clearTimeout(timer);
546
+ }
547
+ }
548
+ async buildBody(log) {
549
+ if (typeof this.format === "function") return { body: await this.format(log) };
550
+ if (this.format === "json") return {
551
+ body: this.formatLog(log, "json"),
552
+ contentType: "application/json"
553
+ };
554
+ return {
555
+ body: this.formatLog(log, "text"),
556
+ contentType: "text/plain;charset=utf-8"
557
+ };
558
+ }
195
559
  };
560
+ export { BaseLoggerService, ConsoleTransport, CustomTransport, FileTransport, LOGGER_LEVELS, StreamTransport, Transport, WebhookTransport };
561
+
196
562
  //# sourceMappingURL=index.js.map