forked from graphile/worker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.ts
92 lines (80 loc) · 2.2 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
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
export interface LogScope {
label?: string;
workerId?: string;
taskIdentifier?: string;
jobId?: string;
}
export interface LogMeta {
[key: string]: unknown;
}
// Inspired by the 'winston' levels: https://github.com/winstonjs/winston#logging-levels
export enum LogLevel {
ERROR = "error",
WARNING = "warning",
INFO = "info",
DEBUG = "debug",
}
export interface LogFunction {
(level: LogLevel, message: string, meta?: LogMeta): void;
}
export interface LogFunctionFactory {
(scope: LogScope): LogFunction;
}
export class Logger {
private _scope: LogScope;
private _logFactory: LogFunctionFactory;
private log: LogFunction;
constructor(logFactory: LogFunctionFactory, scope: LogScope = {}) {
this._scope = scope;
this._logFactory = logFactory;
this.log = logFactory(scope);
}
scope(additionalScope: LogScope) {
return new Logger(this._logFactory, { ...this._scope, ...additionalScope });
}
error(message: string, meta?: LogMeta): void {
return this.log(LogLevel.ERROR, message, meta);
}
warn(message: string, meta?: LogMeta): void {
return this.log(LogLevel.WARNING, message, meta);
}
info(message: string, meta?: LogMeta): void {
return this.log(LogLevel.INFO, message, meta);
}
debug(message: string, meta?: LogMeta): void {
return this.log(LogLevel.DEBUG, message, meta);
}
}
// The default console logger does not output metadata
export const consoleLogFactory = (scope: LogScope) => (
level: LogLevel,
message: string,
) => {
if (level === LogLevel.DEBUG && !process.env.GRAPHILE_WORKER_DEBUG) {
return;
}
let method: "error" | "warn" | "info" | "log" = (() => {
switch (level) {
case LogLevel.ERROR:
return "error";
case LogLevel.WARNING:
return "warn";
case LogLevel.INFO:
return "info";
default:
return "log";
}
})();
console[method](
`[%s%s] %s: %s`,
scope.label || "core",
scope.workerId
? `(${scope.workerId}${
scope.taskIdentifier ? `: ${scope.taskIdentifier}` : ""
}${scope.jobId ? `{${scope.jobId}}` : ""})`
: "",
level.toUpperCase(),
message,
);
};
export const defaultLogger = new Logger(consoleLogFactory);