2012-02-14 20 views
24

是否可以擴展控制檯對象?我可以在javascript中擴展控制檯對象(用於重新路由日誌記錄)嗎?

我想是這樣的:

Console.prototype.log = function(msg){ 
    Console.prototype.log.call(msg); 
    alert(msg); 
} 

但這並沒有工作。 我想通過像log4javascript這樣的框架向控制檯對象添加額外的日誌記錄,並且仍然在我的代碼中使用標準控制檯對象(在log4javascript不可用的情況下)。

在此先感謝!

+2

爲什麼要擴展原型對象而不是擴展'Console'對象本身?你有沒有打電話給'新的控制檯()'? – biziclop 2012-02-14 13:43:17

回答

35

嘗試以下操作:

(function() { 
    var exLog = console.log; 
    console.log = function(msg) { 
     exLog.apply(this, arguments); 
     alert(msg); 
    } 
})() 
2

您還可以添加登錄時間這種方式:

添加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); 
}; 
0
// 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'); 

我注意到,nitesh上述使用Array.prototype.unshift.call的是一種更好的方式來添加「詳細:」標籤。

相關問題