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!
您可以使用new Error().lineNumber
获取行号有关确定行号的更多信息- 确定行号
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.