@c9up/spectrum 0.1.18 → 0.1.19

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 +23 -6
  2. package/dist/Logger.d.ts +6 -2
  3. package/dist/Logger.d.ts.map +1 -1
  4. package/dist/Logger.js +190 -72
  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 +13 -11
  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 +164 -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 +47 -0
  50. package/dist/stdSerializers.d.ts.map +1 -0
  51. package/dist/stdSerializers.js +128 -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 +18 -2
  66. package/dist/types.js.map +1 -1
  67. package/package.json +1 -1
  68. package/src/Logger.ts +254 -79
  69. package/src/LoggerManager.ts +10 -3
  70. package/src/RustLogBridge.ts +59 -30
  71. package/src/SpectrumProvider.ts +26 -17
  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 +222 -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 +146 -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 +97 -4
  85. package/stubs/config/logger.stub +1 -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,51 +64,101 @@ 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
164
  const DEFAULT_SERIALIZERS: Record<string, LogSerializer> = {
@@ -114,6 +182,12 @@ export class Logger {
114
182
  #level?: LogLevelWithSilent;
115
183
  /** `config.redact` compiled once, as pino compiles its redactor once. */
116
184
  readonly #redactPaths: string[][];
185
+ readonly #redactAction: RedactAction;
186
+ /**
187
+ * How a JSON channel writes this logger's lines, when the config moved
188
+ * anything away from the defaults.
189
+ */
190
+ readonly #lineOptions: JsonLineOptions | undefined;
117
191
 
118
192
  constructor(
119
193
  config: LogConfig,
@@ -125,23 +199,18 @@ export class Logger {
125
199
  // channels. Convert once here so every read path downstream sees only
126
200
  // channels — an explicit `channels` list wins, since it is the more
127
201
  // 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;
202
+ rejectUnsupportedOptions(config);
203
+ this.#config = withChannels(config);
138
204
  this.#module = module;
139
205
  this.#correlationId = correlationId;
140
206
  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);
207
+ if (this.#config.level !== undefined) assertLogLevel(this.#config.level);
208
+ for (const value of Object.values(this.#config.modules ?? {})) {
209
+ assertLogLevel(value);
210
+ }
211
+ this.#redactPaths = redactPathsOf(this.#config.redact);
212
+ this.#redactAction = redactAction(this.#config.redact);
213
+ this.#lineOptions = lineOptions(this.#config);
145
214
  }
146
215
 
147
216
  /** Whether the logger is enabled. When false every log call is a no-op. */
@@ -155,7 +224,7 @@ export class Logger {
155
224
  }
156
225
 
157
226
  set level(level: LogLevelWithSilent) {
158
- this.#level = level;
227
+ this.#level = assertLogLevel(level);
159
228
  }
160
229
 
161
230
  /** Numeric value of the current level (`silent` → +Infinity). */
@@ -206,24 +275,54 @@ export class Logger {
206
275
  * Create a child logger. Accepts arbitrary bindings that are merged into
207
276
  * every entry; `module` and `correlationId` are honoured as conventions.
208
277
  * This is the preferred way to scope per-request logging.
278
+ *
279
+ * `options` are upstream's: the child's own `level`, a `redact` that
280
+ * replaces the parent's, `serializers` added to the parent's, and a
281
+ * `msgPrefix` appended to the parent's.
209
282
  */
210
- child(bindings: Record<string, unknown> = {}): Logger {
283
+ child(
284
+ bindings: Record<string, unknown> = {},
285
+ options?: ChildOptions,
286
+ ): Logger {
211
287
  if (!this.isEnabled) return this;
212
288
  const { module, correlationId, ...rest } = bindings;
213
289
  const nextModule = typeof module === "string" ? module : this.#module;
214
290
  const nextCorrelation =
215
291
  typeof correlationId === "string" ? correlationId : this.#correlationId;
216
- const child = new Logger(this.#config, nextModule, nextCorrelation, {
217
- ...this.#bindings,
218
- ...rest,
219
- });
292
+ const child = new Logger(
293
+ options === undefined ? this.#config : this.#childConfig(options),
294
+ nextModule,
295
+ nextCorrelation,
296
+ { ...this.#bindings, ...rest },
297
+ );
220
298
  // A child starts where its parent stands now, and moves on its own
221
299
  // afterwards — pino's semantics, and the reason the level cannot live
222
300
  // in the config the two of them share.
223
- if (this.#level !== undefined) child.level = this.#level;
301
+ const level = options?.level ?? this.#level;
302
+ if (level !== undefined) child.level = level;
303
+ this.#config.onChild?.(child);
224
304
  return child;
225
305
  }
226
306
 
307
+ /** The config a child with options writes under; the parent's is untouched. */
308
+ #childConfig(options: ChildOptions): LogConfig {
309
+ return {
310
+ ...this.#config,
311
+ ...(options.redact !== undefined ? { redact: options.redact } : {}),
312
+ ...(options.serializers !== undefined
313
+ ? {
314
+ serializers: {
315
+ ...this.#config.serializers,
316
+ ...options.serializers,
317
+ },
318
+ }
319
+ : {}),
320
+ ...(options.msgPrefix !== undefined
321
+ ? { msgPrefix: (this.#config.msgPrefix ?? "") + options.msgPrefix }
322
+ : {}),
323
+ };
324
+ }
325
+
227
326
  /** Current bindings (logger name + child bindings + module/correlationId). */
228
327
  bindings(): Record<string, unknown> {
229
328
  const out: Record<string, unknown> = {
@@ -300,11 +399,24 @@ export class Logger {
300
399
  silent(message: string, ...values: unknown[]): void;
301
400
  silent(): void {}
302
401
 
303
- /** Resolve the numeric threshold for this logger + module. */
402
+ /**
403
+ * Resolve the numeric threshold for this logger + module.
404
+ *
405
+ * Only an OWN entry of `modules` overrides: bracket access answered for
406
+ * `constructor`, `toString` or `__proto__` with an inherited function, which
407
+ * is no level, and the fallback put such a module at `info` under a logger
408
+ * configured for `error`. Without an override a module is at the logger's
409
+ * own level — never at one more verbose than configured.
410
+ */
304
411
  #threshold(): number {
305
- const raw = this.#config.modules?.[this.#module] ?? this.level;
412
+ const modules = this.#config.modules;
413
+ const override =
414
+ modules !== undefined && Object.hasOwn(modules, this.#module)
415
+ ? modules[this.#module]
416
+ : undefined;
417
+ const raw = isLogLevelWithSilent(override) ? override : this.level;
306
418
  if (raw === "silent") return levelThreshold("silent");
307
- if (typeof raw === "string" && isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
419
+ if (isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
308
420
  return LOG_LEVEL_ORDER.info;
309
421
  }
310
422
 
@@ -322,17 +434,45 @@ export class Logger {
322
434
  arg0: unknown,
323
435
  rest: unknown[],
324
436
  ): { message: string; mergingObject?: Record<string, unknown> } {
437
+ const { message, mergingObject, given } = this.#splitArgs(arg0, rest);
438
+ // The prefix goes on a message the call gave, as upstream's does.
439
+ const prefix = this.#config.msgPrefix;
440
+ return {
441
+ message: prefix !== undefined && given ? prefix + message : message,
442
+ ...(mergingObject !== undefined ? { mergingObject } : {}),
443
+ };
444
+ }
445
+
446
+ #splitArgs(
447
+ arg0: unknown,
448
+ rest: unknown[],
449
+ ): {
450
+ message: string;
451
+ mergingObject?: Record<string, unknown>;
452
+ given: boolean;
453
+ } {
454
+ const errorKey = this.#config.errorKey ?? "err";
325
455
  if (arg0 instanceof Error) {
326
456
  const message =
327
457
  typeof rest[0] === "string"
328
458
  ? format(rest[0], ...rest.slice(1))
329
459
  : arg0.message;
330
- return { message, mergingObject: { err: arg0 } };
460
+ return { message, mergingObject: { [errorKey]: arg0 }, given: true };
331
461
  }
332
462
  if (isMergeableObject(arg0)) {
333
- const message =
334
- typeof rest[0] === "string" ? format(rest[0], ...rest.slice(1)) : "";
335
- return { message, mergingObject: arg0 };
463
+ if (typeof rest[0] === "string") {
464
+ return {
465
+ message: format(rest[0], ...rest.slice(1)),
466
+ mergingObject: arg0,
467
+ given: true,
468
+ };
469
+ }
470
+ // An object carrying an error and no message is described by the
471
+ // error's message, as upstream does.
472
+ const err = Object.hasOwn(arg0, errorKey) ? arg0[errorKey] : undefined;
473
+ return err instanceof Error
474
+ ? { message: err.message, mergingObject: arg0, given: true }
475
+ : { message: "", mergingObject: arg0, given: false };
336
476
  }
337
477
 
338
478
  const template = typeof arg0 === "string" ? arg0 : String(arg0);
@@ -341,17 +481,35 @@ export class Logger {
341
481
  isMergeableObject(rest[0]) &&
342
482
  !PRINTF_TOKEN.test(template)
343
483
  ) {
344
- return { message: template, mergingObject: rest[0] };
484
+ return { message: template, mergingObject: rest[0], given: true };
345
485
  }
346
486
  const message = rest.length > 0 ? format(template, ...rest) : template;
347
- return { message };
487
+ return { message, given: true };
488
+ }
489
+
490
+ /** The merging object with the mixin's fields; the merging object wins by default. */
491
+ #withMixin(
492
+ mergingObject: Record<string, unknown>,
493
+ level: LogLevel,
494
+ ): Record<string, unknown> {
495
+ const mixin = this.#config.mixin;
496
+ if (mixin === undefined) return mergingObject;
497
+ const mixed: unknown = mixin(mergingObject, LOG_LEVEL_ORDER[level], this);
498
+ const mixinObject = isMergeableObject(mixed) ? mixed : {};
499
+ const strategy = this.#config.mixinMergeStrategy;
500
+ return strategy !== undefined
501
+ ? strategy(mergingObject, mixinObject)
502
+ : { ...mixinObject, ...mergingObject };
348
503
  }
349
504
 
350
505
  #applySerializers(bag: Record<string, unknown>): Record<string, unknown> {
351
506
  const serializers = { ...DEFAULT_SERIALIZERS, ...this.#config.serializers };
507
+ const errorKey = this.#config.errorKey ?? "err";
352
508
  let out: Record<string, unknown> | null = null;
353
509
  for (const key of Object.keys(bag)) {
354
- const serializer = serializers[key];
510
+ // The error key takes the `err` serializer unless it has its own.
511
+ const serializer =
512
+ serializers[key] ?? (key === errorKey ? serializers.err : undefined);
355
513
  if (serializer) {
356
514
  if (!out) out = { ...bag };
357
515
  out[key] = serializer(bag[key]);
@@ -362,23 +520,36 @@ export class Logger {
362
520
 
363
521
  #applyRedact(bag: Record<string, unknown>): Record<string, unknown> {
364
522
  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
523
  let out: unknown = bag;
371
524
  for (const tokens of this.#redactPaths) {
372
- out = redactPath(out, tokens, censor);
525
+ out = redactPath(out, tokens, this.#redactAction);
373
526
  }
374
527
  return isMergeableObject(out) ? out : bag;
375
528
  }
376
529
 
377
- #write(level: LogLevel, arg0: unknown, rest: unknown[]): void {
530
+ #write(
531
+ level: LogLevel,
532
+ arg0: unknown,
533
+ rest: unknown[],
534
+ viaHook = false,
535
+ ): void {
378
536
  if (!this.isEnabled) return;
379
537
  if (LOG_LEVEL_ORDER[level] < this.#threshold()) return;
380
538
 
539
+ const hook = this.#config.hooks?.logMethod;
540
+ if (hook !== undefined && !viaHook) {
541
+ hook.call(
542
+ this,
543
+ [arg0, ...rest],
544
+ (...args: unknown[]) =>
545
+ this.#write(level, args[0], args.slice(1), true),
546
+ LOG_LEVEL_ORDER[level],
547
+ );
548
+ return;
549
+ }
550
+
381
551
  const { message, mergingObject } = this.#resolveArgs(arg0, rest);
552
+ const merged = this.#withMixin(mergingObject ?? {}, level);
382
553
 
383
554
  let bag: Record<string, unknown> = {
384
555
  // The name a multi-logger config gave this logger. It was assigned by
@@ -387,7 +558,7 @@ export class Logger {
387
558
  // pino carries it as a binding; a merging object still wins over it.
388
559
  ...(this.#config.name !== undefined ? { name: this.#config.name } : {}),
389
560
  ...this.#bindings,
390
- ...(mergingObject ?? {}),
561
+ ...merged,
391
562
  };
392
563
  bag = this.#applySerializers(bag);
393
564
  bag = this.#applyRedact(bag);
@@ -403,6 +574,10 @@ export class Logger {
403
574
  timestamp: new Date().toISOString(),
404
575
  };
405
576
 
577
+ if (this.#lineOptions !== undefined) {
578
+ attachLineOptions(entry, this.#lineOptions);
579
+ }
580
+
406
581
  // Observers before the channels: a channel that throws falls back to
407
582
  // stderr, and an observer must not be skipped by that path.
408
583
  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
  }