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


当前回答

Chrome版本89.0.4389.90 (19.03.2021)

按F12。 找到并按齿轮图标。 检查显示时间戳。

其他回答

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

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

试试这个:

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版本89.0.4389.90 (19.03.2021)

按F12。 找到并按齿轮图标。 检查显示时间戳。

ES6解决方案:

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

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