Search code examples
javascriptconsole.lognw.jsnwjs

javascript - Capturing console with line number


How do I capture the line number of logs when capturing the console? (Chrome only - other browsers not relevant for me)

I have the below to capture all logs;

consoleLogs: [],

init: function(){
    app.captureConsole();
},

captureConsole: function(){
    var _log = console.log;

    console.log = function() {
        app.consoleLogs.push(JSON.stringify({method: 'log', args: arguments}));
        return _log.apply(console, arguments); // <-- line number 123 [e.g.]
    };
},

When the console is returned the line number for all consoles is 123 as expected - this isn't important. What I want is to be able to push the original console log number to my array.

It is a nw.js app so a chrome api / nw api would be great [if it exists]


Solution

  • You can try to parse the value of new Error().stack. It is a string which is the stack trace of the scope where the Error object was created.

    The output is browser dependent since it is a non-standard feature. Since you only need it to work on nw.js it could be an option for you.

    On node.js (and I suspect chrome) the output is a newline separated string where each line is of the format:

    at functionName (/absolute/file/path:lineNumber:charNumber)
    

    So the in your case the information you want is probably:

    new Error().stack.split('\n')[1];