code everywhere
technology, web services and applications

adding console.log timestamp in javascript

posted on January 25, 2014, 5:45 pm in js

Developing with javascript you probably dump a lot of debug info using the console.log() function. But when going back into the log files, you really need to know what datetime a certain event is attached to.

Here's some simple code you can add that will modify the standard console.log() to add a timestamp in the form of DD/MM/YY HH:MM:SS.

(function() {
    var 
old console.log;
    
console.log("> Log Date Format DD/MM/YY HH:MM:SS - UTCString");
    
console.log = function() {
        var 
= new Date();
        var 
= ("0" + (n.getDate().toString())).slice(-2),
            
= ("0" + ((n.getMonth() + 1).toString())).slice(-2),
            
= ("0" + (n.getFullYear().toString())).slice(-2),
            
n.toUTCString().slice(-13, -4);
        Array.
prototype.unshift.call(arguments"[" "/" "/" "]");
        
old.apply(thisarguments);
    }
})();

And the result:

bash -- 70x32
> Log Date Format DD/MM/YY HH:MM:SS - UTCString
[11/09/16 20:57:06] Hello
[11/09/16 20:57:06] World...
Or take a look at your web browser's console.
setTimeout(function() {
  
console.log("Hello");
  
console.log("World...");
},
5000);

recent posts

< back