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

How to quickly and conveniently disable all console.log statements in my code?(如何快速方便地禁用我的代码中的所有 console.log 语句?)
本文介绍了如何快速方便地禁用我的代码中的所有 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 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Google apps script get range of bytes from binary file(谷歌应用程序脚本从二进制文件中获取字节范围)
Sending Multiple attachments with Google Script from Google Drive(使用 Google 脚本从 Google Drive 发送多个附件)
Distributing Google Apps Scripts for Sheets in your company network(在您的公司网络中分发适用于表格的 Google Apps 脚本)
Upload file to my google drive from anyone using javascript(使用 javascript 将文件从任何人上传到我的谷歌驱动器)
quot;Shared Drivequot; support in Google Apps Script(“共享驱动器Google Apps 脚本中的支持)
Angular 2+ HTTP POST and GDrive API. Resumable file upload with name(Angular 2+ HTTP POST 和 GDrive API.带名称的可恢复文件上传)