是否有任何快速的方法让Chrome在console.log写入中输出时间戳(像Firefox那样)。或者是prepending new Date().getTime()是唯一的选项?
当前回答
如果您使用谷歌Chrome浏览器,您可以使用Chrome控制台api:
控制台。时间:在代码中你想要开始计时器的地方调用它 控制台。timeEnd:调用它来停止计时器
这两个调用之间的运行时间显示在控制台中。
有关详细信息,请参阅doc链接:https://developers.google.com/chrome-developer-tools/docs/console
其他回答
ES6解决方案:
const timestamp = () => `[${new Date().toUTCString()}]`
const log = (...args) => console.log(timestamp(), ...args)
其中timestamp()返回实际格式化的时间戳和日志添加一个时间戳,并将所有自己的参数传播到console.log
如果希望保留行号信息(每个消息都指向它的.log()调用,而不是所有消息都指向包装器),则必须使用.bind()。您可以通过console.log预先添加一个额外的时间戳参数。Bind (console, <timestamp>),但问题是你每次都需要重新运行这个函数来获得一个新的时间戳绑定。 一种尴尬的方法是返回一个绑定函数:
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());
}
然后必须与双重调用一起使用:
logf()(object, "message...")
但是,我们可以通过安装带有getter函数的属性来隐式地进行第一次调用:
var origLog = console.log;
// TODO: fallbacks if no `defineProperty`...
Object.defineProperty(console, "log", {
get: function () {
return Function.prototype.bind.call(origLog, console, yourTimeFormat());
}
});
现在您只需调用console.log(…),它就会自动添加一个时间戳!
> console.log(12)
71.919s 12 VM232:2
undefined
> console.log(12)
72.866s 12 VM233:2
undefined
你甚至可以通过Object.defineProperty(window, "log",…)来实现简单的log()而不是console.log()。
请参阅https://github.com/pimterry/loglevel,了解使用.bind()的安全控制台包装器,并提供兼容性回退。
参见https://github.com/eligrey/Xccessors获取从defineProperty()到遗留__defineGetter__ API的兼容性回调。 如果这两个属性API都不起作用,则应该退回到每次都获得一个新的时间戳的包装器函数。(在这种情况下,你会丢失行号信息,但时间戳仍然会显示。)
Boilerplate:我喜欢的时间格式:
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); }
Chrome版本89.0.4389.90 (19.03.2021)
按F12。 找到并按齿轮图标。 检查显示时间戳。
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
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 如何禁用谷歌翻译从HTML在Chrome
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?