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!
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!
Share Improve this question asked Aug 19, 2013 at 7:25 ElvisElvis 2894 silver badges14 bronze badges 5-
console.log()
does not return any value... so it is not possible with console.log – Arun P Johny Commented Aug 19, 2013 at 7:27 -
infact
myObj
ismyLog
, Just assign it – Moazzam Khan Commented Aug 19, 2013 at 7:27 - Technically, you could overwrite the function in the console's prototype, but that seems like a terrible idea. – Fenixp Commented Aug 19, 2013 at 7:28
- Do you want to save output as a String or an Object? – Moazzam Khan Commented Aug 19, 2013 at 7:33
- I would prefer as an object, but since i'm mainly interested in the line number, as a string would be a big help as well. – Elvis Commented Aug 19, 2013 at 7:39
4 Answers
Reset to default 2you can use new Error().lineNumber
to get line number
For more info about determining line number - determining line number
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();
Try saving myObj object. That is what the logger will log.
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
}
}