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

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

本文关键字:绑定 控制台 日志 时间 日期 是否      更新时间:2023-09-26

我有以下代码:

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的行。

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

这是因为每次调用console.log时,都会在timestamp上调用toString(实际上,所有内容)。

我们覆盖默认的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
}
...

我想这就是你想要的,简单的

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