Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 如何快速方便地禁用我的代码中的所有console.log语句?(How to quickly and conveniently disable all console.log statements in my code?)

有没有办法关闭我的JavaScript代码中的所有console.log语句,以进行测试?

  ask by Zack Burt translate from so

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

1 Reply

0 votes
by (71.8m points)

Redefine the console.log function in your script.(在脚本中重新定义console.log函数。)

console.log = function() {}

That's it, no more messages to console.(就是这样,没有更多的消息来控制台。)

EDIT:(编辑:)

Expanding on Cide's idea.(扩展了Cide的想法。)

A custom logger which you can use to toggle logging on/off from your code.(一个自定义记录器,可用于从代码中切换日志记录开/关。)

From my Firefox console:(从我的Firefox控制台:)

image

var logger = function()
{
    var oldConsoleLog = null;
    var pub = {};

    pub.enableLogger =  function enableLogger() 
                        {
                            if(oldConsoleLog == null)
                                return;

                            window['console']['log'] = oldConsoleLog;
                        };

    pub.disableLogger = function disableLogger()
                        {
                            oldConsoleLog = console.log;
                            window['console']['log'] = function() {};
                        };

    return pub;
}();

$(document).ready(
    function()
    {
        console.log('hello');

        logger.disableLogger();
        console.log('hi', 'hiya');
        console.log('this wont show up in console');

        logger.enableLogger();
        console.log('This will show up!');
    }
 );

How to use the above 'logger'?(如何使用上面的“记录器”?)

In your ready event, call logger.disableLogger so that console messages are not logged.(在ready事件中,调用logger.disableLogger以便不记录控制台消息。) Add calls to logger.enableLogger and logger.disableLogger inside the method for which you want to log messages to the console.(在要将消息记录到控制台的方法中添加对logger.enableLogger和logger.disableLogger的调用。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...