-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathlogger.ts
More file actions
279 lines (220 loc) · 7.92 KB
/
logger.ts
File metadata and controls
279 lines (220 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// Create a logger class that uses the debug package internally
/**
* Represents different log levels.
* - `"log"`: Only essential messages.
* - `"error"`: Errors and essential messages.
* - `"warn"`: Warnings, Errors and essential messages.
* - `"info"`: Info, Warnings, Errors and essential messages.
* - `"debug"`: Everything.
*/
import { env } from "node:process";
import { Buffer } from "node:buffer";
import { trace, context } from "@opentelemetry/api";
export type LogLevel = "log" | "error" | "warn" | "info" | "debug" | "verbose";
const logLevels: Array<LogLevel> = ["log", "error", "warn", "info", "debug", "verbose"];
export class Logger {
#name: string;
readonly #level: number;
#filteredKeys: string[] = [];
#jsonReplacer?: (key: string, value: unknown) => unknown;
#additionalFields: () => Record<string, unknown>;
// Add a static "onError" method that will be called when an error is logged
static onError: (message: string, ...args: Array<Record<string, unknown> | undefined>) => void;
constructor(
name: string,
level: LogLevel = "info",
filteredKeys: string[] = [],
jsonReplacer?: (key: string, value: unknown) => unknown,
additionalFields?: () => Record<string, unknown>
) {
this.#name = name;
this.#level = logLevels.indexOf((env.TRIGGER_LOG_LEVEL ?? level) as LogLevel);
this.#filteredKeys = filteredKeys;
this.#jsonReplacer = createReplacer(jsonReplacer);
this.#additionalFields = additionalFields ?? (() => ({}));
}
child(fields: Record<string, unknown>) {
return new Logger(
this.#name,
logLevels[this.#level],
this.#filteredKeys,
this.#jsonReplacer,
() => ({ ...this.#additionalFields(), ...fields })
);
}
// Return a new Logger instance with the same name and a new log level
// but filter out the keys from the log messages (at any level)
filter(...keys: string[]) {
return new Logger(this.#name, logLevels[this.#level], keys, this.#jsonReplacer);
}
static satisfiesLogLevel(logLevel: LogLevel, setLevel: LogLevel) {
return logLevels.indexOf(logLevel) <= logLevels.indexOf(setLevel);
}
log(message: string, ...args: Array<Record<string, unknown> | undefined>) {
if (this.#level < 0) return;
this.#structuredLog(console.log, message, "log", ...args);
}
error(message: string, ...args: Array<Record<string, unknown> | undefined>) {
if (this.#level < 1) return;
this.#structuredLog(console.error, message, "error", ...args);
if (Logger.onError) {
Logger.onError(message, ...args);
}
}
warn(message: string, ...args: Array<Record<string, unknown> | undefined>) {
if (this.#level < 2) return;
this.#structuredLog(console.warn, message, "warn", ...args);
}
info(message: string, ...args: Array<Record<string, unknown> | undefined>) {
if (this.#level < 3) return;
this.#structuredLog(console.info, message, "info", ...args);
}
debug(message: string, ...args: Array<Record<string, unknown> | undefined>) {
if (this.#level < 4) return;
this.#structuredLog(console.debug, message, "debug", ...args);
}
verbose(message: string, ...args: Array<Record<string, unknown> | undefined>) {
if (this.#level < 5) return;
this.#structuredLog(console.log, message, "verbose", ...args);
}
#structuredLog(
loggerFunction: (message: string, ...args: any[]) => void,
message: string,
level: string,
...args: Array<Record<string, unknown> | undefined>
) {
// Get the current context from trace if it exists
const currentSpan = trace.getSpan(context.active());
const structuredError = extractStructuredErrorFromArgs(...args);
const structuredMessage = extractStructuredMessageFromArgs(...args);
const structuredLog = {
...structureArgs(safeJsonClone(args) as Record<string, unknown>[], this.#filteredKeys),
...this.#additionalFields(),
...(structuredError ? { error: structuredError } : {}),
timestamp: new Date(),
name: this.#name,
message,
...(structuredMessage ? { $message: structuredMessage } : {}),
level,
traceId:
currentSpan && currentSpan.isRecording() ? currentSpan?.spanContext().traceId : undefined,
parentSpanId:
currentSpan && currentSpan.isRecording() ? currentSpan?.spanContext().spanId : undefined,
};
// If the span is not recording, and it's a debug log, mark it so we can filter it out when we forward it
if (currentSpan && !currentSpan.isRecording() && level === "debug") {
structuredLog.skipForwarding = true;
}
loggerFunction(JSON.stringify(structuredLog, this.#jsonReplacer));
}
}
// Detect if args is an error object
// Or if args contains an error object at the "error" key
// In both cases, return the error object as a structured error
function extractStructuredErrorFromArgs(...args: Array<Record<string, unknown> | undefined>) {
const error = args.find((arg) => arg instanceof Error) as Error | undefined;
if (error) {
return {
message: error.message,
stack: error.stack,
name: error.name,
};
}
const structuredError = args.find((arg) => arg?.error);
if (structuredError && structuredError.error instanceof Error) {
return {
message: structuredError.error.message,
stack: structuredError.error.stack,
name: structuredError.error.name,
};
}
return;
}
function extractStructuredMessageFromArgs(...args: Array<Record<string, unknown> | undefined>) {
// Check to see if there is a `message` key in the args, and if so, return it
const structuredMessage = args.find((arg) => arg?.message);
if (structuredMessage) {
return structuredMessage.message;
}
return;
}
function createReplacer(replacer?: (key: string, value: unknown) => unknown) {
return (key: string, value: unknown) => {
if (typeof value === "bigint") {
return value.toString();
}
if (replacer) {
return replacer(key, value);
}
return value;
};
}
// Replacer function for JSON.stringify that converts BigInts to strings
function bigIntReplacer(_key: string, value: unknown) {
if (typeof value === "bigint") {
return value.toString();
}
return value;
}
function safeJsonClone(obj: unknown) {
try {
return JSON.parse(JSON.stringify(obj, bigIntReplacer));
} catch (e) {
return;
}
}
// If args is has a single item that is an object, return that object
function structureArgs(args: Array<Record<string, unknown>>, filteredKeys: string[] = []) {
if (!args) {
return;
}
if (args.length === 0) {
return;
}
if (args.length === 1 && typeof args[0] === "object") {
return filterKeys(JSON.parse(JSON.stringify(args[0], bigIntReplacer)), filteredKeys);
}
return args;
}
// Recursively filter out keys from an object, including nested objects, and arrays
function filterKeys(obj: unknown, keys: string[]): any {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((item) => filterKeys(item, keys));
}
const filteredObj: any = {};
for (const [key, value] of Object.entries(obj)) {
if (keys.includes(key)) {
if (value) {
filteredObj[key] = `[filtered ${prettyPrintBytes(value)}]`;
} else {
filteredObj[key] = value;
}
continue;
}
filteredObj[key] = filterKeys(value, keys);
}
return filteredObj;
}
function prettyPrintBytes(value: unknown): string {
if (env.NODE_ENV === "production") {
return "skipped size";
}
const sizeInBytes = getSizeInBytes(value);
if (sizeInBytes < 1024) {
return `${sizeInBytes} bytes`;
}
if (sizeInBytes < 1024 * 1024) {
return `${(sizeInBytes / 1024).toFixed(2)} KB`;
}
if (sizeInBytes < 1024 * 1024 * 1024) {
return `${(sizeInBytes / (1024 * 1024)).toFixed(2)} MB`;
}
return `${(sizeInBytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
function getSizeInBytes(value: unknown) {
const jsonString = JSON.stringify(value);
return Buffer.byteLength(jsonString, "utf8");
}