Skip to content

Instantly share code, notes, and snippets.

@atomizer
Created September 29, 2013 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atomizer/6754833 to your computer and use it in GitHub Desktop.
Save atomizer/6754833 to your computer and use it in GitHub Desktop.
a console.log replacement that prints callee file name and line
// this goes in the main file
// (assumes that all the modules that use this function are in the same directory or below)
// the Error.stack trick suggested by isaacbw on #Node.js on freenode
global.log = function() {
var line = new Error().stack.match(/at .+\n/g)[1]
var filename = line.match(/\((.+?\.js:\d+)/)[1].replace(__dirname, '').slice(1)
var args = [].slice.call(arguments)
args.unshift('[%s]', filename)
console.log.apply(this, args)
}
// and so
var foo = require('./lib/foo')
// then, in module lib/foo.js
global.log('hey')
// prints "[lib/foo.js:42] hey"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment