JavaScript developers who have spent time in languages like C often miss the ability to use certain types of introspection, like logging line numbers, and what method the current method was invoked from. Well if you're using V8 (Chrome, Node.js) you can employ the following.
Asked
Active
Viewed 3.1k times
2 Answers
102
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();
}
});
console.log(__line);
The above will log 19
.
Combined with arguments.callee.caller
you can get closer to the type of useful logging you get in C via macros.

james_womack
- 10,028
- 6
- 55
- 74
-
3https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi#Customizing_stack_traces has a list of other methods available in the v8 StackTrace API. A general list: getThis, getTypeName, getFunction, getFunctionName, getMethodName, getFileName, getLineNumber, getColumnNumber, getEvalOrigin, isToplevel, isEval, isNative, isConstructor – zamnuts May 14 '13 at 23:02
-
See also this answer for some sample code to output the whole trace. http://stackoverflow.com/questions/6163807/customized-stack-traces-in-google-chrome-developer-tools/10942404#10942404 – Charles Kendrick Mar 20 '14 at 22:20
-
One can see some example use of this API here: https://github.com/jameswomack/capn/blob/master/test/capn.js – james_womack Mar 24 '14 at 10:29
-
@zamnuts That page doesn't seem to list any of those functions any more – Michael Nov 16 '16 at 18:13
-
This does not work in strict mode as it relies on arguments.callee :/ – mattyb Mar 09 '17 at 19:53
-
@Midas It works in strict mode in Node.js—just paste 'use strict' and then my code example into the Node REPL to test. That said, the `__stack` technique is a special operation that you largely should not use in production code. FWIW I also typically use in Node.js rather than in Chrome. Many of the benefits of strict mode can be attained by using ESLint w/ ES6 in recent versions of Node. You can use a transpiler or bundler plugin to add 'strict' and strip out __stack for prod if you'd like. See Bunyan for a package that recommends conditionally using this technique. – james_womack Mar 21 '17 at 17:28
-
2The URL for documentation of v8 stack trace API in 2019 is https://v8.dev/docs/stack-trace-api – gtzilla Aug 20 '19 at 19:52
8
The problem with the accepted answer, IMO, is that when you want to print something you might be using a logger, and when that is the case, using the accepted solution will always print the same line :)
Some minor changes will help avoiding such a case!
In our case, we're using Winston for logging, so the code looks like this (pay attention to the code-comments below):
/**
* Use CallSite to extract filename and number, for more info read: https://v8.dev/docs/stack-trace-api#customizing-stack-traces
* @returns {string} filename and line number separated by a colon
*/
const getFileNameAndLineNumber = () => {
const oldStackTrace = Error.prepareStackTrace;
try {
// eslint-disable-next-line handle-callback-err
Error.prepareStackTrace = (err, structuredStackTrace) => structuredStackTrace;
Error.captureStackTrace(this);
// in this example I needed to "peel" the first CallSites in order to get to the caller we're looking for
// in your code, the number of stacks depends on the levels of abstractions you're using
// in my code I'm stripping frames that come from logger module and winston (node_module)
const callSite = this.stack.find(line => line.getFileName().indexOf('/logger/') < 0 && line.getFileName().indexOf('/node_modules/') < 0);
return callSite.getFileName() + ':' + callSite.getLineNumber();
} finally {
Error.prepareStackTrace = oldStackTrace;
}
};

Nir Alfasi
- 53,191
- 11
- 86
- 129
-
2This is another great solution. My answer was written so long ago, but I believe my reference to `arguments.callee.caller` was about resolving the issue you raise here as well – james_womack Jan 17 '20 at 20:03
-
@james_womack `arguments.callee.caller` is not always reachable (in my nodejs application it isn't). Also: https://eslint.org/docs/rules/no-caller but I guess it was okay to use it at the time your wrote the answer :) – Nir Alfasi Jan 17 '20 at 22:41
-
-
1`arguments.callee` removed from ES5 strict mode: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee – Jason Stewart Nov 20 '21 at 03:24
-
The only problem with this answer is arguments.callee. It really shouldn't be used. Im surprised its even supported at all. – JΛYDΞV Feb 12 '22 at 06:56