forked from LearnBoost/console-trace
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdebug-trace-browser.js
90 lines (77 loc) · 2.28 KB
/
debug-trace-browser.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
/**
* Store custom options
*
* @param {Object} options
* @api public
*/
module.exports = function debugTrace(options) {
options = options || {};
console.traceOptions = console.traceOptions || {};
console.traceOptions.always = typeof options.always !== 'undefined' ? options.always : true;
}
// only works with Chrome (V8)
if (typeof Error.captureStackTrace === 'function') {
var callsite = require('callsite');
/**
* Overrides the console methods.
*/
;['error', 'log', 'info', 'warn', 'trace'].forEach(function (name) {
var fn = console[name];
console[name] = function () {
var args = arguments;
if (console._trace || console.traceOptions.always) {
if (args.length === 1) args = ['', args[0]];
if (typeof args[0] === 'object') {
args[0] = JSON.stringify(args[0], null, ' ');
}
// when using the debug module: dig one level deeper in the stack
var stack = callsite();
var trace = stack[1];
if (stack.length > 2 && trace.getFunctionName() === 'log') {
trace = stack[3];
trace.debug = true;
}
trace.debug = trace.debug || false;
args[0] = console.traceFormat(trace, name) + args[0];
}
console._trace = false;
return fn.apply(this, args);
}
});
/**
* Overridable formatting function.
*
* @param {CallSite}
* @param {String} calling method
* @api public
*/
console.traceFormat = function (call, method) {
var options = {};
call.method = method;
call.functionName = call.getFunctionName() || 'anonymous';
call.getDate = function getDate() {
return new Date().toISOString().replace('T', ' ').replace('Z', '');
}
return console.format(call);
}
/**
* Overridable string formatting function.
*
* @param {CallSite} CallSite Object pimped with additional properties.
* @api public
*/
console.format = function (c) {
return "[" + c.getFileName() + ":" + c.getLineNumber() + "] " + c.functionName + " ";
};
/**
* Adds trace getter to the `console` object.
*
* @api public
*/
function getter() {
this._trace = true;
return this;
}
Object.defineProperty(console, 't', { get: getter });
Object.defineProperty(console, 'traced', { get: getter });
}