-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathlogger.js
98 lines (87 loc) · 1.88 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
98
"use strict";
const fs = require('fs');
const winston = require('winston');
const loggerConfig = {
levels: {
data: 0,
debug: 1,
info: 2,
warn: 3,
error: 4
},
colors: {
data: 'grey',
debug: 'magenta',
info: 'green',
warn: 'yellow',
error: 'red'
}
};
let logger = null;
function init(logLevelConsole, logLevelFile) {
logLevelConsole = validateLogLevel(logLevelConsole, 'debug');
logLevelFile = validateLogLevel(logLevelFile, 'data');
const logDir = 'logs';
// sync is okay as this is on startup
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const unixTime = Math.floor((new Date()).getTime() / 1000);
const logPrefix = logDir + '/' + unixTime + '-';
logger = new winston.Logger({
transports: [
new winston.transports.Console({
colorize: true,
level: logLevelConsole
}),
new winston.transports.File({
filename: logPrefix + 'main.log',
level: logLevelFile,
json: false
})
],
levels: loggerConfig.levels,
colors: loggerConfig.colors
});
logger.debug('Logger initialized with logLevelConsole %s and logLevelFile %s', logLevelConsole, logLevelFile);
}
function validateLogLevel(logLevel, defaultLogLevel) {
if (typeof logLevel === 'string' && logLevel in loggerConfig.levels) {
// valid
return logLevel;
} else {
// invalid or not present
return defaultLogLevel;
}
}
function data() {
if (logger) {
logger.data.apply(this, arguments);
}
}
function debug() {
if (logger) {
logger.debug.apply(this, arguments);
}
}
function info() {
if (logger) {
logger.info.apply(this, arguments);
}
}
function warn() {
if (logger) {
logger.warn.apply(this, arguments);
}
}
function error() {
if (logger) {
logger.error.apply(this, arguments);
}
}
module.exports.init = init;
module.exports.data = data;
module.exports.debug = debug;
module.exports.info = info;
module.exports.warn = warn;
module.exports.error = error;