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?
-
1can you please change the accepted answer? The second most voted one is much simpler.– Liron YahdavFeb 12, 2015 at 18:13
-
Looks like Chrome have changed how to turn this on. See, github.com/Microsoft/vscode/issues/61298#issuecomment-431422747– itsthetasteFeb 12, 2019 at 1:09
16 Answers
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:
-
3As @Krzysztof Wolny pointed out, this is now built-in to Chrome 35 DevTools. (Yay!) Enable by opening developer tools (e.g. F12 or "Inspect Element"), click on the "gear" to view settings, then check the "Show timestamps" checkbox in the "Console" section. !Enable timestamps setting in devtools twitter.com/addyosmani#stream-item-tweet-485862365247053824 html5rocks.com/en/tutorials/developertools/chrome-35/… codereview.chromium.org/185713007– jacobqJul 7, 2014 at 13:56
-
1Is there a way to use a pattern for the timestamp in Chrome ? I only need the hour and minute.– AugustJun 8, 2016 at 8:59
-
36On Chrome 68.0.3440.106 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 (top right) Sep 4, 2018 at 9:52
-
570.0.3538.110 (Official Build) (64-bit) This answer once worked for me: i.e. console "gear icon"; "Show timestamps" checkmark ... but now I don't see "Show timestamps" in Chrome 70.0.3538.110 (Official Build) (64-bit) So I tried @tekiegirl's suggestion re: Chrome 68: i.e. open dev tools (F12) > click the three-dot menu in the top right > click settings > select Preferences in the left menu > check show timestamps ... but I don't see "Preferences" in the left menu of Settings 70.0.3538.110 (Official Build) (64-bit) Dec 5, 2018 at 18:14
-
2Thanks @tekiegirl , agree, your answer solves my problem! That is, users of Chrome 68+ must change DevTools settings (vs the drawer for quick Console settings).in the DevTools settings, "Preferences" tab, "Console" header; youwill find the "Show timestamps" checkbox. Apr 2, 2019 at 16:28
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.
-
Rewritten the log statement to display objects in Chrome's console in a lovely manner, the previous version was simply showing "[object Object]" or sort of.– JSmythNov 7, 2012 at 23:28
-
-
This will not work in the general case where the first argument to log is a format string– blueFastFeb 15, 2014 at 17:49
-
@gonvaled deleted my comment as it really didn't make sense - lack of coffee in blood. You're correct, this sample code does not assume format specifiers. I think, we can go out on a limb here and check for the format string specifiers, based on that produce different outputs.– JSmythFeb 15, 2014 at 20:12
-
Any way to handle newlines nicely? A multi-line message is displayed on multiple lines by chrome, but when in a string, it becomes one long line with the ↵ character in it. Mar 6, 2014 at 13:34
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.
-
There's also
console.timeStamp('foo')
it just appears as a yellow point in the timeline. It didn't work for me when using names with spaces tho.– Vitim.usNov 29, 2016 at 22:03 -
this does not answer the question related to
console.log
or the logging at all Jun 13, 2018 at 8:42 -
@AndreasDietrich why not? It does output to the console. More about it on this 2013 blogpost blog.mariusschulz.com/2013/11/22/… Aug 23, 2018 at 8:45
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"]
+new Date
and Date.now()
are alternate ways to get timestamps
-
Thanks, +1, but I was hoping that there might be some support for this without having to add code. Aug 17, 2012 at 18:40
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
-
To expand on this a little for those like me too lazy to go and look it up. The correct usage is: console.time("myMeasure"); [code you want to time] console.timeEnd("myMeasure");– SamihOct 1, 2014 at 9:16
-
this does not answer the question related to console.log or the logging at all Jun 13, 2018 at 8:43
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
-
1Please elaborate by making it clear to understand for all, what function will do what Apr 7, 2020 at 11:59
-
Update as of for Chrome 98:
Settings -> Preferences -> Console -> Show timestamps
From Chrome 68:
"Show timestamps" moved to settings
The Show timestamps checkbox previously in Console Settings Console Settings has moved to Settings.
-
3@tekiegirl's answer has a screenshot showing where to find the checkbox in the DevTools Settings are ; the screenshot in this answer doesn't show me where to find the "Show timestamps" checkbox. Apr 2, 2019 at 16:30
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
.
-
ׁThe
log
function created this way freezes a fixed timestamp; you'd have to re-run this every time you want an up-to-date time [= up to time Date ;-]. It is possible to make this a function but you'd have to use it likemklog()(...)
instead oflog()
. Oct 25, 2014 at 18:32
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); }
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 (e.g.
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'
-
a disadvantage though is that (e.g. in FF 56.0) it does not show the source location of the log statement, but the one from the
Utl.js
above. so enabling (on-demand commenting in/out) of theUtl.consoleWithTimestamps(...)
-override may make sense Jun 13, 2018 at 9:27
Chrome Version 89.0.4389.90 (19.03.2021)
- Press F12.
- Find and press gear wheel icon.
- Check
Show timestamps
.
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
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
-
This looks almost all good, except that if you
console.log(document, window)
, i.e. without the format string assumption, then you'd get smth. like2014-02-15T20:02:17.284Z > [object HTMLDocument] Window {…}
instead ofdocument
being represented as an expandable object tree.– JSmythFeb 15, 2014 at 20:07 -
-
@JSmyth: sure, that is why one of the requirements of my refinement is that the first argument is a format string. To make it flexible, probably a check of the first argument to be a string would be enough.– blueFastFeb 15, 2014 at 21:59