如何快速方便地禁用我的代码中的所有 console.log 语句?

2022-01-11 00:00:00 debugging console javascript

有什么方法可以关闭我的 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.

相关文章