-
Notifications
You must be signed in to change notification settings - Fork 25
/
logger.ts
78 lines (71 loc) · 1.84 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
import winston from 'winston';
import RnR from 'runtime-node-refresh';
import httpContext from 'express-http-context';
import config from '@config/config';
const errorStackFormat = winston.format((info) => {
if (info instanceof Error) {
return {
...info,
stack: info.stack,
message: info.message,
};
}
return info;
});
const errorTemplate = ({ timestamp, level, message, stack }) => {
const reqId = httpContext.get('ReqId');
let tmpl = `${timestamp}`;
if (reqId) tmpl += ` ${reqId}`;
tmpl += ` ${level} ${message}`;
if (stack) tmpl += ` \n ${stack}`;
return tmpl;
};
const logger: winston.Logger = winston.createLogger({
level: config.env === 'development' ? 'debug' : 'info',
format: winston.format.combine(
errorStackFormat(),
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
config.env === 'development'
? winston.format.colorize()
: winston.format.uncolorize(),
winston.format.splat(),
winston.format.printf(errorTemplate),
),
transports: [
new winston.transports.Console({
stderrLevels: ['error'],
}),
],
});
const avbLogLevels = [
'error',
'warn',
'info',
'http',
'verbose',
'debug',
'silly',
];
let currentLogLevel: number = logger.levels[logger.level];
logger.info(`Logger level is set to ${logger.level}`);
// Refresh log level on runtime
RnR(() => {
if (currentLogLevel < avbLogLevels.length - 1) {
currentLogLevel += 1;
} else {
currentLogLevel = 0;
}
const found = Object.entries(logger.levels).find(
([, value]) => value === currentLogLevel,
);
if (found && found.length) {
// eslint-disable-next-line
console.log(
`${new Date().toISOString()} system: Switch logger level from ${
logger.level
} to ${found[0]}`,
);
logger.level = found[`${0}`];
}
});
export default logger;