console.log timestamps in Chrome?

Solution 1:

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:

Show timestamps how-to picture

Solution 2:

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:

Sample output

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.