forked from LiskArchive/lisk-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
93 lines (76 loc) · 2.04 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
'use strict';
var strftime = require('strftime').utc();
var fs = require('fs');
var util = require('util');
require('colors');
module.exports = function (config) {
config = config || {};
var exports = {};
config.levels = config.levels || {
trace: 0,
debug: 1,
log: 2,
info: 3,
warn: 4,
error: 5,
fatal: 6
};
config.level_abbr = config.level_abbr || {
trace: 'trc',
debug: 'dbg',
log: 'log',
info: 'inf',
warn: 'WRN',
error: 'ERR',
fatal: 'FTL'
};
config.filename = config.filename || __dirname + '/logs.log';
config.errorLevel = config.errorLevel || 'log';
var log_file = fs.createWriteStream(config.filename, {flags: 'a'});
exports.setLevel = function (errorLevel) {
config.errorLevel = errorLevel;
};
function snipsecret (data) {
for (var key in data) {
if (key.search(/secret/i) > -1) {
data[key] = 'XXXXXXXXXX';
}
}
return data;
}
Object.keys(config.levels).forEach(function (name) {
function log (message, data) {
var log = {
level: name,
timestamp: strftime('%F %T', new Date())
};
if (message instanceof Error) {
log.message = message.stack;
} else {
log.message = message;
}
if (data && util.isObject(data)) {
log.data = JSON.stringify(snipsecret(data));
} else {
log.data = data;
}
log.symbol = config.level_abbr[log.level] ? config.level_abbr[log.level] : '???';
if (config.levels[config.errorLevel] <= config.levels[log.level]) {
if (log.data) {
log_file.write(util.format('[%s] %s | %s - %s\n', log.symbol, log.timestamp, log.message, log.data));
} else {
log_file.write(util.format('[%s] %s | %s\n', log.symbol, log.timestamp, log.message));
}
}
if (config.echo && config.levels[config.echo] <= config.levels[log.level]) {
if (log.data) {
console.log('['+log.symbol.bgYellow.black+']', log.timestamp.grey, '|', log.message, '-', log.data);
} else {
console.log('['+log.symbol.bgYellow.black+']', log.timestamp.grey, '|', log.message);
}
}
}
exports[name] = log;
});
return exports;
};