-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.js
112 lines (102 loc) · 2.15 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const color = require('ansi-colors');
let logLevel = 1;
let isEnabled = true;
/**
* Get the currently set log level.
*
* @return {number}
*/
module.exports.getLogLevel = () => {
return logLevel;
};
/**
* Set the log level.
*
* @param {number} level
*/
module.exports.setLogLevel = (level) => {
logLevel = level;
};
/**
* Log an expression to console at a specific level.
*
* @param {*} msg
* @param {number} [level]
* @param {string|undefined} prefix
*/
module.exports.logExpression = (msg, level, prefix) => {
if ((level !== undefined && level > logLevel) || !isEnabled) {
return;
}
const now = new Date();
const date = [
now.getFullYear(),
now.getMonth() + 1,
now.getDate()
].map((val) => val.toString().padStart(2, '0')).join('-');
const time = [
now.getHours(),
now.getMinutes(),
now.getSeconds()
].map((val) => val.toString().padStart(2, '0')).join(':');
const datetime = `[${date} ${time}.${now.getMilliseconds().toString().padStart(3, '0').substr(0, 2)}]`;
const start = `${prefix ? prefix + ' ' : ''}${datetime}`;
if (typeof msg === 'object') {
console.log(start);
console.log(JSON.stringify(msg, null, 2));
}
else {
console.log(`${start} ${msg}`);
}
};
/**
* Enable or disable logExpression globally.
*
* @param {bool} enabled
*/
module.exports.setLoggerEnabled = (enabled) => {
if (typeof enabled === 'string') {
enabled = enabled.toLowerCase() === 'true';
}
isEnabled = !!enabled;
};
/**
* Log debug message
*
* @param {*} msg
*/
module.exports.debug = (msg) => {
this.logExpression(msg, 2, color.blue('[debug]'));
};
/**
* Log info message
*
* @param {*} msg
*/
module.exports.info = (msg) => {
this.logExpression(msg, 1, color.green('[info ]'));
};
/**
* Log warn message
*
* @param {*} msg
*/
module.exports.warn = (msg) => {
this.logExpression(msg, 0, color.yellow('[warn ]'));
};
/**
* Log error message
*
* @param {*} msg
*/
module.exports.error = (msg) => {
this.logExpression(msg, -1, color.red('[error]'));
};
/**
* Log fatal message
*
* @param {*} msg
*/
module.exports.fatal = (msg) => {
this.logExpression(msg, -2, color.bold.red('[FATAL]'))
}