/
logger.js
97 lines (83 loc) · 2.7 KB
/
logger.js
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
/* eslint-disable no-console */
import { format as utilFormat } from "node:util";
import winston from "winston";
import checkAndCopyConfig, { getSettings, CONF_DIR } from "utils/config/config";
let winstonLogger;
function init() {
checkAndCopyConfig("settings.yaml");
const settings = getSettings();
const logpath = settings.logpath || CONF_DIR;
function combineMessageAndSplat() {
return {
// eslint-disable-next-line no-unused-vars
transform: (info, opts) => {
// combine message and args if any
// eslint-disable-next-line no-param-reassign
info.message = utilFormat(info.message, ...(info[Symbol.for("splat")] || []));
return info;
},
};
}
function messageFormatter(logInfo) {
if (logInfo.label) {
if (logInfo.stack) {
return `[${logInfo.timestamp}] ${logInfo.level}: <${logInfo.label}> ${logInfo.stack}`;
}
return `[${logInfo.timestamp}] ${logInfo.level}: <${logInfo.label}> ${logInfo.message}`;
}
if (logInfo.stack) {
return `[${logInfo.timestamp}] ${logInfo.level}: ${logInfo.stack}`;
}
return `[${logInfo.timestamp}] ${logInfo.level}: ${logInfo.message}`;
}
winstonLogger = winston.createLogger({
level: process.env.LOG_LEVEL || "info",
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.errors({ stack: true }),
combineMessageAndSplat(),
winston.format.timestamp(),
winston.format.colorize(),
winston.format.printf(messageFormatter),
),
handleExceptions: true,
handleRejections: true,
}),
new winston.transports.File({
format: winston.format.combine(
winston.format.errors({ stack: true }),
combineMessageAndSplat(),
winston.format.timestamp(),
winston.format.printf(messageFormatter),
),
filename: `${logpath}/logs/homepage.log`,
handleExceptions: true,
handleRejections: true,
}),
],
});
// patch the console log mechanism to use our logger
const consoleMethods = ["log", "debug", "info", "warn", "error"];
consoleMethods.forEach((method) => {
// workaround for https://github.com/winstonjs/winston/issues/1591
switch (method) {
case "log":
console[method] = winstonLogger.info.bind(winstonLogger);
break;
default:
console[method] = winstonLogger[method].bind(winstonLogger);
break;
}
});
}
const loggers = {};
export default function createLogger(label) {
if (!winstonLogger) {
init();
}
if (!loggers[label]) {
loggers[label] = winstonLogger.child({ label });
}
return loggers[label];
}