问题描述:

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 is Console Settings (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.

网友答案:

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:

P.S.: Tested in Chrome only.

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

网友答案:

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.

网友答案:

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

网友答案:

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.unshifted 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"]
网友答案:

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

网友答案:

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.

网友答案:

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

网友答案:

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); }
网友答案:

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
相关阅读:
Top