67

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 2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

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
See also this answer for some sample code to output the whole trace. stackoverflow.com/questions/6163807/…
One can see some example use of this API here: github.com/jameswomack/capn/blob/master/test/capn.js
@zamnuts That page doesn't seem to list any of those functions any more
The URL for documentation of v8 stack trace API in 2019 is v8.dev/docs/stack-trace-api
|
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;
    }
};

5 Comments

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 well
@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 :)
understood—what you're saying makes sense
arguments.callee removed from ES5 strict mode: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
The only problem with this answer is arguments.callee. It really shouldn't be used. Im surprised its even supported at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.