是否可以将日期/时间绑定到控制台日志? [英] Is it possible to bind a date/time to a console log?

查看:100
本文介绍了是否可以将日期/时间绑定到控制台日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

当我想记录前面加上 [DEBUG] 到控制台。
现在我想在日志中添加日期/时间,我尝试了这个:

Which works find when I want to log things prepended with [DEBUG] to the console. Now I want to add a date/time to the log and I tried this:

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

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

Which obviously does not work because it always logs the same time (the time that the .bind was called).

有没有办法(使用。绑定)记录每个日志的当前时间,不用必须这样做:

Is there any way (using .bind) to log the current time on each log without having to do this:

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

Because the above method shows me the line that console.log.apply was called and not the line that myLog was called.

推荐答案

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

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

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

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

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

我选择了上面的模式,因为正如其他人所说的那样(在SO聊天中),你可以轻松扩展DEBUG对象来做其他事情。

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

这篇关于是否可以将日期/时间绑定到控制台日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆