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

查看:214
本文介绍了如何快速方便地禁用我的代码中的所有console.log语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法关闭我的JavaScript代码中的所有 console.log 语句,用于测试目的?

Is there any way to turn off all console.log statements in my JavaScript code, for testing purposes?

推荐答案

在脚本中重新定义console.log函数。

Redefine the console.log function in your script.

console.log = function() {}

就是这样,没有更多的信息到控制台。

That's it, no more messages to console.

编辑:

扩展Cide的想法。一个自定义记录器,可用于从代码中切换日志记录。

Expanding on Cide's idea. A custom logger which you can use to toggle logging on/off from your code.

工作演示→

从我的Firefox控制台:

From my Firefox console:

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!');
    }
 );

如何使用上述记录器?在准备好的事件中,调用logger.disableLogger,以便不记录控制台消息。在要将消息记录到控制台的方法中添加对logger.enableLogger和logger.disableLogger的调用。

How to use the above 'logger'? In your ready event, call logger.disableLogger so that console messages are not logged. Add calls to logger.enableLogger and logger.disableLogger inside the method for which you want to log messages to the console.

这篇关于如何快速方便地禁用我的代码中的所有console.log语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆