forked from Countly/countly-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.js
More file actions
330 lines (308 loc) · 10.5 KB
/
Copy pathlog.js
File metadata and controls
330 lines (308 loc) · 10.5 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
'use strict';
/**
* Log provides a wrapper over debug or console functions with log level filtering, module filtering and ability to store log in database.
* Uses configuration require('../config.js').logging:
* {
* 'info': ['app', 'auth', 'static'], // log info and higher level for modules 'app*', 'auth*', 'static*'
* 'debug': ['api.users'], // log debug and higher (in fact everything) for modules 'api.users*'
* 'default': 'warn', // log warn and higher for all other modules
* }
* Note that log levels supported are ['debug', 'info', 'warn', 'error']
*
* Usage is quite simple:
* var log = require('common.js').log('module[:submodule[:subsubmodule]]');
* log.i('something happened: %s, %j', 'string', {obj: 'ect'});
* log.e('something really bad happened: %j', new Error('Oops'));
*
* Whenever DEBUG is in process.env, log outputs all filtered messages with debug module instead of console so you could have pretty colors in console.
* In other cases only log.d is logged using debug module.
*
* To control log level at runtime, call require('common.js').log.setLevel('events', 'debug'). From now on 'events' logger will log everything.
*
* There is also a handy method for generating standard node.js callbacks which log error. Only applicable if no actions in case of error needed:
* collection.find().toArray(log.callback(function(arg1, arg2){ // all good }));
* - if error didn't happen, function is called
* - if error happened, it will be logged, but function won't be called
* - if error happened, arg1 is a first argument AFTER error, it's not an error
* @module api/utils/log
*/
var prefs = require('../config.js', 'dont-enclose').logging || {};
prefs.default = prefs.default || "warn";
var colors = require('colors');
var deflt = (prefs && prefs.default) ? prefs.default : 'error';
for (var level in prefs) {
if (prefs[level].sort) { prefs[level].sort(); }
}
var styles = {
moduleColors: {
// 'push:*api': 0 // green
'[last]': -1
},
colors: ['green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'red'],
stylers: {
warn: function(args) {
for (var i = 0; i < args.length; i++) {
if (typeof args[i] === 'string') { args[i] = colors.bgYellow.black(args[i].black); }
}
},
error: function(args) {
for (var i = 0; i < args.length; i++) {
if (typeof args[i] === 'string') { args[i] = colors.bgRed.white(args[i].white); }
}
}
}
};
/**
* Returns logger function for given preferences
* @param {string} level - log level
* @param {string} prefix - add prefix to message
* @param {boolean} enabled - whether function should log anything
* @param {object} outer - this for @out
* @param {function} out - output function (console or debug)
* @param {function} styler - function to apply styles
* @returns {function} logger function
*/
var log = function(level, prefix, enabled, outer, out, styler) {
return function() {
// console.log(level, prefix, enabled(), arguments);
if (enabled()) {
var args = Array.prototype.slice.call(arguments, 0);
var color = styles.moduleColors[prefix];
if (color === undefined) {
color = (++styles.moduleColors['[last]']) % styles.colors.length;
styles.moduleColors[prefix] = color;
}
color = styles.colors[color];
if (styler) {
args[0] = new Date().toISOString() + ': ' + level + '\t' + '[' + (prefix || '') + ']\t' + args[0];
styler(args);
} else {
args[0] = (new Date().toISOString() + ': ' + level + '\t').gray + colors[color]('[' + (prefix || '') + ']\t') + args[0];
}
// args[0] = (new Date().toISOString() + ': ' + (prefix || '')).gray + args[0];
// console.log('Logging %j', args);
if (typeof out === 'function') { out.apply(outer, args); }
else {
for (var k in out) { out[k].apply(outer, args); }
}
}
};
};
/**
* Looks for logging level in config for a particular module
* @param {string} name - module name
*/
var logLevel = function(name) {
if (typeof prefs === 'undefined') { return 'error'; }
else if (typeof prefs === 'string') { return prefs; }
else {
for (var level in prefs) {
if (typeof prefs[level] === 'string' && name.indexOf(prefs[level]) === 0) { return level; }
if (typeof prefs[level] === 'object' && prefs[level].length ) {
for (var i = prefs[level].length - 1; i >= 0; i--) {
var opt = prefs[level][i];
if (opt === name || name.indexOf(opt) === 0) { return level; }
}
// for (var m in prefs[level]) {
// if (name.indexOf(prefs[level][m]) === 0) { return level; }
// }
}
}
return deflt;
}
};
/**
* Current levels for all modules
*/
var levels = {
// mongo: 'info'
};
/**
* Sets current logging level
* @static
* @param {string} module - name of the module for logging
* @param {string} level - level of logging, possible values are: debug, info, warn, error
**/
var setLevel = function(module, level) {
levels[module] = level;
};
/**
* Sets default logging level for all modules, that do not have specific level set
* @static
* @param {string} level - level of logging, possible values are: debug, info, warn, error
**/
var setDefault = function(level) {
deflt = level;
};
/**
* Get currently set logging level for module
* @static
* @returns {string} level of logging, possible values are: debug, info, warn, error
**/
var getLevel = function(module) {
return levels[module] || deflt;
};
var getEnabledWithLevel = function(acceptable, module) {
return function(){
// if (acceptable.indexOf(levels[module]) === -1) {
// console.log('Won\'t log %j because %j doesn\'t have %j (%j)', module, acceptable, levels[module], levels);
// }
return acceptable.indexOf(levels[module] || deflt) !== -1;
};
};
/**
* Handle messages from ipc
* @static
* @param {string} msg - message received from other processes
**/
var ipcHandler = function(msg){
var m, l, modules, i;
if (!msg || msg.cmd !== 'log' || !msg.config) {
return;
}
// console.log('%d: Setting logging config to %j (was %j)', process.pid, msg.config, levels);
if (msg.config.default) {
deflt = msg.config.default;
}
for (m in levels) {
var found = null;
for (l in msg.config) {
modules = msg.config[l].split(',').map(function(v){ return v.trim(); });
for (i = 0; i < modules.length; i++) {
if (modules[i] === m) {
found = l;
}
}
}
if (found === null) {
for (l in msg.config) {
modules = msg.config[l].split(',').map(function(v){ return v.trim(); });
for (i = 0; i < modules.length; i++) {
if (modules[i].indexOf('*') === -1 && modules[i] === m.split(':')[0]) {
found = l;
} else if (modules[i].indexOf('*') !== -1 && modules[i].split(':')[1] === '*' && modules[i].split(':')[0] === m.split(':')[0]) {
found = l;
}
}
}
}
if (found !== null) {
levels[m] = found;
} else {
levels[m] = deflt;
}
}
for (l in msg.config) {
if (msg.config[l] && l !== 'default') {
modules = msg.config[l].split(',').map(function(v){ return v.trim(); });
prefs[l] = modules;
for (i in modules) {
m = modules[i];
if (!(m in levels)) {
levels[m] = l;
}
}
} else {
prefs[l] = [];
}
}
prefs.default = msg.config.default;
// console.log('%d: Set logging config to %j (now %j)', process.pid, msg.config, levels);
};
/**
* Creates new logger object for provided module
* @param {string} name - name of the module
* @returns {module:api/utils/log~Logger} logger object
**/
module.exports = function(name) {
setLevel(name, logLevel(name));
// console.log('Got level for ' + name + ': ' + levels[name] + ' ( prefs ', prefs);
/**
* @class Logger
**/
return {
/**
* Logging debug level messages
* @memberof module:api/utils/log~Logger
* @param {...*} var_args - string and values to format string with
**/
d: log('DEBUG', name, getEnabledWithLevel(['debug'], name), this, console.log),
/**
* Logging information level messages
* @memberof module:api/utils/log~Logger
* @param {...*} var_args - string and values to format string with
**/
i: log('INFO', name, getEnabledWithLevel(['debug', 'info'], name), this, console.info),
/**
* Logging warning level messages
* @memberof module:api/utils/log~Logger
* @param {...*} var_args - string and values to format string with
**/
w: log('WARN', name, getEnabledWithLevel(['debug', 'info', 'warn'], name), this, console.warn, styles.stylers.warn),
/**
* Logging error level messages
* @memberof module:api/utils/log~Logger
* @param {...*} var_args - string and values to format string with
**/
e: log('ERROR', name, getEnabledWithLevel(['debug', 'info', 'warn', 'error'], name), this, console.error, styles.stylers.error),
/**
* Logging inside callbacks
* @memberof module:api/utils/log~Logger
* @param {function=} next - next function to call, after callback executed
* @returns function to pass as callback
**/
callback: function(next){
var self = this;
return function(err) {
if (err) { self.e(err); }
else if (next) {
var args = Array.prototype.slice.call(arguments, 1);
next.apply(this, args);
}
};
},
/**
* Logging database callbacks
* @memberof module:api/utils/log~Logger
* @param {string} name - name of the performed operation
* @param {function=} next - next function to call, after callback executed
* @returns function to pass as callback
**/
logdb: function(name, next, nextError) {
var self = this;
return function(err) {
if (err) {
self.e('Error while %j: %j', name, err);
if (nextError) {
nextError(err);
}
} else {
self.d('Done %j', name);
if (next) {
next.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
};
}
};
// return {
// d: log('DEBUG\t', getEnabledWithLevel(['debug'], name), this, debug(name)),
// i: log('INFO\t', getEnabledWithLevel(['debug', 'info'], name), this, debug(name)),
// w: log('WARN\t', getEnabledWithLevel(['debug', 'info', 'warn'], name), this, debug(name)),
// e: log('ERROR\t', getEnabledWithLevel(['debug', 'info', 'warn', 'error'], name), this, debug(name)),
// callback: function(next){
// var self = this;
// return function(err) {
// if (err) { self.e(err); }
// else if (next) {
// var args = Array.prototype.slice.call(arguments, 1);
// next.apply(this, args);
// }
// };
// },
// };
};
module.exports.setLevel = setLevel;
module.exports.setDefault = setDefault;
module.exports.getLevel = getLevel;
module.exports.ipcHandler = ipcHandler;