-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
90 lines (71 loc) · 2.31 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
/* jslint node:true */
'use strict';
require('colors');
var prettyjson = require('prettyjson'),
util = require('util');
var options = {
errorTag: 'ERROR'.red.bold,
timestamp: false,
splatchError: false
};
function splatchError(error) {
var result = { };
Object.getOwnPropertyNames(error).forEach(function (key) {
var value = this[key];
if (value instanceof Error) value = splatchError(value);
result[key] = value;
}, error /* thisArg */);
return prettyjson.render(result);
}
var originalError = console.error;
console.error = function () {
var args = options.errorTag ? [String(options.errorTag)] : [];
var arg = null;
if (options.timestamp) args.push((new Date()).toISOString().bold);
// convert arguments into real Array
var tmp = [];
for (arg in arguments) tmp.push(arguments[arg]);
// just print empty logs like this
if (tmp.length === 0) {
originalError();
return;
}
// check for string interpolation
if (tmp[0]) {
var match = String(tmp[0]).match(/%[sdj]/g);
if (match) {
args.push(util.format.apply(null, tmp.slice(0, match.length + 1)));
tmp = tmp.slice(match.length + 1);
}
}
// extract errors
var errors = [];
for (arg in arguments) {
if (arguments[arg] instanceof Error) {
errors.push(arguments[arg]);
}
}
for (arg in tmp) {
if (tmp[arg] instanceof Error) {
args.push(tmp[arg].message);
} else {
args.push(tmp[arg]);
}
}
var pos = new Error().stack.split('\n')[2];
if (pos.indexOf('(') >= 0) pos = pos.slice(pos.indexOf('(') + 1).replace(')', '');
if (pos.indexOf(' at ') >= 0) pos = pos.slice(pos.indexOf(' at ') + 4);
args.push(String('[ ' + pos + ' ]').bold);
if (errors.length > 0) args = args.concat(errors.map(function (e) {
if (options.splatchError) return '\n' + splatchError(e);
return '\n' + (e.message ? e.message : '').italic.bold + ' ' + e.stack.grey;
}));
originalError.apply(console, args);
};
module.exports = exports = function (_options) {
if (typeof _options !== 'object') return;
if (_options instanceof Array) return;
for (var p in _options) {
options[p] = _options[p];
}
};