@c9up/spectrum 0.1.7 → 0.1.9
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/Logger.d.ts +53 -18
- package/dist/Logger.d.ts.map +1 -1
- package/dist/Logger.js +230 -50
- package/dist/Logger.js.map +1 -1
- package/dist/LoggerManager.d.ts +20 -0
- package/dist/LoggerManager.d.ts.map +1 -0
- package/dist/LoggerManager.js +39 -0
- package/dist/LoggerManager.js.map +1 -0
- package/dist/SpectrumProvider.d.ts +1 -1
- package/dist/SpectrumProvider.d.ts.map +1 -1
- package/dist/SpectrumProvider.js +58 -22
- package/dist/SpectrumProvider.js.map +1 -1
- package/dist/channels/ConsoleChannel.d.ts.map +1 -1
- package/dist/channels/ConsoleChannel.js +11 -10
- package/dist/channels/ConsoleChannel.js.map +1 -1
- package/dist/config.d.ts +10 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +10 -1
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/sanitize.d.ts +9 -0
- package/dist/sanitize.d.ts.map +1 -0
- package/dist/sanitize.js +17 -0
- package/dist/sanitize.js.map +1 -0
- package/dist/testing/FakeLogger.d.ts.map +1 -1
- package/dist/testing/FakeLogger.js +10 -12
- package/dist/testing/FakeLogger.js.map +1 -1
- package/dist/types.d.ts +50 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +23 -0
- package/dist/types.js.map +1 -1
- package/package.json +3 -1
- package/src/Logger.ts +291 -62
- package/src/LoggerManager.ts +47 -0
- package/src/SpectrumProvider.ts +79 -28
- package/src/channels/ConsoleChannel.ts +12 -10
- package/src/config.ts +25 -4
- package/src/index.ts +11 -1
- package/src/sanitize.ts +16 -0
- package/src/testing/FakeLogger.ts +10 -12
- package/src/types.ts +74 -4
package/src/Logger.ts
CHANGED
|
@@ -1,57 +1,178 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Spectrum Logger — structured logging with levels and correlation ID.
|
|
3
3
|
*
|
|
4
|
+
* A thin, framework-agnostic wrapper that mirrors the surface of
|
|
5
|
+
* `@adonisjs/logger` (itself a pino wrapper): object-first / message-first
|
|
6
|
+
* calls, printf interpolation, `enabled`, `redact`, `serializers`, and the
|
|
7
|
+
* `level` / `isLevelEnabled` / `child` / `bindings` API.
|
|
8
|
+
*
|
|
9
|
+
* Spectrum divergences from pino (preserved): output goes through
|
|
10
|
+
* `LogChannel[]` instead of pino transports, per-module level overrides live
|
|
11
|
+
* in `config.modules`, and the Rust log bridge feeds the same channels.
|
|
12
|
+
*
|
|
4
13
|
* @implements FR54, FR55, FR56, FR58
|
|
5
14
|
*/
|
|
6
15
|
|
|
7
|
-
import
|
|
8
|
-
import {
|
|
16
|
+
import { format } from "node:util";
|
|
17
|
+
import { sanitizeLogValue } from "./sanitize.js";
|
|
18
|
+
import type {
|
|
19
|
+
LogConfig,
|
|
20
|
+
LogEntry,
|
|
21
|
+
LogLevel,
|
|
22
|
+
LogLevelWithSilent,
|
|
23
|
+
LogSerializer,
|
|
24
|
+
} from "./types.js";
|
|
25
|
+
import { LOG_LEVEL_ORDER, levelThreshold } from "./types.js";
|
|
9
26
|
|
|
10
27
|
export type { LogLevel };
|
|
11
28
|
|
|
29
|
+
/** printf-style tokens understood by `util.format`. */
|
|
30
|
+
const PRINTF_TOKEN = /%[sdifjoOc%]/;
|
|
31
|
+
|
|
32
|
+
function isLogLevel(value: string): value is LogLevel {
|
|
33
|
+
return value in LOG_LEVEL_ORDER;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A plain object usable as a merging object (excludes arrays and Errors). */
|
|
37
|
+
function isMergeableObject(value: unknown): value is Record<string, unknown> {
|
|
38
|
+
return (
|
|
39
|
+
typeof value === "object" &&
|
|
40
|
+
value !== null &&
|
|
41
|
+
!Array.isArray(value) &&
|
|
42
|
+
!(value instanceof Error)
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
12
46
|
/**
|
|
13
|
-
* Serialize an
|
|
14
|
-
*
|
|
15
|
-
* usefully otherwise. Other data passes through untouched. Returns a new object;
|
|
16
|
-
* the caller's data is not mutated.
|
|
47
|
+
* Serialize an Error into a plain `{ name, message, stack }` — the pino `err`
|
|
48
|
+
* serializer parity. Non-Error values pass through untouched.
|
|
17
49
|
*/
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
50
|
+
function serializeError(value: unknown): unknown {
|
|
51
|
+
if (value instanceof Error) {
|
|
52
|
+
return { name: value.name, message: value.message, stack: value.stack };
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const DEFAULT_SERIALIZERS: Record<string, LogSerializer> = {
|
|
58
|
+
err: serializeError,
|
|
59
|
+
error: serializeError,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Copy-on-write redaction of a single dot-path. Never mutates the input; only
|
|
64
|
+
* the objects along the path are shallow-copied.
|
|
65
|
+
*/
|
|
66
|
+
function redactPath(
|
|
67
|
+
obj: Record<string, unknown>,
|
|
68
|
+
path: string,
|
|
69
|
+
censor: string,
|
|
70
|
+
): Record<string, unknown> {
|
|
71
|
+
const dot = path.indexOf(".");
|
|
72
|
+
const head = dot === -1 ? path : path.slice(0, dot);
|
|
73
|
+
if (!(head in obj)) return obj;
|
|
74
|
+
|
|
75
|
+
const copy: Record<string, unknown> = { ...obj };
|
|
76
|
+
if (dot === -1) {
|
|
77
|
+
copy[head] = censor;
|
|
78
|
+
} else {
|
|
79
|
+
const child = copy[head];
|
|
80
|
+
if (isMergeableObject(child)) {
|
|
81
|
+
copy[head] = redactPath(child, path.slice(dot + 1), censor);
|
|
29
82
|
}
|
|
30
83
|
}
|
|
31
|
-
return
|
|
84
|
+
return copy;
|
|
32
85
|
}
|
|
33
86
|
|
|
34
87
|
export class Logger {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
88
|
+
#config: LogConfig;
|
|
89
|
+
#module: string;
|
|
90
|
+
#correlationId?: string;
|
|
91
|
+
#bindings: Record<string, unknown>;
|
|
92
|
+
|
|
93
|
+
constructor(
|
|
94
|
+
config: LogConfig,
|
|
95
|
+
module = "app",
|
|
96
|
+
correlationId?: string,
|
|
97
|
+
bindings: Record<string, unknown> = {},
|
|
98
|
+
) {
|
|
99
|
+
this.#config = config;
|
|
100
|
+
this.#module = module;
|
|
101
|
+
this.#correlationId = correlationId;
|
|
102
|
+
this.#bindings = bindings;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Whether the logger is enabled. When false every log call is a no-op. */
|
|
106
|
+
get isEnabled(): boolean {
|
|
107
|
+
return this.#config.enabled !== false;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The configured level for this logger. */
|
|
111
|
+
get level(): LogLevelWithSilent {
|
|
112
|
+
return this.#config.level ?? "info";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
set level(level: LogLevelWithSilent) {
|
|
116
|
+
this.#config.level = level;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Numeric value of the current level (`silent` → +Infinity). */
|
|
120
|
+
get levelNumber(): number {
|
|
121
|
+
return levelThreshold(this.level);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A pino-style mapping of level labels and values. */
|
|
125
|
+
get levels(): {
|
|
126
|
+
values: Record<string, number>;
|
|
127
|
+
labels: Record<number, string>;
|
|
128
|
+
} {
|
|
129
|
+
const labels: Record<number, string> = {};
|
|
130
|
+
for (const [label, value] of Object.entries(LOG_LEVEL_ORDER)) {
|
|
131
|
+
labels[value] = label;
|
|
132
|
+
}
|
|
133
|
+
return { values: { ...LOG_LEVEL_ORDER }, labels };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Whether a given level would be emitted for this logger + module. */
|
|
137
|
+
isLevelEnabled(level: LogLevel): boolean {
|
|
138
|
+
if (!this.isEnabled) return false;
|
|
139
|
+
return LOG_LEVEL_ORDER[level] >= this.#threshold();
|
|
140
|
+
}
|
|
38
141
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
142
|
+
/**
|
|
143
|
+
* Run `callback` only when `level` is enabled — useful to guard expensive
|
|
144
|
+
* log-data computation.
|
|
145
|
+
*/
|
|
146
|
+
ifLevelEnabled(level: LogLevel, callback: (logger: this) => void): void {
|
|
147
|
+
if (this.isLevelEnabled(level)) callback(this);
|
|
43
148
|
}
|
|
44
149
|
|
|
45
150
|
/**
|
|
46
|
-
* Create a child logger
|
|
47
|
-
*
|
|
151
|
+
* Create a child logger. Accepts arbitrary bindings that are merged into
|
|
152
|
+
* every entry; `module` and `correlationId` are honoured as conventions.
|
|
153
|
+
* This is the preferred way to scope per-request logging.
|
|
48
154
|
*/
|
|
49
|
-
child(
|
|
50
|
-
return
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
155
|
+
child(bindings: Record<string, unknown> = {}): Logger {
|
|
156
|
+
if (!this.isEnabled) return this;
|
|
157
|
+
const { module, correlationId, ...rest } = bindings;
|
|
158
|
+
const nextModule = typeof module === "string" ? module : this.#module;
|
|
159
|
+
const nextCorrelation =
|
|
160
|
+
typeof correlationId === "string" ? correlationId : this.#correlationId;
|
|
161
|
+
return new Logger(this.#config, nextModule, nextCorrelation, {
|
|
162
|
+
...this.#bindings,
|
|
163
|
+
...rest,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Current bindings (child bindings + module/correlationId conventions). */
|
|
168
|
+
bindings(): Record<string, unknown> {
|
|
169
|
+
const out: Record<string, unknown> = {
|
|
170
|
+
...this.#bindings,
|
|
171
|
+
module: this.#module,
|
|
172
|
+
};
|
|
173
|
+
if (this.#correlationId !== undefined)
|
|
174
|
+
out.correlationId = this.#correlationId;
|
|
175
|
+
return out;
|
|
55
176
|
}
|
|
56
177
|
|
|
57
178
|
/**
|
|
@@ -59,61 +180,169 @@ export class Logger {
|
|
|
59
180
|
* Prefer child() for per-request scoping to avoid shared-state mutation.
|
|
60
181
|
*/
|
|
61
182
|
setCorrelationId(id: string): void {
|
|
62
|
-
this
|
|
183
|
+
this.#correlationId = id;
|
|
63
184
|
}
|
|
64
185
|
|
|
65
|
-
|
|
66
|
-
|
|
186
|
+
log(
|
|
187
|
+
level: LogLevel,
|
|
188
|
+
mergingObject: unknown,
|
|
189
|
+
message?: string,
|
|
190
|
+
...values: unknown[]
|
|
191
|
+
): void;
|
|
192
|
+
log(level: LogLevel, message: string, ...values: unknown[]): void;
|
|
193
|
+
log(level: LogLevel, arg0: unknown, ...rest: unknown[]): void {
|
|
194
|
+
this.#write(level, arg0, rest);
|
|
67
195
|
}
|
|
68
196
|
|
|
69
|
-
|
|
70
|
-
|
|
197
|
+
trace(mergingObject: unknown, message?: string, ...values: unknown[]): void;
|
|
198
|
+
trace(message: string, ...values: unknown[]): void;
|
|
199
|
+
trace(arg0: unknown, ...rest: unknown[]): void {
|
|
200
|
+
this.#write("trace", arg0, rest);
|
|
71
201
|
}
|
|
72
202
|
|
|
73
|
-
|
|
74
|
-
|
|
203
|
+
debug(mergingObject: unknown, message?: string, ...values: unknown[]): void;
|
|
204
|
+
debug(message: string, ...values: unknown[]): void;
|
|
205
|
+
debug(arg0: unknown, ...rest: unknown[]): void {
|
|
206
|
+
this.#write("debug", arg0, rest);
|
|
75
207
|
}
|
|
76
208
|
|
|
77
|
-
|
|
78
|
-
|
|
209
|
+
info(mergingObject: unknown, message?: string, ...values: unknown[]): void;
|
|
210
|
+
info(message: string, ...values: unknown[]): void;
|
|
211
|
+
info(arg0: unknown, ...rest: unknown[]): void {
|
|
212
|
+
this.#write("info", arg0, rest);
|
|
79
213
|
}
|
|
80
214
|
|
|
81
|
-
|
|
82
|
-
|
|
215
|
+
warn(mergingObject: unknown, message?: string, ...values: unknown[]): void;
|
|
216
|
+
warn(message: string, ...values: unknown[]): void;
|
|
217
|
+
warn(arg0: unknown, ...rest: unknown[]): void {
|
|
218
|
+
this.#write("warn", arg0, rest);
|
|
83
219
|
}
|
|
84
220
|
|
|
85
|
-
|
|
86
|
-
|
|
221
|
+
error(mergingObject: unknown, message?: string, ...values: unknown[]): void;
|
|
222
|
+
error(message: string, ...values: unknown[]): void;
|
|
223
|
+
error(arg0: unknown, ...rest: unknown[]): void {
|
|
224
|
+
this.#write("error", arg0, rest);
|
|
87
225
|
}
|
|
88
226
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
227
|
+
fatal(mergingObject: unknown, message?: string, ...values: unknown[]): void;
|
|
228
|
+
fatal(message: string, ...values: unknown[]): void;
|
|
229
|
+
fatal(arg0: unknown, ...rest: unknown[]): void {
|
|
230
|
+
this.#write("fatal", arg0, rest);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** No-op — pino API-surface parity for the `silent` level. */
|
|
234
|
+
silent(): void {}
|
|
235
|
+
|
|
236
|
+
/** Resolve the numeric threshold for this logger + module. */
|
|
237
|
+
#threshold(): number {
|
|
238
|
+
const raw = this.#config.modules?.[this.#module] ?? this.#config.level;
|
|
239
|
+
if (raw === "silent") return levelThreshold("silent");
|
|
240
|
+
if (typeof raw === "string" && isLogLevel(raw)) return LOG_LEVEL_ORDER[raw];
|
|
241
|
+
return LOG_LEVEL_ORDER.info;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Resolve a call's args into a message string and an optional merging object.
|
|
246
|
+
*
|
|
247
|
+
* - `(object, message?, ...values)` → object merged at root (pino).
|
|
248
|
+
* - `(error, message?, ...values)` → `{ err }` merged (pino err serializer).
|
|
249
|
+
* - `(message, ...values)` → printf via `util.format` (pino).
|
|
250
|
+
* - `(message, singleObject)` with no printf token → merged as structured
|
|
251
|
+
* fields. This is spectrum's message-first ergonomic (ream ContextLogger
|
|
252
|
+
* particularity) preserved on top of pino's message-first form.
|
|
253
|
+
*/
|
|
254
|
+
#resolveArgs(
|
|
255
|
+
arg0: unknown,
|
|
256
|
+
rest: unknown[],
|
|
257
|
+
): { message: string; mergingObject?: Record<string, unknown> } {
|
|
258
|
+
if (arg0 instanceof Error) {
|
|
259
|
+
const message =
|
|
260
|
+
typeof rest[0] === "string"
|
|
261
|
+
? format(rest[0], ...rest.slice(1))
|
|
262
|
+
: arg0.message;
|
|
263
|
+
return { message, mergingObject: { err: arg0 } };
|
|
264
|
+
}
|
|
265
|
+
if (isMergeableObject(arg0)) {
|
|
266
|
+
const message =
|
|
267
|
+
typeof rest[0] === "string" ? format(rest[0], ...rest.slice(1)) : "";
|
|
268
|
+
return { message, mergingObject: arg0 };
|
|
100
269
|
}
|
|
101
270
|
|
|
271
|
+
const template = typeof arg0 === "string" ? arg0 : String(arg0);
|
|
272
|
+
if (
|
|
273
|
+
rest.length === 1 &&
|
|
274
|
+
isMergeableObject(rest[0]) &&
|
|
275
|
+
!PRINTF_TOKEN.test(template)
|
|
276
|
+
) {
|
|
277
|
+
return { message: template, mergingObject: rest[0] };
|
|
278
|
+
}
|
|
279
|
+
const message = rest.length > 0 ? format(template, ...rest) : template;
|
|
280
|
+
return { message };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
#applySerializers(bag: Record<string, unknown>): Record<string, unknown> {
|
|
284
|
+
const serializers = { ...DEFAULT_SERIALIZERS, ...this.#config.serializers };
|
|
285
|
+
let out: Record<string, unknown> | null = null;
|
|
286
|
+
for (const key of Object.keys(bag)) {
|
|
287
|
+
const serializer = serializers[key];
|
|
288
|
+
if (serializer) {
|
|
289
|
+
if (!out) out = { ...bag };
|
|
290
|
+
out[key] = serializer(bag[key]);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return out ?? bag;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
#applyRedact(bag: Record<string, unknown>): Record<string, unknown> {
|
|
297
|
+
const redact = this.#config.redact;
|
|
298
|
+
if (!redact) return bag;
|
|
299
|
+
const paths = Array.isArray(redact) ? redact : redact.paths;
|
|
300
|
+
if (paths.length === 0) return bag;
|
|
301
|
+
const censor = Array.isArray(redact)
|
|
302
|
+
? "[Redacted]"
|
|
303
|
+
: (redact.censor ?? "[Redacted]");
|
|
304
|
+
let out = bag;
|
|
305
|
+
for (const path of paths) {
|
|
306
|
+
out = redactPath(out, path, censor);
|
|
307
|
+
}
|
|
308
|
+
return out;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
#write(level: LogLevel, arg0: unknown, rest: unknown[]): void {
|
|
312
|
+
if (!this.isEnabled) return;
|
|
313
|
+
if (LOG_LEVEL_ORDER[level] < this.#threshold()) return;
|
|
314
|
+
|
|
315
|
+
const { message, mergingObject } = this.#resolveArgs(arg0, rest);
|
|
316
|
+
|
|
317
|
+
let bag: Record<string, unknown> = {
|
|
318
|
+
...this.#bindings,
|
|
319
|
+
...(mergingObject ?? {}),
|
|
320
|
+
};
|
|
321
|
+
bag = this.#applySerializers(bag);
|
|
322
|
+
bag = this.#applyRedact(bag);
|
|
323
|
+
|
|
324
|
+
// Structural fields are assigned AFTER the merged bag so a merging object
|
|
325
|
+
// can never overwrite level/module/timestamp (log-injection hardening).
|
|
102
326
|
const entry: LogEntry = {
|
|
327
|
+
...bag,
|
|
103
328
|
level,
|
|
104
329
|
message,
|
|
105
|
-
module: this
|
|
106
|
-
correlationId: this
|
|
330
|
+
module: this.#module,
|
|
331
|
+
correlationId: this.#correlationId,
|
|
107
332
|
timestamp: new Date().toISOString(),
|
|
108
|
-
data: serializeErr(data),
|
|
109
333
|
};
|
|
110
334
|
|
|
111
|
-
for (const channel of this
|
|
335
|
+
for (const channel of this.#config.channels ?? []) {
|
|
112
336
|
try {
|
|
113
337
|
channel.write(entry);
|
|
114
338
|
} catch (err) {
|
|
339
|
+
// Sanitize every interpolated value — a channel name / message /
|
|
340
|
+
// error carrying CR/LF or ANSI escapes could otherwise forge log
|
|
341
|
+
// lines here (the fallback bypasses the channel's own sanitizer).
|
|
115
342
|
process.stderr.write(
|
|
116
|
-
`[Spectrum] Channel '${channel.name}' failed for: ${
|
|
343
|
+
`[Spectrum] Channel '${sanitizeLogValue(channel.name)}' failed for: ${sanitizeLogValue(
|
|
344
|
+
message,
|
|
345
|
+
)} — ${sanitizeLogValue(String(err))}\n`,
|
|
117
346
|
);
|
|
118
347
|
}
|
|
119
348
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logger manager — manages multiple named `Logger` instances from a single
|
|
3
|
+
* multi-logger config. Mirrors `@adonisjs/logger`'s `LoggerManager`: extends
|
|
4
|
+
* `Logger` (so the manager itself proxies the default logger), caches created
|
|
5
|
+
* loggers forever, and exposes `use()` / `create()`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { Logger } from "./Logger.js";
|
|
9
|
+
import type { LogConfig, LoggerManagerConfig } from "./types.js";
|
|
10
|
+
|
|
11
|
+
export class LoggerManager extends Logger {
|
|
12
|
+
#config: LoggerManagerConfig;
|
|
13
|
+
#loggers: Map<string, Logger> = new Map();
|
|
14
|
+
|
|
15
|
+
constructor(config: LoggerManagerConfig) {
|
|
16
|
+
super(config.loggers[config.default]);
|
|
17
|
+
this.#config = config;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Get a named logger (or the default logger when no name is given). */
|
|
21
|
+
use(name?: string): Logger {
|
|
22
|
+
const key = name ?? this.#config.default;
|
|
23
|
+
|
|
24
|
+
const cached = this.#loggers.get(key);
|
|
25
|
+
if (cached) return cached;
|
|
26
|
+
|
|
27
|
+
const config = this.#config.loggers[key];
|
|
28
|
+
if (!config) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
`[spectrum] Unknown logger "${key}". Registered: ${Object.keys(this.#config.loggers).join(", ")}`,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
if (!config.name) config.name = key;
|
|
34
|
+
|
|
35
|
+
const logger = this.create(config);
|
|
36
|
+
this.#loggers.set(key, logger);
|
|
37
|
+
return logger;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Create a logger from a config. The returned instance is NOT cached or
|
|
42
|
+
* managed by the manager.
|
|
43
|
+
*/
|
|
44
|
+
create(config: LogConfig): Logger {
|
|
45
|
+
return new Logger(config);
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/SpectrumProvider.ts
CHANGED
|
@@ -1,14 +1,26 @@
|
|
|
1
1
|
import { ConsoleChannel } from "./channels/ConsoleChannel.js";
|
|
2
2
|
import { Logger } from "./Logger.js";
|
|
3
|
+
import { LoggerManager } from "./LoggerManager.js";
|
|
3
4
|
import { setLogger } from "./services/main.js";
|
|
4
|
-
import type {
|
|
5
|
+
import type {
|
|
6
|
+
LogChannel,
|
|
7
|
+
LogConfig,
|
|
8
|
+
LoggerManagerConfig,
|
|
9
|
+
LogLevelWithSilent,
|
|
10
|
+
} from "./types.js";
|
|
5
11
|
import { LOG_LEVEL_ORDER } from "./types.js";
|
|
6
12
|
|
|
7
|
-
const VALID_LEVELS = new Set<string>(
|
|
13
|
+
const VALID_LEVELS = new Set<string>([
|
|
14
|
+
...Object.keys(LOG_LEVEL_ORDER),
|
|
15
|
+
"silent",
|
|
16
|
+
]);
|
|
8
17
|
|
|
9
|
-
function
|
|
10
|
-
|
|
11
|
-
|
|
18
|
+
function isValidLevel(raw: unknown): raw is LogLevelWithSilent {
|
|
19
|
+
return typeof raw === "string" && VALID_LEVELS.has(raw);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function resolveLogLevel(raw: unknown): LogLevelWithSilent {
|
|
23
|
+
return isValidLevel(raw) ? raw : "info";
|
|
12
24
|
}
|
|
13
25
|
|
|
14
26
|
/** A channel that owns a resource (e.g. a FileChannel WriteStream) to release on shutdown. */
|
|
@@ -16,9 +28,22 @@ function hasClose(ch: LogChannel): ch is LogChannel & { close(): void } {
|
|
|
16
28
|
return "close" in ch && typeof ch.close === "function";
|
|
17
29
|
}
|
|
18
30
|
|
|
31
|
+
function isManagerConfig(value: unknown): value is LoggerManagerConfig {
|
|
32
|
+
return (
|
|
33
|
+
typeof value === "object" &&
|
|
34
|
+
value !== null &&
|
|
35
|
+
"loggers" in value &&
|
|
36
|
+
"default" in value
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isPartialLogConfig(value: unknown): value is Partial<LogConfig> {
|
|
41
|
+
return typeof value === "object" && value !== null;
|
|
42
|
+
}
|
|
43
|
+
|
|
19
44
|
interface SpectrumContainer {
|
|
20
45
|
singleton(token: unknown, factory: () => unknown): void;
|
|
21
|
-
resolve<T = unknown>(token: unknown): T
|
|
46
|
+
resolve<T = unknown>(token: unknown): Promise<T>;
|
|
22
47
|
}
|
|
23
48
|
|
|
24
49
|
interface SpectrumConfigStore {
|
|
@@ -36,35 +61,23 @@ export default class SpectrumProvider {
|
|
|
36
61
|
constructor(protected app: SpectrumAppContext) {}
|
|
37
62
|
|
|
38
63
|
register() {
|
|
39
|
-
const
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
// fall back to a pretty console channel only when none are supplied.
|
|
46
|
-
// Previously this was hardcoded and config.channels was silently ignored.
|
|
47
|
-
this.#channels =
|
|
48
|
-
config?.channels && config.channels.length > 0
|
|
49
|
-
? config.channels
|
|
50
|
-
: [new ConsoleChannel("pretty")];
|
|
51
|
-
const channels = this.#channels;
|
|
52
|
-
|
|
53
|
-
// Forward per-module level overrides (config.logger.modules) — Logger.log
|
|
54
|
-
// gates each module's level off config.modules?.[module]; dropping it here
|
|
55
|
-
// silently disables every per-module override in production.
|
|
56
|
-
const modules = config?.modules;
|
|
57
|
-
this.app.container.singleton(
|
|
58
|
-
Logger,
|
|
59
|
-
() => new Logger({ level, channels, modules }),
|
|
64
|
+
const raw = this.app.config.get<unknown>("logger");
|
|
65
|
+
const managerConfig = this.#normalize(raw);
|
|
66
|
+
|
|
67
|
+
// Collect every channel across all loggers so shutdown can release them.
|
|
68
|
+
this.#channels = Object.values(managerConfig.loggers).flatMap(
|
|
69
|
+
(logger) => logger.channels ?? [],
|
|
60
70
|
);
|
|
71
|
+
|
|
72
|
+
const manager = new LoggerManager(managerConfig);
|
|
73
|
+
this.app.container.singleton(Logger, () => manager);
|
|
61
74
|
this.app.container.singleton("logger", () => {
|
|
62
75
|
return this.app.container.resolve<Logger>(Logger);
|
|
63
76
|
});
|
|
64
77
|
}
|
|
65
78
|
|
|
66
79
|
async boot() {
|
|
67
|
-
setLogger(this.app.container.resolve<Logger>(Logger));
|
|
80
|
+
setLogger(await this.app.container.resolve<Logger>(Logger));
|
|
68
81
|
}
|
|
69
82
|
|
|
70
83
|
/** Release channel resources (e.g. FileChannel WriteStreams) on shutdown. */
|
|
@@ -73,4 +86,42 @@ export default class SpectrumProvider {
|
|
|
73
86
|
if (hasClose(channel)) channel.close();
|
|
74
87
|
}
|
|
75
88
|
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Normalize the raw `logger` config into a multi-logger config, filling in
|
|
92
|
+
* env-based level fallback and a default console channel. Accepts the Adonis
|
|
93
|
+
* multi-logger shape or the legacy flat shape (or nothing).
|
|
94
|
+
*/
|
|
95
|
+
#normalize(raw: unknown): LoggerManagerConfig {
|
|
96
|
+
if (isManagerConfig(raw)) {
|
|
97
|
+
const loggers: Record<string, LogConfig> = {};
|
|
98
|
+
for (const [name, cfg] of Object.entries(raw.loggers)) {
|
|
99
|
+
loggers[name] = this.#normalizeLogger(cfg);
|
|
100
|
+
}
|
|
101
|
+
// Fail loud at boot if `default` references a missing logger — else
|
|
102
|
+
// LoggerManager builds with `loggers[default] === undefined` and crashes
|
|
103
|
+
// with a cryptic TypeError on the first log. Mirrors defineConfig().
|
|
104
|
+
if (!loggers[raw.default]) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
`[spectrum] Missing "loggers.${raw.default}". It is referenced by the "default" logger`,
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
return { default: raw.default, loggers };
|
|
110
|
+
}
|
|
111
|
+
const flat = isPartialLogConfig(raw) ? raw : {};
|
|
112
|
+
return { default: "app", loggers: { app: this.#normalizeLogger(flat) } };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
#normalizeLogger(cfg: Partial<LogConfig>): LogConfig {
|
|
116
|
+
// Honour the configured channels; fall back to a pretty console channel
|
|
117
|
+
// only when none are supplied.
|
|
118
|
+
const channels =
|
|
119
|
+
cfg.channels && cfg.channels.length > 0
|
|
120
|
+
? cfg.channels
|
|
121
|
+
: [new ConsoleChannel("pretty")];
|
|
122
|
+
const level = isValidLevel(cfg.level)
|
|
123
|
+
? cfg.level
|
|
124
|
+
: resolveLogLevel(process.env.LOG_LEVEL);
|
|
125
|
+
return { ...cfg, level, channels };
|
|
126
|
+
}
|
|
76
127
|
}
|
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
* @implements FR57, FR58
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
import { sanitizeLogValue } from "../sanitize.js";
|
|
7
8
|
import type { LogChannel, LogEntry } from "../types.js";
|
|
9
|
+
import { logEntryExtras } from "../types.js";
|
|
8
10
|
|
|
9
11
|
export class ConsoleChannel implements LogChannel {
|
|
10
12
|
name = "console";
|
|
@@ -23,7 +25,8 @@ export class ConsoleChannel implements LogChannel {
|
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
#writeJson(entry: LogEntry): void {
|
|
26
|
-
//
|
|
28
|
+
// Structural fields first, then merged root fields spread flat (pino
|
|
29
|
+
// output parity). Legacy `data` (if present) stays under its own key.
|
|
27
30
|
const output = JSON.stringify({
|
|
28
31
|
timestamp: entry.timestamp,
|
|
29
32
|
level: entry.level,
|
|
@@ -31,19 +34,13 @@ export class ConsoleChannel implements LogChannel {
|
|
|
31
34
|
message: entry.message,
|
|
32
35
|
correlationId: entry.correlationId,
|
|
33
36
|
data: entry.data,
|
|
37
|
+
...logEntryExtras(entry),
|
|
34
38
|
});
|
|
35
39
|
this.#writeToStream(entry.level, `${output}\n`);
|
|
36
40
|
}
|
|
37
41
|
|
|
38
42
|
#sanitize(str: string): string {
|
|
39
|
-
|
|
40
|
-
// it via String.fromCharCode rather than a /\x1b/ regex (Biome's
|
|
41
|
-
// noControlCharactersInRegex rule rightly flags the literal form).
|
|
42
|
-
const ESC = String.fromCharCode(0x1b);
|
|
43
|
-
return str
|
|
44
|
-
.replace(/\r/g, "\\r")
|
|
45
|
-
.replace(/\n/g, "\\n")
|
|
46
|
-
.replaceAll(ESC, "[ESC]");
|
|
43
|
+
return sanitizeLogValue(str);
|
|
47
44
|
}
|
|
48
45
|
|
|
49
46
|
#writePretty(entry: LogEntry): void {
|
|
@@ -60,7 +57,12 @@ export class ConsoleChannel implements LogChannel {
|
|
|
60
57
|
: entry.correlationId
|
|
61
58
|
: "";
|
|
62
59
|
const cid = cidRaw ? ` cid=${this.#sanitize(cidRaw)}` : "";
|
|
63
|
-
|
|
60
|
+
// Prefer legacy `data`; otherwise render the merged root fields. JSON
|
|
61
|
+
// encoding escapes control chars, so no CRLF can leak into the line.
|
|
62
|
+
const extras = logEntryExtras(entry);
|
|
63
|
+
const payload =
|
|
64
|
+
entry.data ?? (Object.keys(extras).length > 0 ? extras : undefined);
|
|
65
|
+
const dataStr = payload ? ` ${JSON.stringify(payload)}` : "";
|
|
64
66
|
const message = this.#sanitize(entry.message);
|
|
65
67
|
const module = this.#sanitize(entry.module);
|
|
66
68
|
|