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.
2 Answers
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.
-
3code.google.com/p/v8/wiki/… 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– zamnutsMay 14, 2013 at 23:02
-
See also this answer for some sample code to output the whole trace. stackoverflow.com/questions/6163807/… Mar 20, 2014 at 22:20
-
One can see some example use of this API here: github.com/jameswomack/capn/blob/master/test/capn.js Mar 24, 2014 at 10:29
-
@zamnuts That page doesn't seem to list any of those functions any more– MichaelNov 16, 2016 at 18:13
-
2The URL for documentation of v8 stack trace API in 2019 is v8.dev/docs/stack-trace-api– gtzillaAug 20, 2019 at 19:52
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;
}
};
-
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 Jan 17, 2020 at 20:03 -
@james_womack
arguments.callee.caller
is not always reachable (in my nodejs application it isn't). Also: eslint.org/docs/rules/no-caller but I guess it was okay to use it at the time your wrote the answer :) Jan 17, 2020 at 22:41 -
-
1
arguments.callee
removed from ES5 strict mode: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Nov 20, 2021 at 3: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ΞVFeb 12, 2022 at 6:56