是否有任何快速的方法让Chrome在console.log写入中输出时间戳(像Firefox那样)。或者是prepending new Date().getTime()是唯一的选项?


当前回答

也试试这个:

this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );

该函数将时间戳、文件名和行号与内置console.log相同。

其他回答

如果您使用谷歌Chrome浏览器,您可以使用Chrome控制台api:

控制台。时间:在代码中你想要开始计时器的地方调用它 控制台。timeEnd:调用它来停止计时器

这两个调用之间的运行时间显示在控制台中。

有关详细信息,请参阅doc链接:https://developers.google.com/chrome-developer-tools/docs/console

在Chrome中,有一个控制台设置选项(按F1或选择开发人员工具->控制台->设置[右上角])名为“显示时间戳”,这正是我所需要的。

我刚找到。不需要其他肮脏的黑客破坏占位符和擦除代码中记录消息的地方。

Chrome 68+更新

“显示时间戳”设置已经移动到“DevTools设置”的Preferences窗格中,在DevTools抽屉的右上角:

ES6解决方案:

const timestamp = () => `[${new Date().toUTCString()}]`
const log = (...args) => console.log(timestamp(), ...args)

其中timestamp()返回实际格式化的时间戳和日志添加一个时间戳,并将所有自己的参数传播到console.log

您可以使用开发工具分析器。

console.time('Timer name');
//do critical time stuff
console.timeEnd('Timer name');

“定时器名称”必须相同。您可以使用多个具有不同名称的计时器实例。

这将添加一个“log”函数到局部作用域(使用This),使用尽可能多的参数:

this.log = function() {
    var args = [];
    args.push('[' + new Date().toUTCString() + '] ');
    //now add all the other arguments that were passed in:
    for (var _i = 0, _len = arguments.length; _i < _len; _i++) {
      arg = arguments[_i];
      args.push(arg);
    }

    //pass it all into the "real" log function
    window.console.log.apply(window.console, args); 
}

所以你可以使用它:

this.log({test: 'log'}, 'monkey', 42);

输出如下所示:

[Mon, 11 Mar 2013 16:47:49 GMT]对象{test: "log"} monkey 42