是否有任何快速的方法让Chrome在console.log写入中输出时间戳(像Firefox那样)。或者是prepending 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在这里并不完美,因为它将被记录为对象的数组,而不是对象的一系列。
其他回答
Chrome 98的更新如下:
设置—>首选项—>控制台—>显示时间戳
Chrome 68:
“显示时间戳”移至设置
以前在“控制台设置”中的“显示时间戳”复选框已移动到“设置”。
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);
}
};
这样的:
显示以毫秒为单位的时间戳 假设一个格式字符串作为.log的第一个参数
如果您使用谷歌Chrome浏览器,您可以使用Chrome控制台api:
控制台。时间:在代码中你想要开始计时器的地方调用它 控制台。timeEnd:调用它来停止计时器
这两个调用之间的运行时间显示在控制台中。
有关详细信息,请参阅doc链接:https://developers.google.com/chrome-developer-tools/docs/console
+new Date和Date.now()是获取时间戳的替代方法
也试试这个:
this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );
该函数将时间戳、文件名和行号与内置console.log相同。
推荐文章
- 转换php数组到Javascript
- 如何跳转到浏览器页面的顶部
- 在电子邮件消息中是否支持JavaScript ?
- 如何在JavaScript中指定Math.log()的基?
- 多重左赋值JavaScript
- 如何在单个测试基础上更改模拟实现?
- VueJS有条件地为元素添加属性
- Uncaught TypeError:(中间值)(…)不是一个函数
- 如何设置URL查询参数在Vue与Vue路由器
- 了解Chrome网络日志“停滞”状态
- 无法读取属性“addEventListener”为空
- 如何防止moment.js从webpack加载地区?
- getMonth在javascript中给出前一个月
- 如何在禁用按钮上启用引导工具提示?
- Node.js全局变量