是否可以将日期/时间绑定到控制台日志?

时间:2013-08-23 19:06:01

标签: javascript console.log

我有以下代码:

var myLog = console.log.bind(console, '[DEBUG]');

当我想将[DEBUG]前面的内容记录到控制台时,可以找到哪些内容。 现在我想在日志中添加日期/时间,我尝试了这个:

var myLog = console.log.bind(console, '[DEBUG ' + (new Date) + ']');

这显然不起作用,因为始终记录的时间相同(.bind被调用的时间。)

有没有办法(使用.bind)记录每个日志的当前时间,而不必执行此操作:

var myLog = function(){
    var args = ['[DEBUG ' + (new Date) + ']'];
    for(var i = 0; i < arguments.length; ++i) {
        args.push(arguments[i]);
    }
    return console.log.apply(console, args);
};

因为上述方法向我显示了console.log.apply被调用的行和调用myLog的行。

2 个答案:

答案 0 :(得分:27)

是。 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)

这是有效的,因为每次调用toStringtimestamp都会调用console.log(实际上,所有内容都会调用)。

我们覆盖默认的toString方法,并将其替换为时间戳(显然,您可以将输出更改为您想要的任何内容)。

我选择了上述模式,因为正如其他人所说的那样(在SO聊天中),您可以轻松地扩展DEBUG对象以执行其他操作。

...
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
}
...

答案 1 :(得分:2)

我认为这就是你要找的,这很简单

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

console.debug = function(data)
{
    var currentDate = '[' + new Date().toUTCString() + '] ';
    this.logCopy(currentDate, data);
};
相关问题