Last active
August 29, 2015 14:10
-
-
Save imposibrus/405496bdf67f679c7ec2 to your computer and use it in GitHub Desktop.
Node.js debug.js with file name and line number
This file contains 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
// first: npm i debug --save | |
// run with DEBUG=worker,worker2 node app.js | |
var debug = require('./debug')('worker'); | |
debug('worker'); | |
var debug2 = require('./debug')('worker2'); | |
debug2('worker2'); | |
// print: | |
// worker app.js:6:1 +0ms worker | |
// worker2 app.js:10:1 +2ms worker2 |
This file contains 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
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(); | |
} | |
}); | |
var path = require('path'); | |
module.exports = function(namespace) { | |
var debug = require('debug')(namespace); | |
if(!debug.enabled) { | |
return function() {}; | |
} | |
return function(str) { | |
var stackArr = (new Error).stack.split("\n"), | |
currFile = stackArr.filter(function(stackLine) {return stackLine.indexOf(__filename) !== -1;}), | |
callerFile, | |
matchedString, | |
callerName = []; | |
if(currFile.length) { | |
callerFile = stackArr[stackArr.indexOf(currFile[0]) + 1]; | |
matchedString = callerFile.split(/\s/).pop().match(/(.[^:]*):([0-9]+):([0-9]+)/); | |
if(matchedString) { | |
callerName = [path.basename(matchedString[1]), matchedString[2], matchedString[3]]; | |
} | |
} | |
debug(callerName.join(':') + ' ' + str); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment