-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlogger.ts
More file actions
86 lines (76 loc) · 3.02 KB
/
logger.ts
File metadata and controls
86 lines (76 loc) · 3.02 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
import { createLogger, format, transports, Logger as WinstonLogger } from "winston";
import { stringify } from "../internal.js";
import { ILogger } from "./logger.interface.js";
type LogLevel = "error" | "warn" | "info" | "debug" | "verbose";
const validLogLevels: LogLevel[] = ["error", "warn", "info", "debug", "verbose"];
export class Logger implements ILogger {
private logger: WinstonLogger;
private static instance: Logger | null;
private level: LogLevel;
private constructor() {
this.level = this.isValidLogLevel(process.env.LOG_LEVEL) ? process.env.LOG_LEVEL : "info";
this.logger = createLogger({
level: this.level,
format: format.combine(
format.colorize(),
format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
format.errors({ stack: true }),
format.printf(
({ level, message, timestamp, stack, className, chainId, ...rest }) => {
const parts = [
timestamp,
chainId ? `[Chain:${chainId}]` : "",
level,
className ? `[${className}]` : "",
":",
stack ?? message ?? "",
];
const contextInfo =
Object.keys(rest).length > 0 ? `| context: ${stringify(rest)}` : "";
return (
parts.filter(Boolean).join(" ") + (contextInfo ? ` ${contextInfo}` : "")
);
},
),
),
transports: [new transports.Console()],
});
}
/**
* Returns the instance of the Logger class.
* @param level The log level to be used by the logger.
* @returns The instance of the Logger class.
*/
public static getInstance(): ILogger {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}
isValidLogLevel(level?: string): level is LogLevel {
return validLogLevels.includes(level as LogLevel);
}
info(message: string, context?: Record<string, unknown>): void {
this.logger.info(message, context);
}
error(error: Error | string, context?: Record<string, unknown>): void {
if (error instanceof Error) {
this.logger.log("error", error.message, {
...context,
stack: error.stack,
cause: error.cause,
});
} else {
this.logger.log("error", error, context);
}
}
warn(message: string, context?: Record<string, unknown>): void {
this.logger.warn(message, context);
}
debug(message: string, context?: Record<string, unknown>): void {
this.logger.debug(message, context);
}
verbose(message: string, context?: Record<string, unknown>): void {
this.logger.verbose(message, context);
}
}