13 ответов:
в Chrome есть опция настройки консоли (инструменты разработчика -> консоль -> настройки [верхний правый угол] ) с именем "показать временные метки", что именно то, что мне нужно.
Я только что нашел его. Никакие другие грязные хаки не нужны, которые уничтожают заполнители и стирают место в коде, из которого были зарегистрированы сообщения.
попробуйте это:
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); } } };
выходы с этого:
С. П.: Проверял только в Хроме.
П. П. С.:
Array.prototype.sliceздесь не идеально, потому что он будет регистрироваться как массив объектов, а не серия объектов.
вы можете использовать Dev tools profiler.
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Эд тоже, но я не знаю, если изменения, как это хорошая идея будет иметь другие побочные эффекты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"]
попробуй это:
this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );эта функция ставит метку времени, имя файла и номер строки, как же встроенный
console.log.
это добавляет функцию "log" в локальную область (используя
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);выводит что-то вроде этого:
[пн, 11 марта 2013 16:47:49 GMT] Object {test: "log"} monkey 42
если вы хотите сохранить информацию о номере строки (каждое сообщение указывает на его.log () вызов, не все указывая на нашу обертку), вы должны использовать
.bind(). Вы можете добавить дополнительный аргумент 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...")но мы можем сделать первый вызов неявным, установив свойства С функцией геттер:
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вы даже можете достичь этого магического поведения с помощью простого
log()вместоconsole.log()делатьObject.defineProperty(window, "log", ...).
см.https://github.com/pimterry/loglevel для хорошо сделанной безопасной оболочки консоли используя
.bind(), с резервными копиями совместимости.см.https://github.com/eligrey/Xccessors для резервов совместимости от
defineProperty()наследие__defineGetter__API. Если ни один из 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); }
продлил очень приятно решение "С строки формата" от JSmyth к тому же поддержка
- все остальные
console.logвариации (log,debug,info,warn,error)- в том числе временная метка строка гибкость param (например,
09:05:11.518и2018-06-13T09:05:11.518Z)- в том числе запасной вариант в случае
consoleили его функции не существуют in браузеры.
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.*$/, '' ) } ) // e.g. '09:05:11.518'
Из 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
У меня это в большинстве узлов.JS apps. Он также работает в браузере.
function log() { const now = new Date(); const currentDate = `[${now.toISOString()}]: `; const args = Array.from(arguments); args.unshift(currentDate); console.log.apply(console, args); }


Comments