forked from Superalgos/Superalgos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loggerFactory.js
90 lines (85 loc) · 2.6 KB
/
loggerFactory.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
const { createLogger, format, transports, addColors } = require('winston');
const { combine, splat, timestamp, printf } = format;
require('winston-daily-rotate-file');
const customLevels = {
levels: {
error: 0,
warn: 1,
info: 2,
debug: 3
},
colors: {
error: 'red',
warn: 'yellow',
info: 'white',
debug: 'green',
}
};
const consoleFormat = (type) => printf(({ level, message, timestamp, ...metadata }) => {
let msg = `${timestamp} | ${type} | ${level} | ${message} `
if (Object.keys(metadata).length > 0) {
msg += JSON.stringify(metadata)
}
return msg
});
const fileFormat = printf(({ level, message, timestamp, ...metadata }) => {
let msg = `${timestamp} | ${level} | ${message} `
if (Object.keys(metadata).length > 0) {
msg += JSON.stringify(metadata)
}
return msg
});
const getLogLevel = () => {
if (global.env.LOG_LEVEL !== undefined && customLevels.levels[global.env.LOG_LEVEL] !== undefined) {
return global.env.LOG_LEVEL
}
return 'info'
}
/**
*
* @param {string} logFileDirectory
* @param {string} type
* @returns {{
* info: (message: string) => void,
* debug: (message: string) => void,
* warn: (message: string) => void
* error: (message: string, stack: any) => void
* }}
*/
exports.loggerFactory = function loggerFactory(logFileDirectory, type) {
const consoleLogLevel = getLogLevel()
const filePathParts = logFileDirectory.split('/')
addColors(customLevels.colors)
return createLogger({
levels: customLevels.levels,
format: combine(
splat(),
timestamp(),
consoleFormat(type)
),
transports: [
new transports.DailyRotateFile({
filename: filePathParts.concat(['error', '%DATE%.log']).join('/'),
format: fileFormat,
level: 'error',
datePattern: 'YYYY-MM-DD',
maxFiles: '14d',
zippedArchive: true,
handleExceptions: true
}),
new transports.DailyRotateFile({
filename: filePathParts.concat(['combined', '%DATE%.log']).join('/'),
format: fileFormat,
datePattern: 'YYYY-MM-DD',
maxFiles: '14d',
zippedArchive: true,
level: consoleLogLevel == 'debug' ? 'debug' : 'info'
}),
new transports.Console({
level: consoleLogLevel,
handleExceptions: true
})
],
exitOnError: false
})
}