forked from hobbyquaker/ccu.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
95 lines (83 loc) · 2.4 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
var scheduler = require('node-schedule'),
fs = require("fs");
var logger = {
logfile: __dirname + "/log/ccu.io.log",
level: 3,
timestamp: true,
colors: {
"5": '\u001b[31m',
"4": '\u001b[33m',
"3": '\u001b[32m',
"2": '\u001b[34m',
reset: '\u001b[0m'
},
text: {
"0": "silly ",
"1": "debug ",
"2": "verbose",
"3": "info ",
"4": "warn ",
"5": "error "
},
maxLength: 200,
silly: function(obj) {
logger.log(0, obj);
},
debug: function(obj) {
logger.log(1, obj);
},
verbose: function(obj) {
logger.log(2, obj);
},
info: function(obj) {
logger.log(3, obj);
},
warn: function(obj) {
logger.log(4, obj);
},
error: function(obj) {
logger.log(5, obj);
},
log: function(level, obj) {
if (level >= this.level) {
var str;
if (typeof obj !== "string") {
str = JSON.stringify(obj);
} else {
str = obj.replace(/(\r\n|\n|\r)/gm,"");
}
if (this.colors[level]) {
str = this.colors[level] + this.text[level] + this.colors["reset"] + ": " + str;
} else {
str = this.text[level] + ": " + str;
}
if (this.timestamp) {
var ts = new Date();
str = ts.getFullYear() + '-' +
("0" + (ts.getMonth() + 1).toString(10)).slice(-2) + '-' +
("0" + (ts.getDate()).toString(10)).slice(-2) + ' ' +
("0" + (ts.getHours()).toString(10)).slice(-2) + ':' +
("0" + (ts.getMinutes()).toString(10)).slice(-2) + ':' +
("0" + (ts.getSeconds()).toString(10)).slice(-2) + "." +
("00" + (ts.getMilliseconds()).toString(10)).slice(-3) + " " +
str;
}
if (str.length > this.maxLength) {
str = str.slice(0, this.maxLength - 4) + " ...";
}
//console.log(str);
log.write(str+"\n");
}
}
}
var log = fs.createWriteStream(logger.logfile, {
flags: "a", encoding: "utf8", mode: 0644
});
process.on("uncaughtException", function(err) {
try {
log.write(err.stack);
} catch (e) {
// ...?
}
});
module.exports = logger;