【问题标题】:how can I override console.log() and prepend a word at the beginning of the output?如何覆盖 console.log() 并在输出的开头添加一个单词?
【发布时间】:2013-04-28 04:47:38
【问题描述】:

我有函数 Log 可以打印数据和传递的参数,我如何打印内容,同时总是在日志开头打印单词“Report:”。

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

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

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

谢谢。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

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

    演示:Fiddle

    【讨论】:

    • @FabrícioMatté 因为它是如此,你可以做任何你想做的事
    • 好吧,我知道 SO 的匿名投票系统,尽管匿名投票完全有效的答案根本没有建设性。
    • @FabrícioMatté 可能是因为我偏离了原始问题,问题是关于 Log 方法而不是修复它我建议覆盖 console.log。还不知道是不是越野
    • 更简单的console.log = function () { old.apply(this, ['Report: '].concat(arguments)) } 怎么样?
    • 这丢失了原始行,因此所有日志都将出现在同一行
    猜你喜欢
    • 2018-02-02
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多