Ответ 1
Попробуйте следующее:
(function() {
var exLog = console.log;
console.log = function(msg) {
exLog.apply(this, arguments);
alert(msg);
}
})()
Можно ли расширить объект консоли?
Я пробовал что-то вроде:
Console.prototype.log = function(msg){
Console.prototype.log.call(msg);
alert(msg);
}
Но это не сработало. Я хочу добавить дополнительную запись в консольный объект через фреймворк, например log4javascript и по-прежнему использовать стандартный консольный объект (в тех случаях, когда log4javascript не является доступно) в моем коде.
Спасибо заранее!
Попробуйте следующее:
(function() {
var exLog = console.log;
console.log = function(msg) {
exLog.apply(this, arguments);
alert(msg);
}
})()
Используйте шаблон прокси, см. мой ответ для аналогичного случая:
JavaScript: переопределение предупреждения()
Надеюсь, что это поможет
Вы также можете добавить время журнала таким образом:
добавлен Momentjs или используйте Новая дата() вместо момента.
var oldConsole = console.log;
console.log = function(){
var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";
Array.prototype.unshift.call(arguments, timestamp);
oldConsole.apply(this, arguments);
};
// console aliases and verbose logger - console doesnt prototype
var c = console;
c.l = c.log,
c.e = c.error,
c.v = c.verbose = function() {
if (!myclass || !myclass.verbose) // verbose switch
return;
var args = Array.prototype.slice.call(arguments); // toArray
args.unshift('Verbose:');
c.l.apply(this, args); // log
};
// you can then do
var myclass = new myClass();
myclass.prototype.verbose = false;
// generally these calls would be inside your class
c.v('1 This will NOT log as verbose == false');
c.l('2 This will log');
myclass.verbose = true;
c.v('3 This will log');
Я заметил, что вышеупомянутое использование Array.prototype.unshift.call by nitesh - лучший способ добавить тег "Verbose:".
Это действительно то же самое, что некоторые другие дали, но я считаю, что это самый элегантный и наименее хакерский способ добиться этого. Синтаксис распространения (... args) гарантирует, что ни один аргумент не будет потерян.
var _console={...console}
console.log = function(...args) {
var msg = {...args}[0];
//YOUR_CODE
_console.log(...args);
}