-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger.ts
46 lines (42 loc) · 1.45 KB
/
logger.ts
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
export interface Logger {
debug: (message: string, metadata?: unknown) => void;
info: (message: string, metadata?: unknown) => void;
warn: (message: string, metadata?: unknown) => void;
error: (message: string, metadata?: unknown) => void;
}
export const jsonSerializer = (_: unknown, v: unknown) => {
if (v instanceof Error) {
return Object.getOwnPropertyNames(v).reduce(
(acc, key) => {
acc[key] = v[key as keyof Error];
return acc;
},
{} as Record<string, unknown>,
);
}
if (Buffer.isBuffer(v)) {
return v.toString();
}
if (typeof v === 'bigint') {
return v.toString();
}
return v;
};
class JsonLogger implements Logger {
debug(message: string, metadata?: unknown) {
console.debug(JSON.stringify({ message, metadata, level: 'debug' }, jsonSerializer));
}
info(message: string, metadata?: unknown) {
console.info(JSON.stringify({ message, metadata, level: 'info' }, jsonSerializer));
}
warn(message: string, metadata?: unknown) {
console.warn(JSON.stringify({ message, metadata, level: 'warning' }, jsonSerializer));
}
error(message: string, metadata?: unknown) {
console.error(JSON.stringify({ message, metadata, level: 'error' }, jsonSerializer));
}
}
export let log: Logger = new JsonLogger();
export const setLogger = (newLogger: Logger) => {
log = newLogger;
};