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.
8 Comments
zamnuts
code.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
Charles Kendrick
See also this answer for some sample code to output the whole trace. stackoverflow.com/questions/6163807/…
james_womack
One can see some example use of this API here: github.com/jameswomack/capn/blob/master/test/capn.js
Michael
@zamnuts That page doesn't seem to list any of those functions any more
gtzilla
The URL for documentation of v8 stack trace API in 2019 is v8.dev/docs/stack-trace-api
|
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;
}
};
5 Comments
james_womack
This 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 wellNir Alfasi
@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 :)james_womack
understood—what you're saying makes sense
Jason Stewart
arguments.callee removed from ES5 strict mode: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…JAYD3V
The only problem with this answer is arguments.callee. It really shouldn't be used. Im surprised its even supported at all.