3

I would like to save the output of the console.log() function as an object, or as a variable. I'm mainly interested in receiving object-results, as well as the line numbers.

The following is just to demonstrate, what i'm looking for:

var myobj = {"key":"value"}; // (<< in 'myjs.js, line 123)
var mylog = console.log( myobj );

// output mylog: {"key":"value"}, myjs.js:123

Thanks in advance for any help!

Elvis
  • 289
  • 4
  • 14

4 Answers4

2

you can use new Error().lineNumber to get line number For more info about determining line number - determining line number

Community
  • 1
  • 1
Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
  • 1
    This is a very interesting hint, thank you! Unfortunately, Error() does not seem to be as cross-browser compatible, as console(). If there should be a way to catch the console output, i'd prefer this. So far, this one comes very close! – Elvis Aug 19 '13 at 08:04
1

You can overwrite console.log and call Error().stack in google chrome it show line numbers.

In google chrome stack look like this:

Error
    at Error (<anonymous>)
    at Console.console.log (http://localhost/test.js:6:27)
    at foo (http://localhost/test.js:13:13)
    at http://localhost/test.js:16:1 

So the code need to fetch 3 line and remove "at http://localhost" and number of chars

(function(log) {
    console.log = function(o) {
        var stack = Error().stack.split('\n');
        log.call(console, JSON.stringify(o) + ', ' + stack[3].
            replace(/.*http:\/\/[^\/]*|:[0-9]+\)$/g, ''));
    };
})(console.log);


function foo() {
    console.log({foo: 'bar'});
}

foo();
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

Try saving myObj object. That is what the logger will log.

BVdjV
  • 116
  • 1
  • 1
  • 11
0

you can try this from the link Read the output of console.log

function myFunctionThatMightHaveAnError(){
    // instead of just failing silently, actually throw an error
    $.error("My special error");
}
// Then use a try/catch block to handle it
try {
    myFunctionThatMightHaveAnError();
    alert("No error!"); // this line would only run if no error were thrown
} catch (e) {
    if(e == "My special error") {
        // Handle error
    }
}
MaveRick
  • 1,181
  • 6
  • 20
  • Thanks! I made a similar workaround myself, but i'm missing how to catch the line number. – Elvis Aug 19 '13 at 07:36
  • this code is actually capturing the error output from the function so technically you are not reading console.log because you can't read the console.... as my knowledge so far, as a result you can't capture the line number using this code ... or any – MaveRick Aug 19 '13 at 07:42