简体   繁体   中英

console.log timestamps in Chrome?

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

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

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+

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:

显示时间戳操作方法图片

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 thing and in 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 )

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:

样本输出

PS: Tested in Chrome only.

PPS: Array.prototype.slice is not perfect here for it would be logged as an array of objects rather than a series those of.

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

  • 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

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

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.

I convert arguments to Array using Array.prototype.slice so that I can concat with another Array of what I want to add, then pass it into 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 arguments can be Array.prototype.unshift ed too, but I don't know if modifying it like this is a good idea/will have other side effects

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

If you are using Google Chrome browser, you can use chrome console 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

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

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

From Chrome 68:

"Show timestamps" moved to settings

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

在此处输入图片说明

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 .

ES6 solution:

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

where timestamp() returns actually formatted timestamp and log add a timestamp and propagates all own arguments to console.log

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:

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 property with getter function:

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(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", ...) .


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

See https://github.com/eligrey/Xccessors for 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.)


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); }

This adds a "log" function to the local scope (using this ) using as many arguments as you want:

this.log = function() {
    var args = [];
    args.push('[' + new Date().toUTCString() + '] ');
    //now add all the other arguments that were passed in:
    for (var _i = 0, _len = arguments.length; _i < _len; _i++) {
      arg = arguments[_i];
      args.push(arg);
    }

    //pass it all into the "real" log function
    window.console.log.apply(window.console, args); 
}

So you can use it:

this.log({test: 'log'}, 'monkey', 42);

Outputs something like this:

[Mon, 11 Mar 2013 16:47:49 GMT] Object {test: "log"} monkey 42

I have this in most Node.JS apps. It also works in the browser.

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

extended the very nice solution "with format string" from JSmyth to also support

  • all the other console.log variations ( log , debug , info , warn , error )
  • including timestamp string flexibility param (eg 09:05:11.518 vs. 2018-06-13T09:05:11.518Z )
  • including fallback in case console or its functions do not exist in browsers

.

var Utl = {

consoleFallback : function() {

    if (console == undefined) {
        console = {
            log : function() {},
            debug : function() {},
            info : function() {},
            warn : function() {},
            error : function() {}
        };
    }
    if (console.debug == undefined) { // IE workaround
        console.debug = function() {
            console.info( 'DEBUG: ', arguments );
        }
    }
},


/** based on timestamp logging: from: https://stackoverflow.com/a/13278323/1915920 */
consoleWithTimestamps : function( getDateFunc = function(){ return new Date().toJSON() } ) {

    console.logCopy = console.log.bind(console)
    console.log = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.logCopy.apply(this, args)
            } else this.logCopy(timestamp, args)
        }
    }
    console.debugCopy = console.debug.bind(console)
    console.debug = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.debugCopy.apply(this, args)
            } else this.debugCopy(timestamp, args)
        }
    }
    console.infoCopy = console.info.bind(console)
    console.info = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.infoCopy.apply(this, args)
            } else this.infoCopy(timestamp, args)
        }
    }
    console.warnCopy = console.warn.bind(console)
    console.warn = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.warnCopy.apply(this, args)
            } else this.warnCopy(timestamp, args)
        }
    }
    console.errorCopy = console.error.bind(console)
    console.error = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.errorCopy.apply(this, args)
            } else this.errorCopy(timestamp, args)
        }
    }
}
}  // Utl

Utl.consoleFallback()
//Utl.consoleWithTimestamps()  // defaults to e.g. '2018-06-13T09:05:11.518Z'
Utl.consoleWithTimestamps( function(){ return new Date().toJSON().replace( /^.+T(.+)Z.*$/, '$1' ) } )  // e.g. '09:05:11.518'

Chrome Version 89.0.4389.90 (19.03.2021)

  1. Press F12.
  2. Find and press gear wheel icon.
    1
  3. Check Show timestamps .
    2

A refinement on the answer by 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);
    }
};

This:

  • shows timestamps with milliseconds
  • assumes a format string as first parameter to .log

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM