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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16259711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:56:52  来源:igfitidea点击:

how can I override console.log() and append a word at the beginning of the output?

javascriptjquery

提问by Uuid

I have the function Log which prints data along with passed arguments, how can I print the content & at the same time always print the word "Report: " at the beggining of the log.

我有函数 Log 打印数据和传递的参数,我如何打印内容&同时总是在日志的开头打印“报告:”这个词。

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

Log(" error ocurred ", " on this log... ");

I want to have: "Report: error ocurred on this log..."

我想要:“报告:此日志上发生错误......”

Thanks.

谢谢。

回答by Arun P Johny

You can override the console.logeasily

您可以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')

Demo: Fiddle

演示:小提琴