Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extend the console object (for rerouting the logging) in javascript?

Is it possible to extend the console object?

I tried something like:

Console.prototype.log = function(msg){     Console.prototype.log.call(msg);     alert(msg); } 

But this didn't work. I want to add additional logging to the console object via a framework like log4javascript and still use the standard console object (in cases where log4javascript is not available) in my code.

Thanks in advance!

like image 233
prefabSOFT Avatar asked Feb 14 '12 13:02

prefabSOFT


People also ask

How do I make the console log in with different lines?

To display a console. log in multiple lines we need to break the line with \n console. log("Hello \n world!"); That will display it like this: Hello world!

How do you wrap a console log?

Another way to console. log your variables is to simply place your mouse cursor on them and then wrap them on the line below with Ctrl+Alt+W + Down or the line above with Ctrl+Alt+W + Up .

Can you console log in JavaScript?

log() Method. The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.


2 Answers

Try following:

(function() {     var exLog = console.log;     console.log = function(msg) {         exLog.apply(this, arguments);         alert(msg);     } })() 
like image 131
Sergey Ilinsky Avatar answered Sep 30 '22 03:09

Sergey Ilinsky


You Can Also add log Time in This Way :

added Momentjs or use New Date() instead of moment.

var oldConsole = console.log; console.log = function(){     var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";     Array.prototype.unshift.call(arguments, timestamp);     oldConsole.apply(this, arguments); }; 
like image 29
nitesh singh Avatar answered Sep 30 '22 03:09

nitesh singh