-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.js
78 lines (65 loc) · 2.08 KB
/
logging.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
const winston = require('winston');
const fs = require('fs');
const loggers = {};
function getCachedLogger(name, factory) {
if (!(name in loggers)) {
loggers[name] = factory();
}
return loggers[name];
}
function getFormat(name, colorized) {
const format = winston.format.combine(
winston.format.timestamp({ format: () => new Date().toLocaleString() }),
winston.format.align(),
winston.format.printf((info) => {
return `[${info.timestamp}] ${name} - ${info.level}: ${info.message}`
})
);
return colorized
? winston.format.combine(
winston.format.colorize(),
format
)
: format;
}
/**
* The default logger logs everything on the console.
*/
const defaultLoggerName = 'main';
function createDefaultLogger() {
return winston.createLogger({
level: 'info',
format: getFormat(defaultLoggerName),
transports: [new winston.transports.Console()]
});
}
const defaultLogger = getCachedLogger(defaultLoggerName, createDefaultLogger);
/**
* Creates a logger that will log messages in a specific files.
* Warnings and above are also displayed on console.
*
* @param {string} name The logger name
*/
function loggerFactory(name) {
function createLogger() {
if (!fs.existsSync('tmp')) { fs.mkdirSync('tmp'); }
const logPath = `./tmp/${name}.log`;
defaultLogger.info(`logging ${name} to ${logPath}`)
return winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console({
level: 'warn',
format: getFormat(name, true)
}),
new winston.transports.File({
level: 'info',
filename: logPath,
format: getFormat(name)
}),
]
})
}
return getCachedLogger(name, createLogger);
}
module.exports = { defaultLogger, loggerFactory };