[英]console.log timestamps in Chrome?
有沒有什么快速的方法可以讓 Chrome 在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);
}
}
};
輸出:
PS:僅在 Chrome 中測試。
PPS: Array.prototype.slice
在這里並不完美,因為它會被記錄為一個對象數組而不是一系列對象。
您可以使用開發工具分析器。
console.time('Timer name');
//do critical time stuff
console.timeEnd('Timer name');
“定時器名稱”必須相同。 您可以使用多個具有不同名稱的計時器實例。
我轉換arguments
使用數組Array.prototype.slice
,這樣我可以concat
有什么,我想添加另一個數組,然后將它傳遞到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"]
似乎arguments
也可以是Array.prototype.unshift
ed,但我不知道像這樣修改它是否是一個好主意/會產生其他副作用
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"]
如果您使用的是 Google Chrome 瀏覽器,則可以使用 chrome 控制台 api:
這兩次調用之間經過的時間顯示在控制台中。
有關詳細信息,請參閱文檔鏈接: https : //developers.google.com/chrome-developer-tools/docs/console
+new Date
和Date.now()
是獲取時間戳的替代方法
也試試這個:
this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );
此函數將時間戳、文件名和行號與內置的console.log
相同。
ES6解決方案:
const timestamp = () => `[${new Date().toUTCString()}]`
const log = (...args) => console.log(timestamp(), ...args)
其中timestamp()
返回實際格式化的時間戳和log
添加一個時間戳並將所有自己的參數傳播到console.log
如果你想保留行號信息(每條消息都指向它的 .log() 調用,而不是全部指向我們的包裝器),你必須使用.bind()
。 您可以通過console.log.bind(console, <timestamp>)
在前面添加一個額外的時間戳參數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()
並具有兼容性回退的完善的安全控制台包裝器。
有關從defineProperty()
到舊版__defineGetter__
API 的兼容性回退,請參閱https://github.com/eligrey/Xcccessors 。 如果這兩個屬性 API 都不起作用,您應該回退到每次都獲得新時間戳的包裝函數。 (在這種情況下,您會丟失行號信息,但仍會顯示時間戳。)
樣板:按我喜歡的方式格式化時間:
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); }
這會使用任意數量的參數將“日志”函數添加到本地范圍(使用this
):
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);
}
所以你可以使用它:
this.log({test: 'log'}, 'monkey', 42);
輸出如下:
[格林威治標准時間 2013 年 3 月 11 日星期一 16:47:49] 對象 {test: "log"} 猴子 42
我在大多數 Node.JS 應用程序中都有這個。 它也適用於瀏覽器。
function log() {
const now = new Date();
const currentDate = `[${now.toISOString()}]: `;
const args = Array.from(arguments);
args.unshift(currentDate);
console.log.apply(console, args);
}
擴展了來自 JSmyth的非常好的解決方案“帶格式字符串” ,以支持
console.log
變體( log
、 debug
、 info
、 warn
、 error
)09:05:11.518
與09:05:11.518
2018-06-13T09:05:11.518Z
)console
或其功能的情況下的回退.
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'
Chrome 版本 89.0.4389.90 (19.03.2021)
Show timestamps
。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
第一個參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.