Can I extend the console object (to redirect logging) in javascript?

Can I extend the console object?

I tried something like:

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

But that did not work. I want to add an additional entry to the console object through a framework such as log4javascript and still use the standard console object (in cases where log4javascript is not available) in my code.

Thanks in advance!

+25
javascript logging extend
Feb 14 '12 at 13:33
source share
5 answers

Try the following:

 (function() { var exLog = console.log; console.log = function(msg) { exLog.apply(this, arguments); alert(msg); } })() 
+37
Feb 14 '12 at 13:52
source share

Use a proxy template, see my answer for a similar case:

JavaScript: warning override ()

Hope this helps

+11
Feb 14 2018-12-14T00:
source share

You can also add log time in this way:

Moments added or use New Date () instead of a 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); }; 
+2
Dec 12 '16 at 4:54 on
source share
 // console aliases and verbose logger - console doesnt prototype var c = console; cl = c.log, ce = c.error, cv = c.verbose = function() { if (!myclass || !myclass.verbose) // verbose switch return; var args = Array.prototype.slice.call(arguments); // toArray args.unshift('Verbose:'); clapply(this, args); // log }; // you can then do var myclass = new myClass(); myclass.prototype.verbose = false; // generally these calls would be inside your class cv('1 This will NOT log as verbose == false'); cl('2 This will log'); myclass.verbose = true; cv('3 This will log'); 

I noticed that the above use of Array.prototype.unshift.call by nitesh is the best way to add the tag "Verbose:".

+1
Apr 6 '17 at 0:50
source share

This is really the same as some others have given, but I think this is the most elegant and least hacker way to achieve this. The propagation syntax (... args) ensures that no arguments are lost .

 var _console={...console} console.log = function(...args) { var msg = {...args}[0]; //YOUR_CODE _console.log(...args); } 
0
Dec 7 '18 at 15:29
source share



All Articles