-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
128 lines (102 loc) · 2.66 KB
/
index.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
var
FS = require('fs'),
_ = require('lodash'),
MOMENT = require('moment'),
DEBUG = 0,
VERBOSE = 1,
INFO = 2,
ERROR = 3,
CRITICAL = 4,
WRITE_FLAGS = { 'encoding': 'utf8', 'flags': 'a' },
LEVEL_MAP = [
'debug',
'verbose',
'info',
'error',
'critical'
];
function LGR() {
this.count = 0;
this.setLogFormat('<%= ts %> [<%= uptime %>] [<%= count %>] ');
this.level = INFO;
this.outStream = process.stdout;
this.errStream = process.stderr;
}
LGR.prototype.toStr = function(args) {
var objects = _.values(args);
objects.forEach(function(obj, index){
if(typeof obj == 'object') objects[index] = JSON.stringify(obj);
});
return objects;
};
LGR.prototype.setOut = function(fileName) {
if(typeof fileName == 'string') {
try{
this.outStream = FS.createWriteStream(fileName, WRITE_FLAGS);
}
catch(err){
this.outStream = process.stdout;
}
}
};
LGR.prototype.setErr = function(fileName) {
if(typeof fileName == 'string') {
try{
this.errStream = FS.createWriteStream(fileName, WRITE_FLAGS);
}
catch(err){
this.errStream = process.stderr;
}
}
};
LGR.prototype.critical = function() {
if(this.level <= CRITICAL){
this.count++;
this.errStream.write('CRITICAL! ' + this._p() + this.toStr(arguments).join(" ") + "\n");
}
};
LGR.prototype.error = function() {
if(this.level <= ERROR){
this.count++;
this.errStream.write('ERR! ' + this._p() + this.toStr(arguments).join(" ") + "\n");
}
};
LGR.prototype.log = function() {
this.count++;
this.outStream.write('info ' + this._p() + this.toStr(arguments).join(" ") + "\n");
};
LGR.prototype.info = function() {
if(this.level <= INFO){
this.count++;
this.outStream.write('log ' + this._p() + this.toStr(arguments).join(" ") + "\n");
}
};
LGR.prototype.verbose = function() {
if(this.level <= VERBOSE){
this.count++;
this.outStream.write('verb ' + this._p() + this.toStr(arguments).join(" ") + "\n");
}
};
LGR.prototype.debug = function() {
if(this.level <= DEBUG){
this.count++;
this.outStream.write('debug ' + this._p() + this.toStr(arguments).join(" ") + "\n");
}
};
LGR.prototype.setLogFormat = function(format) {
this.format = _.template(format);
};
LGR.prototype.setLevel = function(level) {
this.level = _.indexOf(LEVEL_MAP, level);
if(this.level === -1) this.level = INFO;
};
LGR.prototype._p = function(){
return this.format({
"ram" : JSON.stringify(process.memoryUsage()),
"ts" : MOMENT().format("YYYY-MM-DD HH:mm:ss"),
"uptime" : process.uptime(),
"pid" : process.pid,
"count" : this.count,
});
};
module.exports = new LGR();