如何重写console.log()并在输出的开头添加一个单词?

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

本文关键字:开头 添加 一个 单词 重写 何重写 console log 输出      更新时间:2023-09-26

我有功能日志打印数据随着传递的参数,我怎么能打印内容&同时要打印"报告"字样。日志开头

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

我想拥有:报告:此日志出现错误…

谢谢。

您可以轻松地覆盖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')

演示:小提琴