Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

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

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 beginning of the log.

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

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

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

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can override the console.log easily

(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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...