@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.
- package/README.md +23 -6
- package/dist/Logger.d.ts +6 -2
- package/dist/Logger.d.ts.map +1 -1
- package/dist/Logger.js +195 -72
- package/dist/Logger.js.map +1 -1
- package/dist/LoggerManager.d.ts +5 -0
- package/dist/LoggerManager.d.ts.map +1 -1
- package/dist/LoggerManager.js +10 -3
- package/dist/LoggerManager.js.map +1 -1
- package/dist/RustLogBridge.d.ts +27 -2
- package/dist/RustLogBridge.d.ts.map +1 -1
- package/dist/RustLogBridge.js +45 -31
- package/dist/RustLogBridge.js.map +1 -1
- package/dist/SpectrumProvider.d.ts +6 -2
- package/dist/SpectrumProvider.d.ts.map +1 -1
- package/dist/SpectrumProvider.js +51 -11
- package/dist/SpectrumProvider.js.map +1 -1
- package/dist/channels/ConsoleChannel.d.ts +8 -1
- package/dist/channels/ConsoleChannel.d.ts.map +1 -1
- package/dist/channels/ConsoleChannel.js +18 -14
- package/dist/channels/ConsoleChannel.js.map +1 -1
- package/dist/channels/FileChannel.d.ts +32 -9
- package/dist/channels/FileChannel.d.ts.map +1 -1
- package/dist/channels/FileChannel.js +264 -202
- package/dist/channels/FileChannel.js.map +1 -1
- package/dist/errors.d.ts +9 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +38 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +55 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/jsonLine.d.ts +49 -0
- package/dist/jsonLine.d.ts.map +1 -0
- package/dist/jsonLine.js +164 -0
- package/dist/jsonLine.js.map +1 -0
- package/dist/redact.d.ts +16 -3
- package/dist/redact.d.ts.map +1 -1
- package/dist/redact.js +121 -10
- package/dist/redact.js.map +1 -1
- package/dist/sanitize.d.ts +11 -5
- package/dist/sanitize.d.ts.map +1 -1
- package/dist/sanitize.js +36 -12
- package/dist/sanitize.js.map +1 -1
- package/dist/services/main.d.ts.map +1 -1
- package/dist/services/main.js +12 -1
- package/dist/services/main.js.map +1 -1
- package/dist/stdSerializers.d.ts +47 -0
- package/dist/stdSerializers.d.ts.map +1 -0
- package/dist/stdSerializers.js +128 -0
- package/dist/stdSerializers.js.map +1 -0
- package/dist/stringify.d.ts +33 -0
- package/dist/stringify.d.ts.map +1 -0
- package/dist/stringify.js +148 -0
- package/dist/stringify.js.map +1 -0
- package/dist/targets.d.ts +29 -7
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +130 -31
- package/dist/targets.js.map +1 -1
- package/dist/testing/FakeLogger.js +20 -5
- package/dist/testing/FakeLogger.js.map +1 -1
- package/dist/types.d.ts +71 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +18 -2
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/Logger.ts +259 -79
- package/src/LoggerManager.ts +10 -3
- package/src/RustLogBridge.ts +59 -30
- package/src/SpectrumProvider.ts +69 -17
- package/src/channels/ConsoleChannel.ts +30 -14
- package/src/channels/FileChannel.ts +319 -220
- package/src/errors.ts +13 -0
- package/src/events.ts +62 -0
- package/src/index.ts +18 -3
- package/src/jsonLine.ts +222 -0
- package/src/redact.ts +133 -9
- package/src/sanitize.ts +36 -12
- package/src/services/main.ts +13 -1
- package/src/stdSerializers.ts +146 -0
- package/src/stringify.ts +175 -0
- package/src/targets.ts +193 -42
- package/src/testing/FakeLogger.ts +23 -5
- package/src/types.ts +97 -4
- package/stubs/config/logger.stub +1 -1
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standard serializers, in the shapes upstream's `stdSerializers` write:
|
|
3
|
+
* `err` for errors, `req` and `res` for Node's HTTP request and response.
|
|
4
|
+
*
|
|
5
|
+
* new Logger({ serializers: { req: stdSerializers.req, res: stdSerializers.res } })
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** How far down a chain of nested errors to follow. */
|
|
9
|
+
const MAX_CAUSE_DEPTH = 8;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Serialize an Error the way pino's `err` serializer does. Non-Error values
|
|
13
|
+
* pass through untouched.
|
|
14
|
+
*
|
|
15
|
+
* `{ name, message, stack }` threw away everything the error was carrying.
|
|
16
|
+
* `err.code` is usually the one field a log search is keyed on, and the `cause`
|
|
17
|
+
* of a wrapped error is the half that says what actually failed — both were
|
|
18
|
+
* dropped, silently, by a serializer whose job is to keep them.
|
|
19
|
+
*
|
|
20
|
+
* `path` holds the errors being serialized above this one. An error met again
|
|
21
|
+
* on its own path is a cycle and is written as `"[Circular]"`, as upstream
|
|
22
|
+
* skips an error it has already tagged; without it `err.self = err` was copied
|
|
23
|
+
* down to the depth limit, and an error with k such references cost k^8 copies
|
|
24
|
+
* on the logging call. An error shared by two branches is not a cycle and is
|
|
25
|
+
* written in both.
|
|
26
|
+
*/
|
|
27
|
+
export function serializeError(
|
|
28
|
+
value: unknown,
|
|
29
|
+
path: readonly Error[] = [],
|
|
30
|
+
): unknown {
|
|
31
|
+
if (!(value instanceof Error)) return value;
|
|
32
|
+
if (path.includes(value)) return "[Circular]";
|
|
33
|
+
if (path.length > MAX_CAUSE_DEPTH) return "[cause chain too deep]";
|
|
34
|
+
const below = [...path, value];
|
|
35
|
+
|
|
36
|
+
// Own ENUMERABLE properties only, which on an Error means the ones it was
|
|
37
|
+
// given: `message`, `stack` and `name` are not among them.
|
|
38
|
+
const out: Record<string, unknown> = { ...value };
|
|
39
|
+
for (const [key, nested] of Object.entries(out)) {
|
|
40
|
+
if (nested instanceof Error) out[key] = serializeError(nested, below);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Upstream reads the constructor rather than `name`, so a subclass that
|
|
44
|
+
// never assigns `this.name` is still reported as itself, and it names the
|
|
45
|
+
// field `type` — which is what an Adonis log pipeline reads.
|
|
46
|
+
out.type =
|
|
47
|
+
typeof value.constructor === "function"
|
|
48
|
+
? value.constructor.name
|
|
49
|
+
: value.name;
|
|
50
|
+
out.message = value.message;
|
|
51
|
+
out.stack = value.stack;
|
|
52
|
+
if (value instanceof AggregateError && Array.isArray(value.errors)) {
|
|
53
|
+
out.aggregateErrors = value.errors.map((each: unknown) =>
|
|
54
|
+
serializeError(each, below),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
if (value.cause !== undefined) {
|
|
58
|
+
out.cause = serializeError(value.cause, below);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
64
|
+
return typeof value === "object" && value !== null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* An HTTP request as upstream's `req` serializer writes it: id, method, url,
|
|
69
|
+
* query, params, headers and the remote address. Headers are written as they
|
|
70
|
+
* are — censoring `authorization` or a cookie is what `redact` is for.
|
|
71
|
+
*/
|
|
72
|
+
export function serializeRequest(value: unknown): unknown {
|
|
73
|
+
if (!isRecord(value)) return value;
|
|
74
|
+
const info = Reflect.get(value, "info");
|
|
75
|
+
const connection = isRecord(info) ? info : Reflect.get(value, "socket");
|
|
76
|
+
const id = Reflect.get(value, "id");
|
|
77
|
+
const originalUrl = Reflect.get(value, "originalUrl");
|
|
78
|
+
const pathValue = Reflect.get(value, "path");
|
|
79
|
+
const url = Reflect.get(value, "url");
|
|
80
|
+
const query = Reflect.get(value, "query");
|
|
81
|
+
const params = Reflect.get(value, "params");
|
|
82
|
+
return {
|
|
83
|
+
id:
|
|
84
|
+
typeof id === "function"
|
|
85
|
+
? Reflect.apply(id, value, [])
|
|
86
|
+
: (id ?? (isRecord(info) ? Reflect.get(info, "id") : undefined)),
|
|
87
|
+
method: Reflect.get(value, "method"),
|
|
88
|
+
url: originalUrl
|
|
89
|
+
? originalUrl
|
|
90
|
+
: typeof pathValue === "string"
|
|
91
|
+
? pathValue
|
|
92
|
+
: isRecord(url)
|
|
93
|
+
? (Reflect.get(url, "path") ?? url)
|
|
94
|
+
: url,
|
|
95
|
+
...(query ? { query } : {}),
|
|
96
|
+
...(params ? { params } : {}),
|
|
97
|
+
headers: Reflect.get(value, "headers"),
|
|
98
|
+
remoteAddress: isRecord(connection)
|
|
99
|
+
? Reflect.get(connection, "remoteAddress")
|
|
100
|
+
: undefined,
|
|
101
|
+
remotePort: isRecord(connection)
|
|
102
|
+
? Reflect.get(connection, "remotePort")
|
|
103
|
+
: undefined,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** An HTTP response as upstream's `res` serializer writes it: status and headers. */
|
|
108
|
+
export function serializeResponse(value: unknown): unknown {
|
|
109
|
+
if (!isRecord(value)) return value;
|
|
110
|
+
const getHeaders = Reflect.get(value, "getHeaders");
|
|
111
|
+
return {
|
|
112
|
+
statusCode: Reflect.get(value, "headersSent")
|
|
113
|
+
? Reflect.get(value, "statusCode")
|
|
114
|
+
: null,
|
|
115
|
+
headers:
|
|
116
|
+
typeof getHeaders === "function"
|
|
117
|
+
? Reflect.apply(getHeaders, value, [])
|
|
118
|
+
: Reflect.get(value, "_headers"),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export const stdSerializers: {
|
|
123
|
+
err: (value: unknown) => unknown;
|
|
124
|
+
req: (value: unknown) => unknown;
|
|
125
|
+
res: (value: unknown) => unknown;
|
|
126
|
+
} = {
|
|
127
|
+
err: (value) => serializeError(value),
|
|
128
|
+
req: serializeRequest,
|
|
129
|
+
res: serializeResponse,
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Upstream's time functions, for `timestamp`: each returns the `,"time":…`
|
|
134
|
+
* fragment a JSON line carries.
|
|
135
|
+
*/
|
|
136
|
+
export const stdTimeFunctions: {
|
|
137
|
+
epochTime: () => string;
|
|
138
|
+
unixTime: () => string;
|
|
139
|
+
isoTime: () => string;
|
|
140
|
+
nullTime: () => string;
|
|
141
|
+
} = {
|
|
142
|
+
epochTime: () => `,"time":${Date.now()}`,
|
|
143
|
+
unixTime: () => `,"time":${Math.round(Date.now() / 1000)}`,
|
|
144
|
+
isoTime: () => `,"time":"${new Date(Date.now()).toISOString()}"`,
|
|
145
|
+
nullTime: () => "",
|
|
146
|
+
};
|
package/src/stringify.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a log line is turned into JSON without ever losing it.
|
|
3
|
+
*
|
|
4
|
+
* A bare `JSON.stringify(entry)` throws on a circular reference or a BigInt,
|
|
5
|
+
* and a throw there costs the whole line — every field of it, on every
|
|
6
|
+
* channel. Circular payloads are ordinary (an ORM model with a back-reference,
|
|
7
|
+
* an HTTP client error carrying its request), so the line that explains a
|
|
8
|
+
* failure is the one most likely to vanish.
|
|
9
|
+
*
|
|
10
|
+
* pino's answer, mirrored: `JSON.stringify` first, because it is fast and
|
|
11
|
+
* exact; when it throws, the field is written again by a bounded walker that
|
|
12
|
+
* prints a cycle as `"[Circular]"`, a BigInt as a number, anything deeper than
|
|
13
|
+
* `depthLimit` as `"[Object]"` / `"[Array]"`, and stops after `edgeLimit`
|
|
14
|
+
* entries. Each top-level field falls back on its own, so one bad field does
|
|
15
|
+
* not degrade the others.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export interface StringifyLimits {
|
|
19
|
+
/** How deep the fallback walks before writing `"[Object]"`. Default 5. */
|
|
20
|
+
depthLimit: number;
|
|
21
|
+
/** How many entries of one object or array the fallback writes. Default 100. */
|
|
22
|
+
edgeLimit: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_STRINGIFY_LIMITS: StringifyLimits = {
|
|
26
|
+
depthLimit: 5,
|
|
27
|
+
edgeLimit: 100,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const UNSERIALIZABLE =
|
|
31
|
+
'"[unable to serialize, circular reference is too complex to analyze]"';
|
|
32
|
+
|
|
33
|
+
/** Whether a configured limit is one the walker can honour. */
|
|
34
|
+
export function isStringifyLimit(value: unknown): value is number {
|
|
35
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* One JSON object, never throwing. Keys whose value is `undefined` or a
|
|
40
|
+
* function are left out, as `JSON.stringify` leaves them out.
|
|
41
|
+
*/
|
|
42
|
+
export function stringifyRecord(
|
|
43
|
+
record: Record<string, unknown>,
|
|
44
|
+
limits: StringifyLimits = DEFAULT_STRINGIFY_LIMITS,
|
|
45
|
+
): string {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.stringify(record);
|
|
48
|
+
} catch {
|
|
49
|
+
// Field by field, so the fallback's limits count from each field and a
|
|
50
|
+
// field that cannot be written at all is the only one that says so.
|
|
51
|
+
let out = "";
|
|
52
|
+
for (const key of Object.keys(record)) {
|
|
53
|
+
const value = stringifyValue(readField(record, key), limits);
|
|
54
|
+
if (value === undefined) continue;
|
|
55
|
+
out += `${out === "" ? "" : ","}${JSON.stringify(key)}:${value}`;
|
|
56
|
+
}
|
|
57
|
+
return `{${out}}`;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** One value, never throwing; `undefined` when JSON would omit it. */
|
|
62
|
+
export function stringifyValue(
|
|
63
|
+
value: unknown,
|
|
64
|
+
limits: StringifyLimits = DEFAULT_STRINGIFY_LIMITS,
|
|
65
|
+
): string | undefined {
|
|
66
|
+
try {
|
|
67
|
+
return JSON.stringify(value);
|
|
68
|
+
} catch {
|
|
69
|
+
try {
|
|
70
|
+
return walk("", value, [], limits);
|
|
71
|
+
} catch {
|
|
72
|
+
return UNSERIALIZABLE;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A getter that throws is a value that cannot be written, not a lost line. */
|
|
78
|
+
function readField(record: object, key: string): unknown {
|
|
79
|
+
try {
|
|
80
|
+
return Reflect.get(record, key);
|
|
81
|
+
} catch {
|
|
82
|
+
return "[unreadable]";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function hasToJSON(value: object): value is { toJSON(key: string): unknown } {
|
|
87
|
+
return "toJSON" in value && typeof value.toJSON === "function";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function itemCount(count: number): string {
|
|
91
|
+
return count === 1 ? "1 item" : `${count} items`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The bounded fallback. `stack` holds the objects on the current path, so a
|
|
96
|
+
* value shared by two branches is written twice and only a real cycle is cut.
|
|
97
|
+
*/
|
|
98
|
+
function walk(
|
|
99
|
+
key: string,
|
|
100
|
+
input: unknown,
|
|
101
|
+
stack: object[],
|
|
102
|
+
limits: StringifyLimits,
|
|
103
|
+
): string | undefined {
|
|
104
|
+
let value = input;
|
|
105
|
+
if (typeof value === "object" && value !== null && hasToJSON(value)) {
|
|
106
|
+
value = value.toJSON(key);
|
|
107
|
+
}
|
|
108
|
+
switch (typeof value) {
|
|
109
|
+
case "string":
|
|
110
|
+
return JSON.stringify(value);
|
|
111
|
+
case "number":
|
|
112
|
+
return Number.isFinite(value) ? String(value) : "null";
|
|
113
|
+
case "boolean":
|
|
114
|
+
return value ? "true" : "false";
|
|
115
|
+
case "bigint":
|
|
116
|
+
return String(value);
|
|
117
|
+
case "object": {
|
|
118
|
+
if (value === null) return "null";
|
|
119
|
+
if (stack.includes(value)) return '"[Circular]"';
|
|
120
|
+
if (Array.isArray(value)) return walkArray(value, stack, limits);
|
|
121
|
+
return walkObject(value, stack, limits);
|
|
122
|
+
}
|
|
123
|
+
default:
|
|
124
|
+
// undefined, function, symbol: omitted, as JSON omits them.
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function walkArray(
|
|
130
|
+
value: unknown[],
|
|
131
|
+
stack: object[],
|
|
132
|
+
limits: StringifyLimits,
|
|
133
|
+
): string {
|
|
134
|
+
if (value.length === 0) return "[]";
|
|
135
|
+
if (stack.length + 1 > limits.depthLimit) return '"[Array]"';
|
|
136
|
+
stack.push(value);
|
|
137
|
+
const shown = Math.min(value.length, limits.edgeLimit);
|
|
138
|
+
const parts: string[] = [];
|
|
139
|
+
for (let i = 0; i < shown; i++) {
|
|
140
|
+
parts.push(walk(String(i), value[i], stack, limits) ?? "null");
|
|
141
|
+
}
|
|
142
|
+
if (value.length > shown) {
|
|
143
|
+
parts.push(
|
|
144
|
+
JSON.stringify(`... ${itemCount(value.length - shown)} not stringified`),
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
stack.pop();
|
|
148
|
+
return `[${parts.join(",")}]`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function walkObject(
|
|
152
|
+
value: object,
|
|
153
|
+
stack: object[],
|
|
154
|
+
limits: StringifyLimits,
|
|
155
|
+
): string {
|
|
156
|
+
const keys = Object.keys(value);
|
|
157
|
+
if (keys.length === 0) return "{}";
|
|
158
|
+
if (stack.length + 1 > limits.depthLimit) return '"[Object]"';
|
|
159
|
+
stack.push(value);
|
|
160
|
+
const shown = Math.min(keys.length, limits.edgeLimit);
|
|
161
|
+
const parts: string[] = [];
|
|
162
|
+
for (let i = 0; i < shown; i++) {
|
|
163
|
+
const key = keys[i];
|
|
164
|
+
if (key === undefined) continue;
|
|
165
|
+
const written = walk(key, readField(value, key), stack, limits);
|
|
166
|
+
if (written !== undefined) parts.push(`${JSON.stringify(key)}:${written}`);
|
|
167
|
+
}
|
|
168
|
+
if (keys.length > shown) {
|
|
169
|
+
parts.push(
|
|
170
|
+
`"...":${JSON.stringify(`${itemCount(keys.length - shown)} not stringified`)}`,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
stack.pop();
|
|
174
|
+
return `{${parts.join(",")}}`;
|
|
175
|
+
}
|
package/src/targets.ts
CHANGED
|
@@ -16,16 +16,30 @@
|
|
|
16
16
|
|
|
17
17
|
import { ConsoleChannel } from "./channels/ConsoleChannel.js";
|
|
18
18
|
import { FileChannel } from "./channels/FileChannel.js";
|
|
19
|
-
import
|
|
19
|
+
import { SpectrumError } from "./errors.js";
|
|
20
|
+
import { jsonLine } from "./jsonLine.js";
|
|
21
|
+
import type {
|
|
22
|
+
LineWritable,
|
|
23
|
+
LogChannel,
|
|
24
|
+
LogConfig,
|
|
25
|
+
LogEntry,
|
|
26
|
+
LogLevelWithSilent,
|
|
27
|
+
} from "./types.js";
|
|
20
28
|
import {
|
|
21
29
|
isLogLevelWithSilent,
|
|
22
30
|
LOG_LEVEL_ORDER,
|
|
23
31
|
levelThreshold,
|
|
24
32
|
} from "./types.js";
|
|
25
33
|
|
|
26
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* One transport entry (AdonisJS `TransportTargetOptions`).
|
|
36
|
+
*
|
|
37
|
+
* `target` names `pino-pretty` or `pino/file`, or is a {@link LogChannel}:
|
|
38
|
+
* a destination spectrum has no built-in channel for is plugged in that way,
|
|
39
|
+
* with the target's own level.
|
|
40
|
+
*/
|
|
27
41
|
export interface TransportTargetOptions {
|
|
28
|
-
target: string;
|
|
42
|
+
target: string | LogChannel;
|
|
29
43
|
options?: Record<string, unknown>;
|
|
30
44
|
level?: LogLevelWithSilent | string;
|
|
31
45
|
}
|
|
@@ -33,13 +47,20 @@ export interface TransportTargetOptions {
|
|
|
33
47
|
/** Options `targets.file()` accepts. `destination` is a path, or an fd. */
|
|
34
48
|
export interface FileTargetOptions {
|
|
35
49
|
destination?: string | number;
|
|
50
|
+
/** `false` starts the file over instead of appending. Default true. */
|
|
51
|
+
append?: boolean;
|
|
36
52
|
maxSizeBytes?: number;
|
|
37
53
|
maxFiles?: number;
|
|
54
|
+
maxBufferBytes?: number;
|
|
38
55
|
[key: string]: unknown;
|
|
39
56
|
}
|
|
40
57
|
|
|
41
|
-
/**
|
|
58
|
+
/**
|
|
59
|
+
* Options `targets.pretty()` accepts. `destination` (1 or 2) sends every
|
|
60
|
+
* level to that stream; pino-pretty's formatting options are not read.
|
|
61
|
+
*/
|
|
42
62
|
export interface PrettyTargetOptions {
|
|
63
|
+
destination?: number;
|
|
43
64
|
[key: string]: unknown;
|
|
44
65
|
}
|
|
45
66
|
|
|
@@ -126,11 +147,12 @@ class LeveledChannel implements LogChannel {
|
|
|
126
147
|
|
|
127
148
|
/**
|
|
128
149
|
* Forwarded because the wrapper is now what the provider holds, and a
|
|
129
|
-
* FileChannel that is never closed keeps its
|
|
150
|
+
* FileChannel that is never closed keeps its file open past shutdown.
|
|
151
|
+
* The inner promise is handed back: dropping it let shutdown resolve
|
|
152
|
+
* before any line of a file target was flushed.
|
|
130
153
|
*/
|
|
131
|
-
close(): void {
|
|
132
|
-
|
|
133
|
-
inner.close?.();
|
|
154
|
+
close(): void | Promise<void> {
|
|
155
|
+
return this.#inner.close?.();
|
|
134
156
|
}
|
|
135
157
|
}
|
|
136
158
|
|
|
@@ -140,8 +162,9 @@ function atLevel(channel: LogChannel, level: string | undefined): LogChannel {
|
|
|
140
162
|
if (!isLogLevelWithSilent(level)) {
|
|
141
163
|
// A level nobody can act on is a config error, and the failure mode of
|
|
142
164
|
// ignoring it is the destination receiving everything.
|
|
143
|
-
throw new
|
|
144
|
-
|
|
165
|
+
throw new SpectrumError(
|
|
166
|
+
"E_SPECTRUM_UNKNOWN_LEVEL",
|
|
167
|
+
`Unknown transport target level "${level}". Use one of: ${Object.keys(LOG_LEVEL_ORDER).join(", ")}, silent.`,
|
|
145
168
|
);
|
|
146
169
|
}
|
|
147
170
|
const threshold = levelThreshold(level);
|
|
@@ -150,13 +173,33 @@ function atLevel(channel: LogChannel, level: string | undefined): LogChannel {
|
|
|
150
173
|
return new LeveledChannel(channel, threshold);
|
|
151
174
|
}
|
|
152
175
|
|
|
176
|
+
/**
|
|
177
|
+
* JSON to a file descriptor, every level to that one descriptor, as pino's
|
|
178
|
+
* file target writes it. Splitting by level sent a `destination: 1` app's
|
|
179
|
+
* errors to stderr, where a collector reading stdout never saw them, and
|
|
180
|
+
* ignored any other descriptor. No destination means 1, as upstream.
|
|
181
|
+
*/
|
|
182
|
+
function descriptorChannel(destination: unknown): LogChannel {
|
|
183
|
+
if (destination === undefined || destination === 1) {
|
|
184
|
+
return new ConsoleChannel("json", { stream: "stdout" });
|
|
185
|
+
}
|
|
186
|
+
if (destination === 2)
|
|
187
|
+
return new ConsoleChannel("json", { stream: "stderr" });
|
|
188
|
+
if (typeof destination === "number")
|
|
189
|
+
return new FileChannel({ fd: destination });
|
|
190
|
+
throw new SpectrumError(
|
|
191
|
+
"E_SPECTRUM_INVALID_FILE_OPTIONS",
|
|
192
|
+
`pino/file destination must be a path or a file descriptor, got ${typeof destination}`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
153
196
|
/**
|
|
154
197
|
* Turn transport targets into the channels spectrum actually writes through.
|
|
155
198
|
*
|
|
156
199
|
* `pino-pretty` is the human-readable console; `pino/file` writes JSON — to a
|
|
157
|
-
* file when `destination` is a path, and to
|
|
158
|
-
*
|
|
159
|
-
*
|
|
200
|
+
* file when `destination` is a path, and to that descriptor when it is one:
|
|
201
|
+
* `destination: 1` is stdout, which a containerised app ships to its log
|
|
202
|
+
* collector.
|
|
160
203
|
*
|
|
161
204
|
* A target with no level of its own inherits `inheritedLevel`, the level of the
|
|
162
205
|
* logger it belongs to — upstream's `defineConfig` fills the same gap, by
|
|
@@ -167,34 +210,142 @@ export function channelsFromTargets(
|
|
|
167
210
|
list: readonly TransportTargetOptions[],
|
|
168
211
|
inheritedLevel?: LogLevelWithSilent | string,
|
|
169
212
|
): LogChannel[] {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
)
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
213
|
+
return list.map((entry) =>
|
|
214
|
+
atLevel(channelForTarget(entry), entry.level ?? inheritedLevel),
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The channel a target describes.
|
|
220
|
+
*
|
|
221
|
+
* Any other target name used to fall through to JSON on stdout, so a config
|
|
222
|
+
* shipping logs to Loki or a socket booted fine and nothing reached the sink.
|
|
223
|
+
* Upstream fails when it cannot load a target; so does this.
|
|
224
|
+
*/
|
|
225
|
+
function channelForTarget(entry: TransportTargetOptions): LogChannel {
|
|
226
|
+
const { target } = entry;
|
|
227
|
+
const options = entry.options ?? {};
|
|
228
|
+
if (typeof target !== "string") return target;
|
|
229
|
+
if (target === "pino-pretty") return prettyChannel(options.destination);
|
|
230
|
+
if (target === "pino/file") {
|
|
231
|
+
const destination = options.destination;
|
|
232
|
+
if (typeof destination !== "string") return descriptorChannel(destination);
|
|
233
|
+
return new FileChannel({
|
|
234
|
+
path: destination,
|
|
235
|
+
append: optionalBoolean(options, "append"),
|
|
236
|
+
maxSizeBytes: optionalNumber(options, "maxSizeBytes"),
|
|
237
|
+
maxFiles: optionalNumber(options, "maxFiles"),
|
|
238
|
+
maxBufferBytes: optionalNumber(options, "maxBufferBytes"),
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
throw new SpectrumError(
|
|
242
|
+
"E_SPECTRUM_UNSUPPORTED_TARGET",
|
|
243
|
+
`Transport target "${target}" is not supported: spectrum builds "pino-pretty" and "pino/file". Pass a LogChannel as the target to write anywhere else.`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function prettyChannel(destination: unknown): LogChannel {
|
|
248
|
+
if (destination === undefined) return new ConsoleChannel("pretty");
|
|
249
|
+
if (destination === 1)
|
|
250
|
+
return new ConsoleChannel("pretty", { stream: "stdout" });
|
|
251
|
+
if (destination === 2)
|
|
252
|
+
return new ConsoleChannel("pretty", { stream: "stderr" });
|
|
253
|
+
throw new SpectrumError(
|
|
254
|
+
"E_SPECTRUM_UNSUPPORTED_TARGET",
|
|
255
|
+
`pino-pretty destination ${JSON.stringify(destination)} is not supported: use 1 or 2, or a pino/file target for a file.`,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** A number option, or undefined when absent; any other type is a config error. */
|
|
260
|
+
function optionalNumber(
|
|
261
|
+
options: Record<string, unknown>,
|
|
262
|
+
key: string,
|
|
263
|
+
): number | undefined {
|
|
264
|
+
const value = options[key];
|
|
265
|
+
if (value === undefined || typeof value === "number") return value;
|
|
266
|
+
throw invalidOption(key, "number", value);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** A boolean option, or undefined when absent; any other type is a config error. */
|
|
270
|
+
function optionalBoolean(
|
|
271
|
+
options: Record<string, unknown>,
|
|
272
|
+
key: string,
|
|
273
|
+
): boolean | undefined {
|
|
274
|
+
const value = options[key];
|
|
275
|
+
if (value === undefined || typeof value === "boolean") return value;
|
|
276
|
+
throw invalidOption(key, "boolean", value);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function invalidOption(
|
|
280
|
+
key: string,
|
|
281
|
+
type: string,
|
|
282
|
+
value: unknown,
|
|
283
|
+
): SpectrumError {
|
|
284
|
+
return new SpectrumError(
|
|
285
|
+
"E_SPECTRUM_INVALID_FILE_OPTIONS",
|
|
286
|
+
`pino/file option ${key} must be a ${type}, got ${typeof value}`,
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** JSON lines to anything with a `write(line)` method. */
|
|
291
|
+
class WritableChannel implements LogChannel {
|
|
292
|
+
readonly name = "destination";
|
|
293
|
+
readonly #target: LineWritable;
|
|
294
|
+
|
|
295
|
+
constructor(target: LineWritable) {
|
|
296
|
+
this.#target = target;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
write(entry: LogEntry): void {
|
|
300
|
+
this.#target.write(`${jsonLine(entry)}\n`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function isLineWritable(value: unknown): value is LineWritable {
|
|
305
|
+
return (
|
|
306
|
+
typeof value === "object" &&
|
|
307
|
+
value !== null &&
|
|
308
|
+
"write" in value &&
|
|
309
|
+
typeof value.write === "function"
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The channel a logger's `destination` option names. */
|
|
314
|
+
export function destinationChannel(destination: unknown): LogChannel {
|
|
315
|
+
if (typeof destination === "string")
|
|
316
|
+
return new FileChannel({ path: destination });
|
|
317
|
+
if (typeof destination === "number") return descriptorChannel(destination);
|
|
318
|
+
if (isLineWritable(destination)) return new WritableChannel(destination);
|
|
319
|
+
throw new SpectrumError(
|
|
320
|
+
"E_SPECTRUM_UNSUPPORTED_TARGET",
|
|
321
|
+
"destination must be a path, a file descriptor or an object with a write(line) method",
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* The channels a config's `destination` or `transport` describe, or
|
|
327
|
+
* `undefined` when it declares neither. `destination` wins over `transport`,
|
|
328
|
+
* as upstream; a transport is either a `targets` list or one
|
|
329
|
+
* `{ target, options }`.
|
|
330
|
+
*/
|
|
331
|
+
export function channelsFromConfig(
|
|
332
|
+
config: Pick<LogConfig, "destination" | "transport">,
|
|
333
|
+
level: LogLevelWithSilent | string | undefined,
|
|
334
|
+
): LogChannel[] | undefined {
|
|
335
|
+
if (config.destination !== undefined) {
|
|
336
|
+
return [destinationChannel(config.destination)];
|
|
337
|
+
}
|
|
338
|
+
const transport = config.transport;
|
|
339
|
+
if (transport === undefined) return undefined;
|
|
340
|
+
if ("target" in transport) return channelsFromTargets([transport], level);
|
|
341
|
+
if (Reflect.get(transport, "pipeline") !== undefined) {
|
|
342
|
+
throw new SpectrumError(
|
|
343
|
+
"E_SPECTRUM_UNSUPPORTED_TARGET",
|
|
344
|
+
"transport.pipeline is not supported: declare targets, or pass channels",
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
if (transport.targets === undefined || transport.targets.length === 0) {
|
|
348
|
+
return undefined;
|
|
198
349
|
}
|
|
199
|
-
return
|
|
350
|
+
return channelsFromTargets(transport.targets, level);
|
|
200
351
|
}
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { LogChannel, LogEntry, LogLevel } from "../types.js";
|
|
12
|
-
import { logEntryExtras } from "../types.js";
|
|
12
|
+
import { LOG_LEVEL_ORDER, logEntryExtras } from "../types.js";
|
|
13
13
|
|
|
14
14
|
export interface FakeLoggerPredicate {
|
|
15
15
|
/** Substring match against `entry.message`. */
|
|
@@ -133,9 +133,9 @@ function safeStringify(value: unknown): string {
|
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
-
function deepClone
|
|
136
|
+
function deepClone(entry: LogEntry): LogEntry {
|
|
137
137
|
try {
|
|
138
|
-
return structuredClone(
|
|
138
|
+
return structuredClone(entry);
|
|
139
139
|
} catch {
|
|
140
140
|
// `data` can carry functions / class instances that structuredClone
|
|
141
141
|
// rejects (DataCloneError). For a test capture a perfect clone isn't
|
|
@@ -144,9 +144,27 @@ function deepClone<T>(value: T): T {
|
|
|
144
144
|
// instead of thrown away (the throw propagated into Logger.log's swallow,
|
|
145
145
|
// dropping the entry and making assertLogged fail with "no entry").
|
|
146
146
|
try {
|
|
147
|
-
|
|
147
|
+
const parsed: unknown = JSON.parse(safeStringify(entry));
|
|
148
|
+
return isLogEntry(parsed) ? parsed : entry;
|
|
148
149
|
} catch {
|
|
149
|
-
return
|
|
150
|
+
return entry;
|
|
150
151
|
}
|
|
151
152
|
}
|
|
152
153
|
}
|
|
154
|
+
|
|
155
|
+
/** What came back from the JSON round-trip still has the shape of an entry. */
|
|
156
|
+
function isLogEntry(value: unknown): value is LogEntry {
|
|
157
|
+
return (
|
|
158
|
+
typeof value === "object" &&
|
|
159
|
+
value !== null &&
|
|
160
|
+
"level" in value &&
|
|
161
|
+
typeof value.level === "string" &&
|
|
162
|
+
value.level in LOG_LEVEL_ORDER &&
|
|
163
|
+
"message" in value &&
|
|
164
|
+
typeof value.message === "string" &&
|
|
165
|
+
"module" in value &&
|
|
166
|
+
typeof value.module === "string" &&
|
|
167
|
+
"timestamp" in value &&
|
|
168
|
+
typeof value.timestamp === "string"
|
|
169
|
+
);
|
|
170
|
+
}
|