@c9up/spectrum 0.1.18 → 0.1.20

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.
Files changed (85) hide show
  1. package/README.md +33 -7
  2. package/dist/Logger.d.ts +6 -2
  3. package/dist/Logger.d.ts.map +1 -1
  4. package/dist/Logger.js +214 -80
  5. package/dist/Logger.js.map +1 -1
  6. package/dist/LoggerManager.d.ts +5 -0
  7. package/dist/LoggerManager.d.ts.map +1 -1
  8. package/dist/LoggerManager.js +10 -3
  9. package/dist/LoggerManager.js.map +1 -1
  10. package/dist/RustLogBridge.d.ts +27 -2
  11. package/dist/RustLogBridge.d.ts.map +1 -1
  12. package/dist/RustLogBridge.js +45 -31
  13. package/dist/RustLogBridge.js.map +1 -1
  14. package/dist/SpectrumProvider.d.ts +6 -2
  15. package/dist/SpectrumProvider.d.ts.map +1 -1
  16. package/dist/SpectrumProvider.js +18 -12
  17. package/dist/SpectrumProvider.js.map +1 -1
  18. package/dist/channels/ConsoleChannel.d.ts +8 -1
  19. package/dist/channels/ConsoleChannel.d.ts.map +1 -1
  20. package/dist/channels/ConsoleChannel.js +18 -14
  21. package/dist/channels/ConsoleChannel.js.map +1 -1
  22. package/dist/channels/FileChannel.d.ts +32 -9
  23. package/dist/channels/FileChannel.d.ts.map +1 -1
  24. package/dist/channels/FileChannel.js +264 -202
  25. package/dist/channels/FileChannel.js.map +1 -1
  26. package/dist/errors.d.ts +9 -0
  27. package/dist/errors.d.ts.map +1 -0
  28. package/dist/errors.js +13 -0
  29. package/dist/errors.js.map +1 -0
  30. package/dist/index.d.ts +7 -4
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +4 -2
  33. package/dist/index.js.map +1 -1
  34. package/dist/jsonLine.d.ts +49 -0
  35. package/dist/jsonLine.d.ts.map +1 -0
  36. package/dist/jsonLine.js +165 -0
  37. package/dist/jsonLine.js.map +1 -0
  38. package/dist/redact.d.ts +16 -3
  39. package/dist/redact.d.ts.map +1 -1
  40. package/dist/redact.js +121 -10
  41. package/dist/redact.js.map +1 -1
  42. package/dist/sanitize.d.ts +11 -5
  43. package/dist/sanitize.d.ts.map +1 -1
  44. package/dist/sanitize.js +36 -12
  45. package/dist/sanitize.js.map +1 -1
  46. package/dist/services/main.d.ts.map +1 -1
  47. package/dist/services/main.js +12 -1
  48. package/dist/services/main.js.map +1 -1
  49. package/dist/stdSerializers.d.ts +48 -0
  50. package/dist/stdSerializers.d.ts.map +1 -0
  51. package/dist/stdSerializers.js +129 -0
  52. package/dist/stdSerializers.js.map +1 -0
  53. package/dist/stringify.d.ts +33 -0
  54. package/dist/stringify.d.ts.map +1 -0
  55. package/dist/stringify.js +148 -0
  56. package/dist/stringify.js.map +1 -0
  57. package/dist/targets.d.ts +29 -7
  58. package/dist/targets.d.ts.map +1 -1
  59. package/dist/targets.js +130 -31
  60. package/dist/targets.js.map +1 -1
  61. package/dist/testing/FakeLogger.js +20 -5
  62. package/dist/testing/FakeLogger.js.map +1 -1
  63. package/dist/types.d.ts +71 -3
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +21 -3
  66. package/dist/types.js.map +1 -1
  67. package/package.json +1 -1
  68. package/src/Logger.ts +277 -85
  69. package/src/LoggerManager.ts +10 -3
  70. package/src/RustLogBridge.ts +59 -30
  71. package/src/SpectrumProvider.ts +31 -18
  72. package/src/channels/ConsoleChannel.ts +30 -14
  73. package/src/channels/FileChannel.ts +319 -220
  74. package/src/errors.ts +13 -0
  75. package/src/index.ts +17 -3
  76. package/src/jsonLine.ts +223 -0
  77. package/src/redact.ts +133 -9
  78. package/src/sanitize.ts +36 -12
  79. package/src/services/main.ts +13 -1
  80. package/src/stdSerializers.ts +147 -0
  81. package/src/stringify.ts +175 -0
  82. package/src/targets.ts +193 -42
  83. package/src/testing/FakeLogger.ts +23 -5
  84. package/src/types.ts +100 -5
  85. package/stubs/config/logger.stub +11 -1
package/src/Logger.ts CHANGED
@@ -14,18 +14,36 @@
14
14
  */
15
15
 
16
16
  import { format } from "node:util";
17
+ import { SpectrumError } from "./errors.js";
17
18
  import { emitLog, hasLogListeners } from "./events.js";
18
- import { parseRedactPath, redactPath } from "./redact.js";
19
+ import {
20
+ attachLineOptions,
21
+ type JsonLineOptions,
22
+ resolveLineOptions,
23
+ } from "./jsonLine.js";
24
+ import { type RedactAction, redactPath, redactPathsOf } from "./redact.js";
19
25
  import { sanitizeLogValue } from "./sanitize.js";
20
- import { channelsFromTargets } from "./targets.js";
26
+ import { serializeError } from "./stdSerializers.js";
27
+ import {
28
+ DEFAULT_STRINGIFY_LIMITS,
29
+ isStringifyLimit,
30
+ type StringifyLimits,
31
+ } from "./stringify.js";
32
+ import { channelsFromConfig } from "./targets.js";
21
33
  import type {
34
+ ChildOptions,
22
35
  LogConfig,
23
36
  LogEntry,
24
37
  LogLevel,
25
38
  LogLevelWithSilent,
26
39
  LogSerializer,
27
40
  } from "./types.js";
28
- import { LOG_LEVEL_ORDER, levelThreshold } from "./types.js";
41
+ import {
42
+ assertLogLevel,
43
+ isLogLevelWithSilent,
44
+ LOG_LEVEL_ORDER,
45
+ levelThreshold,
46
+ } from "./types.js";
29
47
 
30
48
  export type { LogLevel };
31
49
 
@@ -46,57 +64,124 @@ function isMergeableObject(value: unknown): value is Record<string, unknown> {
46
64
  );
47
65
  }
48
66
 
49
- /** How far down a `cause` chain to follow before calling it a cycle. */
50
- const MAX_CAUSE_DEPTH = 8;
67
+ /** The config's stringify limits, checked. */
68
+ function stringifyLimits(config: LogConfig): StringifyLimits {
69
+ const { depthLimit, edgeLimit } = config;
70
+ for (const [name, value] of [
71
+ ["depthLimit", depthLimit],
72
+ ["edgeLimit", edgeLimit],
73
+ ] as const) {
74
+ if (value !== undefined && !isStringifyLimit(value)) {
75
+ throw new SpectrumError(
76
+ "E_SPECTRUM_INVALID_STRINGIFY_LIMIT",
77
+ `${name} must be a positive integer, got ${String(value)}`,
78
+ );
79
+ }
80
+ }
81
+ return {
82
+ depthLimit: depthLimit ?? DEFAULT_STRINGIFY_LIMITS.depthLimit,
83
+ edgeLimit: edgeLimit ?? DEFAULT_STRINGIFY_LIMITS.edgeLimit,
84
+ };
85
+ }
86
+
87
+ /** The config's line options, checked; `undefined` when all are default. */
88
+ function lineOptions(config: LogConfig): JsonLineOptions | undefined {
89
+ const limits = stringifyLimits(config);
90
+ const { messageKey, timestamp, base, formatters, depthLimit, edgeLimit } =
91
+ config;
92
+ if (
93
+ [messageKey, timestamp, base, formatters, depthLimit, edgeLimit].every(
94
+ (value) => value === undefined,
95
+ )
96
+ ) {
97
+ return undefined;
98
+ }
99
+ return resolveLineOptions({
100
+ messageKey,
101
+ timestamp,
102
+ base,
103
+ formatters,
104
+ limits,
105
+ });
106
+ }
51
107
 
52
108
  /**
53
- * Serialize an Error the way pino's `err` serializer does. Non-Error values
54
- * pass through untouched.
55
- *
56
- * `{ name, message, stack }` threw away everything the error was carrying.
57
- * `err.code` is usually the one field a log search is keyed on, and the `cause`
58
- * of a wrapped error is the half that says what actually failed — both were
59
- * dropped, silently, by a serializer whose job is to keep them.
109
+ * Upstream options spectrum cannot honour. Ignoring them would run the logger
110
+ * as something other than what the config says, so they are refused.
60
111
  */
61
- function serializeError(value: unknown, depth = 0): unknown {
62
- if (!(value instanceof Error)) return value;
63
-
64
- // Own ENUMERABLE properties only, which on an Error means the ones it was
65
- // given: `message`, `stack` and `name` are not among them.
66
- const out: Record<string, unknown> = { ...value };
67
- for (const [key, nested] of Object.entries(out)) {
68
- if (nested instanceof Error && depth < MAX_CAUSE_DEPTH) {
69
- out[key] = serializeError(nested, depth + 1);
112
+ const UNSUPPORTED_OPTIONS = [
113
+ "customLevels",
114
+ "useOnlyCustomLevels",
115
+ "levelComparison",
116
+ "nestedKey",
117
+ "crlf",
118
+ ] as const;
119
+
120
+ function rejectUnsupportedOptions(config: LogConfig): void {
121
+ for (const option of UNSUPPORTED_OPTIONS) {
122
+ const value: unknown = Reflect.get(config, option);
123
+ if (value !== undefined) {
124
+ throw new SpectrumError(
125
+ "E_SPECTRUM_UNSUPPORTED_OPTION",
126
+ `the "${option}" logger option is not supported`,
127
+ );
70
128
  }
71
129
  }
72
-
73
- // Upstream reads the constructor rather than `name`, so a subclass that
74
- // never assigns `this.name` is still reported as itself, and it names the
75
- // field `type` — which is what an Adonis log pipeline reads.
76
- out.type =
77
- typeof value.constructor === "function"
78
- ? value.constructor.name
79
- : value.name;
80
- out.message = value.message;
81
- out.stack = value.stack;
82
- if (value instanceof AggregateError && Array.isArray(value.errors)) {
83
- out.aggregateErrors = value.errors.map((each) =>
84
- depth < MAX_CAUSE_DEPTH ? serializeError(each, depth + 1) : String(each),
130
+ const streamWrite: unknown =
131
+ config.hooks === undefined
132
+ ? undefined
133
+ : Reflect.get(config.hooks, "streamWrite");
134
+ if (streamWrite !== undefined) {
135
+ throw new SpectrumError(
136
+ "E_SPECTRUM_UNSUPPORTED_OPTION",
137
+ 'the "hooks.streamWrite" logger option is not supported',
85
138
  );
86
139
  }
87
- if (value.cause !== undefined) {
88
- out.cause =
89
- depth < MAX_CAUSE_DEPTH
90
- ? serializeError(value.cause, depth + 1)
91
- : "[cause chain too deep]";
140
+ }
141
+
142
+ /**
143
+ * The config with its output resolved to channels, once: explicit `channels`
144
+ * win, then `destination`, then the transport's targets.
145
+ */
146
+ function withChannels(config: LogConfig): LogConfig {
147
+ if (config.channels !== undefined) return config;
148
+ const channels = channelsFromConfig(config, config.level);
149
+ return channels === undefined ? config : { ...config, channels };
150
+ }
151
+
152
+ /** `config.redact`'s censor (or removal), compiled once. */
153
+ function redactAction(redact: LogConfig["redact"]): RedactAction {
154
+ if (redact === undefined || Array.isArray(redact)) {
155
+ return { remove: false, censor: () => "[Redacted]" };
92
156
  }
93
- return out;
157
+ const censor = redact.censor ?? "[Redacted]";
158
+ return {
159
+ remove: redact.remove === true,
160
+ censor: typeof censor === "function" ? censor : () => censor,
161
+ };
94
162
  }
95
163
 
96
- const DEFAULT_SERIALIZERS: Record<string, LogSerializer> = {
97
- err: serializeError,
98
- error: serializeError,
99
- };
164
+ /**
165
+ * The serializers a key is looked up in, on a null prototype as pino builds
166
+ * its own: every own key of a merging object (a request body, often) is read
167
+ * here, and on an ordinary object `valueOf`, `hasOwnProperty` or `__proto__`
168
+ * answered an `Object.prototype` member — called as a serializer, it threw
169
+ * out of the log call or rewrote the field.
170
+ */
171
+ function serializerBag(
172
+ configured: Record<string, LogSerializer> | undefined,
173
+ ): Record<string, LogSerializer> {
174
+ const bag: Record<string, LogSerializer> = Object.create(null);
175
+ bag.err = serializeError;
176
+ bag.error = serializeError;
177
+ if (configured !== undefined) {
178
+ for (const key of Object.keys(configured)) {
179
+ const serializer = configured[key];
180
+ if (typeof serializer === "function") bag[key] = serializer;
181
+ }
182
+ }
183
+ return bag;
184
+ }
100
185
 
101
186
  export class Logger {
102
187
  #config: LogConfig;
@@ -114,6 +199,12 @@ export class Logger {
114
199
  #level?: LogLevelWithSilent;
115
200
  /** `config.redact` compiled once, as pino compiles its redactor once. */
116
201
  readonly #redactPaths: string[][];
202
+ readonly #redactAction: RedactAction;
203
+ /**
204
+ * How a JSON channel writes this logger's lines, when the config moved
205
+ * anything away from the defaults.
206
+ */
207
+ readonly #lineOptions: JsonLineOptions | undefined;
117
208
 
118
209
  constructor(
119
210
  config: LogConfig,
@@ -125,23 +216,18 @@ export class Logger {
125
216
  // channels. Convert once here so every read path downstream sees only
126
217
  // channels — an explicit `channels` list wins, since it is the more
127
218
  // specific statement of intent.
128
- this.#config =
129
- config.channels === undefined && config.transport?.targets !== undefined
130
- ? {
131
- ...config,
132
- channels: channelsFromTargets(
133
- config.transport.targets,
134
- config.level,
135
- ),
136
- }
137
- : config;
219
+ rejectUnsupportedOptions(config);
220
+ this.#config = withChannels(config);
138
221
  this.#module = module;
139
222
  this.#correlationId = correlationId;
140
223
  this.#bindings = bindings;
141
- const redact = this.#config.redact;
142
- const paths =
143
- redact === undefined ? [] : Array.isArray(redact) ? redact : redact.paths;
144
- this.#redactPaths = paths.map(parseRedactPath);
224
+ if (this.#config.level !== undefined) assertLogLevel(this.#config.level);
225
+ for (const value of Object.values(this.#config.modules ?? {})) {
226
+ assertLogLevel(value);
227
+ }
228
+ this.#redactPaths = redactPathsOf(this.#config.redact);
229
+ this.#redactAction = redactAction(this.#config.redact);
230
+ this.#lineOptions = lineOptions(this.#config);
145
231
  }
146
232
 
147
233
  /** Whether the logger is enabled. When false every log call is a no-op. */
@@ -155,7 +241,7 @@ export class Logger {
155
241
  }
156
242
 
157
243
  set level(level: LogLevelWithSilent) {
158
- this.#level = level;
244
+ this.#level = assertLogLevel(level);
159
245
  }
160
246
 
161
247
  /** Numeric value of the current level (`silent` → +Infinity). */
@@ -206,24 +292,54 @@ export class Logger {
206
292
  * Create a child logger. Accepts arbitrary bindings that are merged into
207
293
  * every entry; `module` and `correlationId` are honoured as conventions.
208
294
  * This is the preferred way to scope per-request logging.
295
+ *
296
+ * `options` are upstream's: the child's own `level`, a `redact` that
297
+ * replaces the parent's, `serializers` added to the parent's, and a
298
+ * `msgPrefix` appended to the parent's.
209
299
  */
210
- child(bindings: Record<string, unknown> = {}): Logger {
300
+ child(
301
+ bindings: Record<string, unknown> = {},
302
+ options?: ChildOptions,
303
+ ): Logger {
211
304
  if (!this.isEnabled) return this;
212
305
  const { module, correlationId, ...rest } = bindings;
213
306
  const nextModule = typeof module === "string" ? module : this.#module;
214
307
  const nextCorrelation =
215
308
  typeof correlationId === "string" ? correlationId : this.#correlationId;
216
- const child = new Logger(this.#config, nextModule, nextCorrelation, {
217
- ...this.#bindings,
218
- ...rest,
219
- });
309
+ const child = new Logger(
310
+ options === undefined ? this.#config : this.#childConfig(options),
311
+ nextModule,
312
+ nextCorrelation,
313
+ { ...this.#bindings, ...rest },
314
+ );
220
315
  // A child starts where its parent stands now, and moves on its own
221
316
  // afterwards — pino's semantics, and the reason the level cannot live
222
317
  // in the config the two of them share.
223
- if (this.#level !== undefined) child.level = this.#level;
318
+ const level = options?.level ?? this.#level;
319
+ if (level !== undefined) child.level = level;
320
+ this.#config.onChild?.(child);
224
321
  return child;
225
322
  }
226
323
 
324
+ /** The config a child with options writes under; the parent's is untouched. */
325
+ #childConfig(options: ChildOptions): LogConfig {
326
+ return {
327
+ ...this.#config,
328
+ ...(options.redact !== undefined ? { redact: options.redact } : {}),
329
+ ...(options.serializers !== undefined
330
+ ? {
331
+ serializers: {
332
+ ...this.#config.serializers,
333
+ ...options.serializers,
334
+ },
335
+ }
336
+ : {}),
337
+ ...(options.msgPrefix !== undefined
338
+ ? { msgPrefix: (this.#config.msgPrefix ?? "") + options.msgPrefix }
339
+ : {}),
340
+ };
341
+ }
342
+
227
343
  /** Current bindings (logger name + child bindings + module/correlationId). */
228
344
  bindings(): Record<string, unknown> {
229
345
  const out: Record<string, unknown> = {
@@ -300,11 +416,24 @@ export class Logger {
300
416
  silent(message: string, ...values: unknown[]): void;
301
417
  silent(): void {}
302
418
 
303
- /** Resolve the numeric threshold for this logger + module. */
419
+ /**
420
+ * Resolve the numeric threshold for this logger + module.
421
+ *
422
+ * Only an OWN entry of `modules` overrides: bracket access answered for
423
+ * `constructor`, `toString` or `__proto__` with an inherited function, which
424
+ * is no level, and the fallback put such a module at `info` under a logger
425
+ * configured for `error`. Without an override a module is at the logger's
426
+ * own level — never at one more verbose than configured.
427
+ */
304
428
  #threshold(): number {
305
- const raw = this.#config.modules?.[this.#module] ?? this.level;
429
+ const modules = this.#config.modules;
430
+ const override =
431
+ modules !== undefined && Object.hasOwn(modules, this.#module)
432
+ ? modules[this.#module]
433
+ : undefined;
434
+ const raw = isLogLevelWithSilent(override) ? override : this.level;
306
435
  if (raw === "silent") return levelThreshold("silent");
307
- if (typeof raw === "string" && isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
436
+ if (isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
308
437
  return LOG_LEVEL_ORDER.info;
309
438
  }
310
439
 
@@ -322,17 +451,45 @@ export class Logger {
322
451
  arg0: unknown,
323
452
  rest: unknown[],
324
453
  ): { message: string; mergingObject?: Record<string, unknown> } {
454
+ const { message, mergingObject, given } = this.#splitArgs(arg0, rest);
455
+ // The prefix goes on a message the call gave, as upstream's does.
456
+ const prefix = this.#config.msgPrefix;
457
+ return {
458
+ message: prefix !== undefined && given ? prefix + message : message,
459
+ ...(mergingObject !== undefined ? { mergingObject } : {}),
460
+ };
461
+ }
462
+
463
+ #splitArgs(
464
+ arg0: unknown,
465
+ rest: unknown[],
466
+ ): {
467
+ message: string;
468
+ mergingObject?: Record<string, unknown>;
469
+ given: boolean;
470
+ } {
471
+ const errorKey = this.#config.errorKey ?? "err";
325
472
  if (arg0 instanceof Error) {
326
473
  const message =
327
474
  typeof rest[0] === "string"
328
475
  ? format(rest[0], ...rest.slice(1))
329
476
  : arg0.message;
330
- return { message, mergingObject: { err: arg0 } };
477
+ return { message, mergingObject: { [errorKey]: arg0 }, given: true };
331
478
  }
332
479
  if (isMergeableObject(arg0)) {
333
- const message =
334
- typeof rest[0] === "string" ? format(rest[0], ...rest.slice(1)) : "";
335
- return { message, mergingObject: arg0 };
480
+ if (typeof rest[0] === "string") {
481
+ return {
482
+ message: format(rest[0], ...rest.slice(1)),
483
+ mergingObject: arg0,
484
+ given: true,
485
+ };
486
+ }
487
+ // An object carrying an error and no message is described by the
488
+ // error's message, as upstream does.
489
+ const err = Object.hasOwn(arg0, errorKey) ? arg0[errorKey] : undefined;
490
+ return err instanceof Error
491
+ ? { message: err.message, mergingObject: arg0, given: true }
492
+ : { message: "", mergingObject: arg0, given: false };
336
493
  }
337
494
 
338
495
  const template = typeof arg0 === "string" ? arg0 : String(arg0);
@@ -341,18 +498,36 @@ export class Logger {
341
498
  isMergeableObject(rest[0]) &&
342
499
  !PRINTF_TOKEN.test(template)
343
500
  ) {
344
- return { message: template, mergingObject: rest[0] };
501
+ return { message: template, mergingObject: rest[0], given: true };
345
502
  }
346
503
  const message = rest.length > 0 ? format(template, ...rest) : template;
347
- return { message };
504
+ return { message, given: true };
505
+ }
506
+
507
+ /** The merging object with the mixin's fields; the merging object wins by default. */
508
+ #withMixin(
509
+ mergingObject: Record<string, unknown>,
510
+ level: LogLevel,
511
+ ): Record<string, unknown> {
512
+ const mixin = this.#config.mixin;
513
+ if (mixin === undefined) return mergingObject;
514
+ const mixed: unknown = mixin(mergingObject, LOG_LEVEL_ORDER[level], this);
515
+ const mixinObject = isMergeableObject(mixed) ? mixed : {};
516
+ const strategy = this.#config.mixinMergeStrategy;
517
+ return strategy !== undefined
518
+ ? strategy(mergingObject, mixinObject)
519
+ : { ...mixinObject, ...mergingObject };
348
520
  }
349
521
 
350
522
  #applySerializers(bag: Record<string, unknown>): Record<string, unknown> {
351
- const serializers = { ...DEFAULT_SERIALIZERS, ...this.#config.serializers };
523
+ const serializers = serializerBag(this.#config.serializers);
524
+ const errorKey = this.#config.errorKey ?? "err";
352
525
  let out: Record<string, unknown> | null = null;
353
526
  for (const key of Object.keys(bag)) {
354
- const serializer = serializers[key];
355
- if (serializer) {
527
+ // The error key takes the `err` serializer unless it has its own.
528
+ const serializer =
529
+ serializers[key] ?? (key === errorKey ? serializers.err : undefined);
530
+ if (serializer !== undefined) {
356
531
  if (!out) out = { ...bag };
357
532
  out[key] = serializer(bag[key]);
358
533
  }
@@ -362,23 +537,36 @@ export class Logger {
362
537
 
363
538
  #applyRedact(bag: Record<string, unknown>): Record<string, unknown> {
364
539
  if (this.#redactPaths.length === 0) return bag;
365
- const redact = this.#config.redact;
366
- const censor =
367
- redact === undefined || Array.isArray(redact)
368
- ? "[Redacted]"
369
- : (redact.censor ?? "[Redacted]");
370
540
  let out: unknown = bag;
371
541
  for (const tokens of this.#redactPaths) {
372
- out = redactPath(out, tokens, censor);
542
+ out = redactPath(out, tokens, this.#redactAction);
373
543
  }
374
544
  return isMergeableObject(out) ? out : bag;
375
545
  }
376
546
 
377
- #write(level: LogLevel, arg0: unknown, rest: unknown[]): void {
547
+ #write(
548
+ level: LogLevel,
549
+ arg0: unknown,
550
+ rest: unknown[],
551
+ viaHook = false,
552
+ ): void {
378
553
  if (!this.isEnabled) return;
379
554
  if (LOG_LEVEL_ORDER[level] < this.#threshold()) return;
380
555
 
556
+ const hook = this.#config.hooks?.logMethod;
557
+ if (hook !== undefined && !viaHook) {
558
+ hook.call(
559
+ this,
560
+ [arg0, ...rest],
561
+ (...args: unknown[]) =>
562
+ this.#write(level, args[0], args.slice(1), true),
563
+ LOG_LEVEL_ORDER[level],
564
+ );
565
+ return;
566
+ }
567
+
381
568
  const { message, mergingObject } = this.#resolveArgs(arg0, rest);
569
+ const merged = this.#withMixin(mergingObject ?? {}, level);
382
570
 
383
571
  let bag: Record<string, unknown> = {
384
572
  // The name a multi-logger config gave this logger. It was assigned by
@@ -387,7 +575,7 @@ export class Logger {
387
575
  // pino carries it as a binding; a merging object still wins over it.
388
576
  ...(this.#config.name !== undefined ? { name: this.#config.name } : {}),
389
577
  ...this.#bindings,
390
- ...(mergingObject ?? {}),
578
+ ...merged,
391
579
  };
392
580
  bag = this.#applySerializers(bag);
393
581
  bag = this.#applyRedact(bag);
@@ -403,6 +591,10 @@ export class Logger {
403
591
  timestamp: new Date().toISOString(),
404
592
  };
405
593
 
594
+ if (this.#lineOptions !== undefined) {
595
+ attachLineOptions(entry, this.#lineOptions);
596
+ }
597
+
406
598
  // Observers before the channels: a channel that throws falls back to
407
599
  // stderr, and an observer must not be skipped by that path.
408
600
  if (hasLogListeners()) emitLog(entry);
@@ -38,13 +38,20 @@ export class LoggerManager extends Logger {
38
38
  `[spectrum] Unknown logger "${key}". Registered: ${Object.keys(this.#config.loggers).join(", ")}`,
39
39
  );
40
40
  }
41
- if (!config.name) config.name = key;
42
-
43
- const logger = this.create(config);
41
+ const logger = this.createLogger(key, config);
44
42
  this.#loggers.set(key, logger);
45
43
  return logger;
46
44
  }
47
45
 
46
+ /**
47
+ * Build a named logger: the config's `name` defaults to the name it is
48
+ * registered under. Not cached; `use()` caches what this returns.
49
+ */
50
+ createLogger(name: string, config: LogConfig): Logger {
51
+ if (!config.name) config.name = name;
52
+ return new Logger(config);
53
+ }
54
+
48
55
  /**
49
56
  * Create a logger from a config. The returned instance is NOT cached or
50
57
  * managed by the manager.
@@ -5,10 +5,29 @@
5
5
  * through the Spectrum Logger so both Rust and TS logs appear in
6
6
  * the same stream with the same format.
7
7
  *
8
+ * Every stderr write in the process goes through the bridge, not only the
9
+ * Rust crates' — `console.error`, a child process, a library echoing request
10
+ * data. So a line is claimed only when its module is on an allow-list
11
+ * (`ream-*` by default), it is written through the Logger (its level,
12
+ * `enabled`, serializers and redaction apply) and it carries
13
+ * `source: 'rust'`. Before that, any `[FATAL anything] text` that reached
14
+ * stderr became a genuine-looking structured entry.
15
+ *
8
16
  * @implements FR55
9
17
  */
10
18
 
11
- import type { LogChannel, LogEntry, LogLevel } from "./types.js";
19
+ import type { Logger } from "./Logger.js";
20
+ import type { LogEntry, LogLevel } from "./types.js";
21
+
22
+ export interface RustLogBridgeOptions {
23
+ /**
24
+ * Modules (after `_` → `-`) the bridge claims. Anything else passes
25
+ * through to stderr as text. Default `/^ream-/`.
26
+ */
27
+ modules?: RegExp;
28
+ }
29
+
30
+ const DEFAULT_MODULES = /^ream-/;
12
31
 
13
32
  /**
14
33
  * Parse a Rust log line into a Spectrum LogEntry.
@@ -50,18 +69,6 @@ export function parseRustLog(line: string): LogEntry | null {
50
69
  };
51
70
  }
52
71
 
53
- /**
54
- * Create a bridge that captures stderr and routes Rust logs to Spectrum channels.
55
- *
56
- * Usage — pass the same channels array you built the Logger with (Logger.config
57
- * is private, so reuse the array rather than reaching into the instance):
58
- * const channels = [new ConsoleChannel('pretty')]
59
- * const logger = new Logger({ level: 'info', channels })
60
- * const bridge = createRustLogBridge(channels)
61
- * bridge.start()
62
- * // ... Rust crates emit to stderr
63
- * bridge.stop()
64
- */
65
72
  /**
66
73
  * `process.stderr.write` exactly as it was found, so `stop()` puts THAT back.
67
74
  *
@@ -117,12 +124,39 @@ function passThrough(
117
124
  return write.call(process.stderr, chunk, encoding, done);
118
125
  }
119
126
 
120
- export function createRustLogBridge(channels: LogChannel[]): {
127
+ /**
128
+ * Create a bridge that captures stderr and routes Rust logs through `logger`.
129
+ *
130
+ * const logger = new Logger({ level: 'info', channels: [new ConsoleChannel('pretty')] })
131
+ * const bridge = createRustLogBridge(logger)
132
+ * bridge.start()
133
+ * // ... Rust crates emit to stderr
134
+ * bridge.stop()
135
+ */
136
+ export function createRustLogBridge(
137
+ logger: Logger,
138
+ options: RustLogBridgeOptions = {},
139
+ ): {
121
140
  start: () => void;
122
141
  stop: () => void;
123
142
  } {
143
+ const modules = options.modules ?? DEFAULT_MODULES;
124
144
  let bridgingDepth = 0;
125
145
 
146
+ /** A claimed line, through the logger, its own writes passed straight on. */
147
+ const emit = (entry: LogEntry): void => {
148
+ bridgingDepth++;
149
+ try {
150
+ logger
151
+ .child({ module: entry.module, source: "rust" })
152
+ .log(entry.level, entry.message);
153
+ } catch {
154
+ // The bridge must never break a stderr write.
155
+ } finally {
156
+ bridgingDepth--;
157
+ }
158
+ };
159
+
126
160
  const bridge = {
127
161
  start() {
128
162
  if (activeBridge === bridge) return;
@@ -164,13 +198,11 @@ export function createRustLogBridge(channels: LogChannel[]): {
164
198
  const str =
165
199
  typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
166
200
  let hadRustLog = false;
167
- // Rebuild passthrough as one byte-faithful string instead of
168
- // re-emitting each line with an appended "\n". split("\n") drops
169
- // the separator, so every segment except a trailing fragment (the
201
+ // Rebuild passthrough byte-faithfully: split("\n") drops the
202
+ // separator, so every segment except a trailing fragment (the
170
203
  // chunk didn't end in "\n") was newline-terminated originally —
171
- // reattach accordingly. This preserves blank lines and a partial
172
- // no-newline trailing write verbatim, and keeps passthrough lines
173
- // in their original order.
204
+ // reattach accordingly. Text ahead of a claimed line is written
205
+ // before it, so the order a reader sees is the order written.
174
206
  let passthrough = "";
175
207
  const segments = str.split("\n");
176
208
  for (let i = 0; i < segments.length; i++) {
@@ -180,20 +212,17 @@ export function createRustLogBridge(channels: LogChannel[]): {
180
212
  const trimmed = seg.trim();
181
213
  // Only a complete, non-empty line is a Rust-log candidate. A
182
214
  // trailing fragment is a partial write — never parse or drop it.
183
- const entry =
215
+ const parsed =
184
216
  trimmed && !isTrailingFragment ? parseRustLog(trimmed) : null;
217
+ const entry =
218
+ parsed !== null && modules.test(parsed.module) ? parsed : null;
185
219
  if (entry) {
186
220
  hadRustLog = true;
187
- for (const channel of channels) {
188
- bridgingDepth++;
189
- try {
190
- channel.write(entry);
191
- } catch {
192
- /* ignore */
193
- } finally {
194
- bridgingDepth--;
195
- }
221
+ if (passthrough) {
222
+ passThrough(origWrite, passthrough, undefined, undefined);
223
+ passthrough = "";
196
224
  }
225
+ emit(entry);
197
226
  } else {
198
227
  passthrough += original;
199
228
  }