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


当前回答

我使用Array.prototype.slice将参数转换为Array,这样我就可以连接到我想添加的另一个Array,然后将它传递到console.log。应用(控制台,/ * * /);

var log = function () {
    return console.log.apply(
        console,
        ['['+new Date().toISOString().slice(11,-5)+']'].concat(
            Array.prototype.slice.call(arguments)
        )
    );
};
log(['foo']); // [18:13:17] ["foo"]

似乎参数也可以是array .prototype. unmoved,但我不知道这样修改是否是个好主意/会有其他副作用

var log = function () {
    Array.prototype.unshift.call(
        arguments,
        '['+new Date().toISOString().slice(11,-5)+']'
    );
    return console.log.apply(console, arguments);
};
log(['foo']); // [18:13:39] ["foo"]

其他回答

Chrome 98的更新如下:

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

Chrome 68:

“显示时间戳”移至设置

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

+new Date和Date.now()是获取时间戳的替代方法

我最初是作为评论添加的,但我想添加一个截图,因为至少有一个人找不到这个选项(或者由于某种原因,它在他们的特定版本中不可用)。

在Chrome 68.0.3440.106(现在检入72.0.3626.121)我必须

开放开发工具(F12) 点击右上方的三点菜单 点击设置 在左侧菜单中选择Preferences 在设置界面的控制台部分检查显示时间戳

我在大多数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);
}

我使用Array.prototype.slice将参数转换为Array,这样我就可以连接到我想添加的另一个Array,然后将它传递到console.log。应用(控制台,/ * * /);

var log = function () {
    return console.log.apply(
        console,
        ['['+new Date().toISOString().slice(11,-5)+']'].concat(
            Array.prototype.slice.call(arguments)
        )
    );
};
log(['foo']); // [18:13:17] ["foo"]

似乎参数也可以是array .prototype. unmoved,但我不知道这样修改是否是个好主意/会有其他副作用

var log = function () {
    Array.prototype.unshift.call(
        arguments,
        '['+new Date().toISOString().slice(11,-5)+']'
    );
    return console.log.apply(console, arguments);
};
log(['foo']); // [18:13:39] ["foo"]