如何覆盖console.log()并在输出的开头附加一个单词?

Uui*_*uid 20 javascript jquery

我具备的功能日志与传递的参数,我怎么能打印的内容和在同一时间总是打印的字一起打印数据"报告:"在日志的beggining.

function Log(){
    if (app.debug_logs){
        if(console && console.log){
            console.log.apply(console, "Report: " + arguments);
        }
    }
}

Log(" error ocurred ", " on this log... ");
Run Code Online (Sandbox Code Playgroud)

我希望:"报告:此日志出现错误......"

谢谢.

Aru*_*hny 48

您可以console.log轻松覆盖

(function(){
    if(window.console && console.log){
        var old = console.log;
        console.log = function(){
            Array.prototype.unshift.call(arguments, 'Report: ');
            old.apply(this, arguments)
        }
    }  
})();

console.log('test')
Run Code Online (Sandbox Code Playgroud)

演示:小提琴

  • @FabrícioMatté,因为它是如此,你可以做你想做的事 (5认同)
  • 这会丢失原始行,因此所有日志都会出现在同一行中 (4认同)
  • 好吧,我知道SO的匿名投票系统,虽然匿名低估一个完全有效的答案根本就没有建设性. (3认同)
  • 如何更简单的`console.log = function(){old.apply(this,['Report:'].concat(arguments))}`? (2认同)