【问题标题】:Is it possible to bind a date/time to a console log?是否可以将日期/时间绑定到控制台日志?
【发布时间】:2013-08-26 22:26:55
【问题描述】:

我有以下代码:

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

【问题讨论】:

  • 您可以提取从Error().stack调用它的行
  • @copy 那是我已经在做的......但这不允许您在控制台中单击它以到达源文件中的行

标签: javascript console.log


【解决方案1】:

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

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

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

【讨论】:

  • 仅当您仅将一件事传递给控制台日志时才会记录。如果您传递多件东西,它们就会丢失
  • 如果你想支持多个参数,你可以在这里使用我的解决方案:
【解决方案2】:

是的。 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
}
...

【讨论】:

  • 我认为你可以简化代码,如果你只是将一个带有toString 方法的对象直接传递给函数:console.log.bind(console, {toString: function() {...}})。无需创建DEBUG 或空函数。好主意!
  • 我明白了,有道理。至少在 Firefox 中,您可以将评估强制为字符串:jsfiddle.net/fkling/SwFJg/4。虽然 Chrome 也支持此功能,但它只显示 Object。请注意,您的解决方案对我来说似乎不适用于 Firefox,但如果您强制执行字符串评估,它可以:jsfiddle.net/fkling/SwFJg/5
  • @FelixKling 很奇怪。老实说,这个问题与 FF 并不完全相关,因为它已经包含时间戳。有点担心它会阻止任何内容被记录。有没有办法删除强制的字符串评估?
  • 有没有办法绑定多个函数?我的意思是,如果我想记录除时间戳之外的其他内容,它会在时间戳旁边而不是其他行上使用变量
猜你喜欢
  • 2014-07-13
  • 2016-12-13
  • 2012-11-08
  • 1970-01-01
  • 2015-03-09
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多