Created
June 1, 2016 13:05
-
-
Save matejc/d7a80ac81853bd3fe5e19ad31955261c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
To print line numbers and files in NodeJS where the console.* functions are called. | |
add `require('./console.js');` to the begining of your app | |
run the app with environment variable like so: `CONSOLE_LINES=true` | |
*/ | |
if (!process.env.CONSOLE_LINES) { | |
return; | |
} | |
var path = require('path'); | |
Object.defineProperty(global, '__stack', { | |
get: function() { | |
var orig = Error.prepareStackTrace; | |
Error.prepareStackTrace = function(_, stack) { | |
return stack; | |
}; | |
var err = new Error; | |
Error.captureStackTrace(err, arguments.callee); | |
var stack = err.stack; | |
Error.prepareStackTrace = orig; | |
return stack; | |
} | |
}); | |
Object.defineProperty(global, '__line', { | |
get: function() { | |
return __stack[1].getLineNumber(); | |
} | |
}); | |
['error', 'log', 'info', 'warn', 'trace'].forEach(function(name) { | |
var fn = console[name]; | |
console[name] = function() { | |
if (console._trace || (console.traceOptions && console.traceOptions.always)) { | |
if (Buffer.isBuffer(arguments[0])) { | |
arguments[0] = arguments[0].inspect(); | |
} else if (typeof arguments[0] === 'object') { | |
arguments[0] = JSON.stringify(arguments[0], null, ' '); | |
} | |
var pad = (arguments[0] && !console.traceOptions.right || !isatty ? ' ' : ''); | |
arguments[0] = console.traceFormat(__stack[1], name) + pad + arguments[0]; | |
} | |
arguments[0] = '[' + __stack[1].getFileName().replace(__dirname+path.sep, '') + ':' + __stack[1].getLineNumber() + '] ' + arguments[0]; | |
console._trace = false; | |
return fn.apply(this, arguments); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment