Javascript Chrome 中的 console.log 时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12008120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:52:18  来源:igfitidea点击:

console.log timestamps in Chrome?

javascriptgoogle-chrome

提问by UpTheCreek

Is there any quick way of getting Chrome to output timestamps in console.logwrites (like Firefox does). Or is prepending new Date().getTime()the only option?

有没有什么快速的方法可以让 Chrome 在console.log写入中输出时间戳(就像 Firefox 那样)。或者预先准备new Date().getTime()是唯一的选择?

回答by Krzysztof Wolny

In Chrome, there is the option is Console Settings (Developer Tools -> Console -> Settings [upper-right corner] ) named "Show timestamps" which is exactly what I needed.

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

I've just found it. No other dirty hacks needed that destroys placeholders and erases place in the code where the messages was logged from.

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

Update for Chrome 68+

Chrome 68+ 更新

The "Show timestamps" setting has been moved to the Preferences pane of the "DevTools settings", found in the upper-right corner of the DevTools drawer:

“显示时间戳”设置已移至“DevTools 设置”的“首选项”窗格,位于 DevTools 抽屉的右上角:

enter image description here

在此处输入图片说明

回答by JSmyth

Try this:

尝试这个:

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

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



Or this, in case you want a timestamp:



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

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

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



To log more than one thingandin a nice way (like object tree representation):



要登录多件事情,并在一个不错的方式(如对象树表示):

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

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



With format string(JSFiddle)



带格式字符串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);
        }
    }
};



Outputs with that:

输出:

Sample output

样本输出

P.S.: Tested in Chrome only.

PS:仅在 Chrome 中测试。

P.P.S.: Array.prototype.sliceis not perfect here for it would be logged as an array of objects rather than a series those of.

PPS:Array.prototype.slice在这里并不完美,因为它会被记录为一个对象数组而不是一系列对象。

回答by SerzN1

You can use dev tools profiler.

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

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

"Timer name" must be the same. You can use multiple instances of timer with different names.

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

回答by tekiegirl

I originally added this as a comment, but I wanted to add a screenshot as at least one person could not find the option (or maybe it was not available in their particular version for some reason).

我最初将其添加为评论,但我想添加屏幕截图,因为至少有一个人找不到该选项(或者由于某种原因,他们的特定版本可能不可用)。

On Chrome 68.0.3440.106 (and now checked in 72.0.3626.121) I had to

在 Chrome 68.0.3440.106(现在签入 72.0.3626.121)我不得不

  • open dev tools (F12)
  • click the three-dot menu in the top right
  • click settings
  • select Preferences in the left menu
  • check show timestamps in the Console section of the settings screen
  • 打开开发工具 (F12)
  • 单击右上角的三点菜单
  • 点击设置
  • 在左侧菜单中选择首选项
  • 在设置屏幕的控制台部分检查显示时间戳

Settings >Preferences >Console >Show timestamps

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

回答by Paul S.

I convert argumentsto Arrayusing Array.prototype.sliceso that I can concatwith another Arrayof what I want to add, then pass it into console.log.apply(console, /*here*/);

我转换argumentsArrayusingArray.prototype.slice以便我可以concat使用我想要添加的另一个Array,然后将其传递给console.log.apply(console, /*here*/);

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"]

It seems that argumentscan be Array.prototype.unshifted too, but I don't know if modifying it like this is a good idea/will have other side effects

好像arguments也可以Array.prototype.unshifted,但是不知道这样修改是不是个好主意/会不会有其他副作用

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"]

回答by KiL

+new Dateand Date.now()are alternate ways to get timestamps

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

回答by itsazzad

From Chrome 68:

从 Chrome 68 开始:

"Show timestamps" moved to settings

“显示时间戳”移至设置

The Show timestamps checkbox previously in Console Settings Console Settings has moved to Settings.

之前控制台设置控制台设置中的显示时间戳复选框已移至设置

enter image description here

在此处输入图片说明

回答by Ian Jiang

If you are using Google Chrome browser, you can use chrome console api:

如果您使用的是 Google Chrome 浏览器,则可以使用 chrome 控制台 api:

  • console.time: call it at the point in your code where you want to start the timer
  • console.timeEnd: call it to stop the timer
  • console.time:在代码中要启动计时器的位置调用它
  • console.timeEnd:调用它来停止计时器

The elapsed time between these two calls is displayed in the console.

这两次调用之间经过的时间显示在控制台中。

For detail info, please see the doc link: https://developers.google.com/chrome-developer-tools/docs/console

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

回答by sho terunuma

Try this also:

也试试这个:

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

This function puts timestamp, filename and line number as same of built-in console.log.

此函数将时间戳、文件名和行号与内置 console.log.

回答by Beni Cherniavsky-Paskin

If you want to preserve line number information (each message pointing to its .log() call, not all pointing to our wrapper), you have to use .bind(). You can prepend an extra timestamp argument via console.log.bind(console, <timestamp>)but the problem is you need to re-run this every time to get a function bound with a fresh timestamp. An awkward way to do that is a function that returns a bound function:

如果你想保留行号信息(每条消息都指向它的 .log() 调用,而不是全部指向我们的包装器),你必须使用.bind(). 您可以通过添加额外的时间戳参数,console.log.bind(console, <timestamp>)但问题是您每次都需要重新运行它以获得绑定了新时间戳的函数。一种笨拙的方法是使用返回绑定函数的函数:

function logf() {
  // console.log is native function, has no .bind in some browsers.
  // TODO: fallback to wrapping if .bind doesn't exist...
  return Function.prototype.bind.call(console.log, console, yourTimeFormat());
}

which then has to be used with a double call:

然后必须与双重调用一起使用:

logf()(object, "message...")

BUT we can make the first call implicit by installing a propertywith getter function:

但是我们可以通过安装一个带有 getter 函数的属性来使第一次调用隐式:

var origLog = console.log;
// TODO: fallbacks if no `defineProperty`...
Object.defineProperty(console, "log", {
  get: function () { 
    return Function.prototype.bind.call(origLog, console, yourTimeFormat()); 
  }
});

Now you just call console.log(...)and automagically it prepends a timestamp!

现在您只需调用console.log(...)并自动添加时间戳!

> console.log(12)
71.919s 12 VM232:2
undefined
> console.log(12)
72.866s 12 VM233:2
undefined

You can even achieve this magical behavior with a simple log()instead of console.log()by doing Object.defineProperty(window, "log", ...).

您甚至可以通过简单的log()而不是console.log()通过执行来实现这种神奇的行为Object.defineProperty(window, "log", ...)



See https://github.com/pimterry/loglevelfor a well-done safe console wrapper using .bind(), with compatibility fallbacks.

请参阅https://github.com/pimterry/loglevel以获取使用.bind()具有兼容性回退的完善的安全控制台包装器。

See https://github.com/eligrey/Xccessorsfor compatibility fallbacks from defineProperty()to legacy __defineGetter__API. If neither property API works, you should fallback to a wrapper function that gets a fresh timestamp every time. (In this case you lose line number info, but timestamps will still show.)

请参阅https://github.com/eligrey/Xcccessors以了解从defineProperty()__defineGetter__API 的兼容性回退。如果这两个属性 API 都不起作用,您应该回退到每次都获得新时间戳的包装函数。(在这种情况下,您会丢失行号信息,但仍会显示时间戳。)



Boilerplate: Time formatting the way I like it:

样板:按我喜欢的方式格式化时间:

var timestampMs = ((window.performance && window.performance.now) ?
                 function() { return window.performance.now(); } :
                 function() { return new Date().getTime(); });
function formatDuration(ms) { return (ms / 1000).toFixed(3) + "s"; }
var t0 = timestampMs();
function yourTimeFormat() { return formatDuration(timestampMs() - t0); }