13

I'm working on enhancing logging in some node.js applications. In the past have used C++'s __ file__ and __ line __ preprocessor macros to help us track down issues when logging events. I haven't found anything similar to it in the node.js world.

Does anyone have suggestions or know how I can get line number and file name in node.js for logging purposes?

I'm looking for something like:

console.log(__FILE__ + "." + __LINE__ + "\t" + new Date().toISOString() + " Message ");
jeremy
  • 4,294
  • 3
  • 22
  • 36

4 Answers4

16

see the global object:

__filename 

for the lineNumber see this post: javascript node.js getting line number in try catch?

Community
  • 1
  • 1
hereandnow78
  • 14,094
  • 8
  • 42
  • 48
9

See: Accessing line number in V8 JavaScript (Chrome & Node.js)

Then for a filename:

Object.defineProperty(global, '__file', {
  get: function(){
    return __stack[1].getFileName().split('/').slice(-1)[0];
  }
});

You could also just use the process.argv[1] instead of calling the __stack getter but I wanted to keep it similar.

Community
  • 1
  • 1
travis
  • 8,055
  • 1
  • 17
  • 19
4

Expanded on the previous answers a bit into here: https://gist.github.com/gavinengel/8572856

Allows setting globals: __line, __file, __ext, __dir

By the way, how do I create?: __function, __method, __class

Gavin
  • 752
  • 8
  • 20
  • Thanks for the gist. You should consider making this into a node module, it could be a nice npm module – jeremy Jan 23 '14 at 15:13
  • Sure. Actually, I'd recommend you check out this code which I just realized was out there by the PHPJS team: https://github.com/kvz/phpjs/tree/master/experimental/language – Gavin Jan 25 '14 at 06:10
2

Just use the C preprocesor, adds an extra build step to your code but then it allows stripping out your logging for production code.

Jim
  • 189
  • 1
  • 14