UNPKG

1.06 kBJavaScriptView Raw
1var util = require('util');
2var fmt = require('dateformat');
3
4var colors = {
5 info: '36',
6 error: '31;1',
7 warn: '33',
8 debug: '90'
9};
10
11/**
12 * Logs a message to the console. The level is displayed in ANSI colors,
13 * either bright red in case of an error or green otherwise.
14 */
15module.exports = function (cfg) {
16
17 function log(msg, level) {
18 if (cfg.timestamp) msg = color(fmt(cfg.timestamp), '30;1') + ' ' + msg;
19 var c = colors[level.toLowerCase()] || '32';
20 console.log('[' + color(level.toUpperCase(), c) + '] ' + msg);
21 }
22
23 function color(s, c) {
24 if (process.stdout.isTTY) {
25 return '\x1B[' + c + 'm' + s + '\x1B[0m';
26 }
27 return s;
28 }
29
30 log.debug = function () {
31 if (!cfg.debug) return
32 log(util.format.apply(util, arguments), 'debug');
33 };
34
35 log.info = function () {
36 log(util.format.apply(util, arguments), 'info');
37 };
38
39 log.warn = function () {
40 log(util.format.apply(util, arguments), 'warn');
41 };
42
43 log.error = function () {
44 log(util.format.apply(util, arguments), 'error');
45 };
46
47 return log;
48};