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


当前回答

试试这个:

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

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

或者这样,如果你想要一个时间戳:

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

console.log = function(data)
{
    var timestamp = '[' + Date.now() + '] ';
    this.logCopy(timestamp, data);
};

以一种很好的方式(如对象树表示)记录多个事物:

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

console.log = function()
{
    if (arguments.length)
    {
        var timestamp = '[' + Date.now() + '] ';
        this.logCopy(timestamp, arguments);
    }
};

带格式字符串(JSFiddle)

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

console.log = function()
{
    // Timestamp to prepend
    var timestamp = new Date().toJSON();

    if (arguments.length)
    {
        // True array copy so we can call .splice()
        var args = Array.prototype.slice.call(arguments, 0);

        // If there is a format string then... it must
        // be a string
        if (typeof arguments[0] === "string")
        {
            // Prepend timestamp to the (possibly format) string
            args[0] = "%o: " + arguments[0];

            // Insert the timestamp where it has to be
            args.splice(1, 0, timestamp);

            // Log the whole array
            this.logCopy.apply(this, args);
        }
        else
        { 
            // "Normal" log
            this.logCopy(timestamp, args);
        }
    }
};

输出:

附注:仅在Chrome中测试。

array .prototype.slice在这里并不完美,因为它将被记录为对象的数组,而不是对象的一系列。

其他回答

Chrome 98的更新如下:

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

Chrome 68:

“显示时间戳”移至设置

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

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

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

也试试这个:

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

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