console.log
输出中输出时间戳(像Firefox那样)?还是只能在前面添加
new Date().getTime()
?console.log
输出中输出时间戳(像Firefox那样)?new Date().getTime()
?试试这个:
console.logCopy = console.log.bind(console);
console.log = function(data)
{
var currentDate = '[' + new Date().toUTCString() + '] ';
this.logCopy(currentDate, data);
};
或者,如果您想要一个时间戳:
console.logCopy = console.log.bind(console);
console.log = function(data)
{
var timestamp = '[' + Date.now() + '] ';
this.logCopy(timestamp, data);
};
如果想要记录多个事物,并以一种美观的方式(例如对象树形式)呈现:
console.logCopy = console.log.bind(console);
console.log = function()
{
if (arguments.length)
{
var timestamp = '[' + Date.now() + '] ';
this.logCopy(timestamp, arguments);
}
};
使用格式字符串 (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);
}
}
};
输出结果如下:
附言:仅在Chrome中测试过。
另外一点:这里不适合使用Array.prototype.slice
,因为它会被记录为对象数组而不是一系列的对象。
你可以使用开发者工具分析器。
console.time('Timer name');
//do critical time stuff
console.timeEnd('Timer name');
计时器名称必须相同。 您可以使用具有不同名称的多个计时器实例。
console.timeStamp('foo')
,它只会在时间轴上显示为黄色点。但是,如果名称中包含空格,则对我无效。 - Vitim.usconsole.log
或日志记录相关的问题。 - Andreas CovidiotES6 解决方案:
const timestamp = () => `[${new Date().toUTCString()}]`
const log = (...args) => console.log(timestamp(), ...args)
timestamp()
返回实际格式化的时间戳,log
会添加时间戳并将所有参数传递给console.log
我使用Array.prototype.slice
将 arguments
转换为数组,以便我可以使用concat
添加另一个数组的内容,然后将其传递到console.log.apply(console, /*此处*/)
中;
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"]
看起来 arguments
也可以通过 Array.prototype.unshift
来修改,但我不确定这样修改是否是一个好主意/是否会有其他副作用。
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
和 Date.now()
是获取时间戳的两种替代方法。
也可以尝试这个:
this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );
这个函数会将时间戳、文件名和行号放在内置的console.log
中相同的位置。
按下 F12。
找到并点击齿轮图标。
勾选 显示时间戳。