@c9up/spectrum 0.1.17 → 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 (90) 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 +195 -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 +51 -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/events.d.ts +38 -0
  31. package/dist/events.d.ts.map +1 -0
  32. package/dist/events.js +55 -0
  33. package/dist/events.js.map +1 -0
  34. package/dist/index.d.ts +8 -4
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +5 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/jsonLine.d.ts +49 -0
  39. package/dist/jsonLine.d.ts.map +1 -0
  40. package/dist/jsonLine.js +164 -0
  41. package/dist/jsonLine.js.map +1 -0
  42. package/dist/redact.d.ts +16 -3
  43. package/dist/redact.d.ts.map +1 -1
  44. package/dist/redact.js +121 -10
  45. package/dist/redact.js.map +1 -1
  46. package/dist/sanitize.d.ts +11 -5
  47. package/dist/sanitize.d.ts.map +1 -1
  48. package/dist/sanitize.js +36 -12
  49. package/dist/sanitize.js.map +1 -1
  50. package/dist/services/main.d.ts.map +1 -1
  51. package/dist/services/main.js +12 -1
  52. package/dist/services/main.js.map +1 -1
  53. package/dist/stdSerializers.d.ts +47 -0
  54. package/dist/stdSerializers.d.ts.map +1 -0
  55. package/dist/stdSerializers.js +128 -0
  56. package/dist/stdSerializers.js.map +1 -0
  57. package/dist/stringify.d.ts +33 -0
  58. package/dist/stringify.d.ts.map +1 -0
  59. package/dist/stringify.js +148 -0
  60. package/dist/stringify.js.map +1 -0
  61. package/dist/targets.d.ts +29 -7
  62. package/dist/targets.d.ts.map +1 -1
  63. package/dist/targets.js +130 -31
  64. package/dist/targets.js.map +1 -1
  65. package/dist/testing/FakeLogger.js +20 -5
  66. package/dist/testing/FakeLogger.js.map +1 -1
  67. package/dist/types.d.ts +71 -3
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js +18 -2
  70. package/dist/types.js.map +1 -1
  71. package/package.json +1 -1
  72. package/src/Logger.ts +259 -79
  73. package/src/LoggerManager.ts +10 -3
  74. package/src/RustLogBridge.ts +59 -30
  75. package/src/SpectrumProvider.ts +69 -17
  76. package/src/channels/ConsoleChannel.ts +30 -14
  77. package/src/channels/FileChannel.ts +319 -220
  78. package/src/errors.ts +13 -0
  79. package/src/events.ts +62 -0
  80. package/src/index.ts +18 -3
  81. package/src/jsonLine.ts +222 -0
  82. package/src/redact.ts +133 -9
  83. package/src/sanitize.ts +36 -12
  84. package/src/services/main.ts +13 -1
  85. package/src/stdSerializers.ts +146 -0
  86. package/src/stringify.ts +175 -0
  87. package/src/targets.ts +193 -42
  88. package/src/testing/FakeLogger.ts +23 -5
  89. package/src/types.ts +97 -4
  90. package/stubs/config/logger.stub +1 -1
package/src/Logger.ts CHANGED
@@ -14,17 +14,36 @@
14
14
  */
15
15
 
16
16
  import { format } from "node:util";
17
- import { parseRedactPath, redactPath } from "./redact.js";
17
+ import { SpectrumError } from "./errors.js";
18
+ import { emitLog, hasLogListeners } from "./events.js";
19
+ import {
20
+ attachLineOptions,
21
+ type JsonLineOptions,
22
+ resolveLineOptions,
23
+ } from "./jsonLine.js";
24
+ import { type RedactAction, redactPath, redactPathsOf } from "./redact.js";
18
25
  import { sanitizeLogValue } from "./sanitize.js";
19
- 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";
20
33
  import type {
34
+ ChildOptions,
21
35
  LogConfig,
22
36
  LogEntry,
23
37
  LogLevel,
24
38
  LogLevelWithSilent,
25
39
  LogSerializer,
26
40
  } from "./types.js";
27
- import { LOG_LEVEL_ORDER, levelThreshold } from "./types.js";
41
+ import {
42
+ assertLogLevel,
43
+ isLogLevelWithSilent,
44
+ LOG_LEVEL_ORDER,
45
+ levelThreshold,
46
+ } from "./types.js";
28
47
 
29
48
  export type { LogLevel };
30
49
 
@@ -45,51 +64,101 @@ function isMergeableObject(value: unknown): value is Record<string, unknown> {
45
64
  );
46
65
  }
47
66
 
48
- /** How far down a `cause` chain to follow before calling it a cycle. */
49
- 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
+ }
50
107
 
51
108
  /**
52
- * Serialize an Error the way pino's `err` serializer does. Non-Error values
53
- * pass through untouched.
54
- *
55
- * `{ name, message, stack }` threw away everything the error was carrying.
56
- * `err.code` is usually the one field a log search is keyed on, and the `cause`
57
- * of a wrapped error is the half that says what actually failed — both were
58
- * 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.
59
111
  */
60
- function serializeError(value: unknown, depth = 0): unknown {
61
- if (!(value instanceof Error)) return value;
62
-
63
- // Own ENUMERABLE properties only, which on an Error means the ones it was
64
- // given: `message`, `stack` and `name` are not among them.
65
- const out: Record<string, unknown> = { ...value };
66
- for (const [key, nested] of Object.entries(out)) {
67
- if (nested instanceof Error && depth < MAX_CAUSE_DEPTH) {
68
- 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
+ );
69
128
  }
70
129
  }
71
-
72
- // Upstream reads the constructor rather than `name`, so a subclass that
73
- // never assigns `this.name` is still reported as itself, and it names the
74
- // field `type` — which is what an Adonis log pipeline reads.
75
- out.type =
76
- typeof value.constructor === "function"
77
- ? value.constructor.name
78
- : value.name;
79
- out.message = value.message;
80
- out.stack = value.stack;
81
- if (value instanceof AggregateError && Array.isArray(value.errors)) {
82
- out.aggregateErrors = value.errors.map((each) =>
83
- 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',
84
138
  );
85
139
  }
86
- if (value.cause !== undefined) {
87
- out.cause =
88
- depth < MAX_CAUSE_DEPTH
89
- ? serializeError(value.cause, depth + 1)
90
- : "[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]" };
91
156
  }
92
- return out;
157
+ const censor = redact.censor ?? "[Redacted]";
158
+ return {
159
+ remove: redact.remove === true,
160
+ censor: typeof censor === "function" ? censor : () => censor,
161
+ };
93
162
  }
94
163
 
95
164
  const DEFAULT_SERIALIZERS: Record<string, LogSerializer> = {
@@ -113,6 +182,12 @@ export class Logger {
113
182
  #level?: LogLevelWithSilent;
114
183
  /** `config.redact` compiled once, as pino compiles its redactor once. */
115
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;
116
191
 
117
192
  constructor(
118
193
  config: LogConfig,
@@ -124,23 +199,18 @@ export class Logger {
124
199
  // channels. Convert once here so every read path downstream sees only
125
200
  // channels — an explicit `channels` list wins, since it is the more
126
201
  // specific statement of intent.
127
- this.#config =
128
- config.channels === undefined && config.transport?.targets !== undefined
129
- ? {
130
- ...config,
131
- channels: channelsFromTargets(
132
- config.transport.targets,
133
- config.level,
134
- ),
135
- }
136
- : config;
202
+ rejectUnsupportedOptions(config);
203
+ this.#config = withChannels(config);
137
204
  this.#module = module;
138
205
  this.#correlationId = correlationId;
139
206
  this.#bindings = bindings;
140
- const redact = this.#config.redact;
141
- const paths =
142
- redact === undefined ? [] : Array.isArray(redact) ? redact : redact.paths;
143
- 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);
144
214
  }
145
215
 
146
216
  /** Whether the logger is enabled. When false every log call is a no-op. */
@@ -154,7 +224,7 @@ export class Logger {
154
224
  }
155
225
 
156
226
  set level(level: LogLevelWithSilent) {
157
- this.#level = level;
227
+ this.#level = assertLogLevel(level);
158
228
  }
159
229
 
160
230
  /** Numeric value of the current level (`silent` → +Infinity). */
@@ -205,24 +275,54 @@ export class Logger {
205
275
  * Create a child logger. Accepts arbitrary bindings that are merged into
206
276
  * every entry; `module` and `correlationId` are honoured as conventions.
207
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.
208
282
  */
209
- child(bindings: Record<string, unknown> = {}): Logger {
283
+ child(
284
+ bindings: Record<string, unknown> = {},
285
+ options?: ChildOptions,
286
+ ): Logger {
210
287
  if (!this.isEnabled) return this;
211
288
  const { module, correlationId, ...rest } = bindings;
212
289
  const nextModule = typeof module === "string" ? module : this.#module;
213
290
  const nextCorrelation =
214
291
  typeof correlationId === "string" ? correlationId : this.#correlationId;
215
- const child = new Logger(this.#config, nextModule, nextCorrelation, {
216
- ...this.#bindings,
217
- ...rest,
218
- });
292
+ const child = new Logger(
293
+ options === undefined ? this.#config : this.#childConfig(options),
294
+ nextModule,
295
+ nextCorrelation,
296
+ { ...this.#bindings, ...rest },
297
+ );
219
298
  // A child starts where its parent stands now, and moves on its own
220
299
  // afterwards — pino's semantics, and the reason the level cannot live
221
300
  // in the config the two of them share.
222
- 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);
223
304
  return child;
224
305
  }
225
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
+
226
326
  /** Current bindings (logger name + child bindings + module/correlationId). */
227
327
  bindings(): Record<string, unknown> {
228
328
  const out: Record<string, unknown> = {
@@ -299,11 +399,24 @@ export class Logger {
299
399
  silent(message: string, ...values: unknown[]): void;
300
400
  silent(): void {}
301
401
 
302
- /** 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
+ */
303
411
  #threshold(): number {
304
- 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;
305
418
  if (raw === "silent") return levelThreshold("silent");
306
- if (typeof raw === "string" && isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
419
+ if (isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
307
420
  return LOG_LEVEL_ORDER.info;
308
421
  }
309
422
 
@@ -321,17 +434,45 @@ export class Logger {
321
434
  arg0: unknown,
322
435
  rest: unknown[],
323
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";
324
455
  if (arg0 instanceof Error) {
325
456
  const message =
326
457
  typeof rest[0] === "string"
327
458
  ? format(rest[0], ...rest.slice(1))
328
459
  : arg0.message;
329
- return { message, mergingObject: { err: arg0 } };
460
+ return { message, mergingObject: { [errorKey]: arg0 }, given: true };
330
461
  }
331
462
  if (isMergeableObject(arg0)) {
332
- const message =
333
- typeof rest[0] === "string" ? format(rest[0], ...rest.slice(1)) : "";
334
- 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 };
335
476
  }
336
477
 
337
478
  const template = typeof arg0 === "string" ? arg0 : String(arg0);
@@ -340,17 +481,35 @@ export class Logger {
340
481
  isMergeableObject(rest[0]) &&
341
482
  !PRINTF_TOKEN.test(template)
342
483
  ) {
343
- return { message: template, mergingObject: rest[0] };
484
+ return { message: template, mergingObject: rest[0], given: true };
344
485
  }
345
486
  const message = rest.length > 0 ? format(template, ...rest) : template;
346
- 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 };
347
503
  }
348
504
 
349
505
  #applySerializers(bag: Record<string, unknown>): Record<string, unknown> {
350
506
  const serializers = { ...DEFAULT_SERIALIZERS, ...this.#config.serializers };
507
+ const errorKey = this.#config.errorKey ?? "err";
351
508
  let out: Record<string, unknown> | null = null;
352
509
  for (const key of Object.keys(bag)) {
353
- 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);
354
513
  if (serializer) {
355
514
  if (!out) out = { ...bag };
356
515
  out[key] = serializer(bag[key]);
@@ -361,23 +520,36 @@ export class Logger {
361
520
 
362
521
  #applyRedact(bag: Record<string, unknown>): Record<string, unknown> {
363
522
  if (this.#redactPaths.length === 0) return bag;
364
- const redact = this.#config.redact;
365
- const censor =
366
- redact === undefined || Array.isArray(redact)
367
- ? "[Redacted]"
368
- : (redact.censor ?? "[Redacted]");
369
523
  let out: unknown = bag;
370
524
  for (const tokens of this.#redactPaths) {
371
- out = redactPath(out, tokens, censor);
525
+ out = redactPath(out, tokens, this.#redactAction);
372
526
  }
373
527
  return isMergeableObject(out) ? out : bag;
374
528
  }
375
529
 
376
- #write(level: LogLevel, arg0: unknown, rest: unknown[]): void {
530
+ #write(
531
+ level: LogLevel,
532
+ arg0: unknown,
533
+ rest: unknown[],
534
+ viaHook = false,
535
+ ): void {
377
536
  if (!this.isEnabled) return;
378
537
  if (LOG_LEVEL_ORDER[level] < this.#threshold()) return;
379
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
+
380
551
  const { message, mergingObject } = this.#resolveArgs(arg0, rest);
552
+ const merged = this.#withMixin(mergingObject ?? {}, level);
381
553
 
382
554
  let bag: Record<string, unknown> = {
383
555
  // The name a multi-logger config gave this logger. It was assigned by
@@ -386,7 +558,7 @@ export class Logger {
386
558
  // pino carries it as a binding; a merging object still wins over it.
387
559
  ...(this.#config.name !== undefined ? { name: this.#config.name } : {}),
388
560
  ...this.#bindings,
389
- ...(mergingObject ?? {}),
561
+ ...merged,
390
562
  };
391
563
  bag = this.#applySerializers(bag);
392
564
  bag = this.#applyRedact(bag);
@@ -402,6 +574,14 @@ export class Logger {
402
574
  timestamp: new Date().toISOString(),
403
575
  };
404
576
 
577
+ if (this.#lineOptions !== undefined) {
578
+ attachLineOptions(entry, this.#lineOptions);
579
+ }
580
+
581
+ // Observers before the channels: a channel that throws falls back to
582
+ // stderr, and an observer must not be skipped by that path.
583
+ if (hasLogListeners()) emitLog(entry);
584
+
405
585
  for (const channel of this.#config.channels ?? []) {
406
586
  try {
407
587
  channel.write(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
  }