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


当前回答

我在大多数Node.JS应用程序中都有这个。它也适用于浏览器。

function log() {
  const now = new Date();
  const currentDate = `[${now.toISOString()}]: `;
  const args = Array.from(arguments);
  args.unshift(currentDate);
  console.log.apply(console, args);
}

其他回答

ES6解决方案:

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

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

JSmyth对答案的改进:

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

console.log = function()
{
    if (arguments.length)
    {
        var timestamp = new Date().toJSON(); // The easiest way I found to get milliseconds in the timestamp
        var args = arguments;
        args[0] = timestamp + ' > ' + arguments[0];
        this.logCopy.apply(this, args);
    }
};

这样的:

显示以毫秒为单位的时间戳 假设一个格式字符串作为.log的第一个参数

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

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

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

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

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

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

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

Chrome 98的更新如下:

设置—>首选项—>控制台—>显示时间戳

Chrome 68:

“显示时间戳”移至设置

以前在“控制台设置”中的“显示时间戳”复选框已移动到“设置”。