Is it possible to bind a date/time to a console log?

对着背影说爱祢 提交于 2019-11-28 21:44:09

Yes. http://jsfiddle.net/SwFJg/6/

var DEBUG = (function(){
    var timestamp = function(){};
    timestamp.toString = function(){
        return "[DEBUG " + (new Date).toLocaleTimeString() + "]";    
    };

    return {
        log: console.log.bind(console, '%s', timestamp)
    }
})();

DEBUG.log("banana", {foo:'bar'}); //[DEBUG 2:43:21 PM] banana Object {foo: "bar"}
console.log("Peppercorn");        //Peppercorn 
DEBUG.log("apple");               //[DEBUG 2:43:21 PM] apple 
DEBUG.log("orange");              //[DEBUG 2:43:21 PM] orange 
setTimeout(function(){
    DEBUG.log("mango");           //[DEBUG 2:43:25 PM] mango 
},3000)

This works because toString is called on timestamp (and, in fact, everything) each time console.log is called.

We overwrite the default toString method, and replace it with a time stamp (obviously you can change the output to whatever you want).

I chose the above pattern because, as others have noted (in SO chat), you can easily extend the DEBUG object to do other things.

...
return {
    log: console.log.bind(console, '%s', timestamp),
    error: console.error.bind(console, '%s', timestamp),
    info: console.info.bind(console, '%s', timestamp),
    warn: console.warn.bind(console, '%s', timestamp),
    group: ...,
    groupEnd: ...,
    groupCollapsed: ... // etc
}
...

I think this is what you are looking for, which is simple

console.logCopy = console.debug.bind(console);

console.debug = function(data)
{
    var currentDate = '[' + new Date().toUTCString() + '] ';
    this.logCopy(currentDate, data);
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!