How to quickly and conveniently disable all console.log statements in my code?

后端 未结 28 2204
深忆病人
深忆病人 2020-11-22 16:48

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

相关标签:
28条回答
  • 2020-11-22 17:37

    After I searched for this issue aswell and tried it within my cordova app, I just want to warn every developer for windows phone to not overwrite

        console.log
    

    because the app will crash on startup.

    It won't crash if you're developing local if you're lucky, but submitting in store it will result in crashing the app.

    Just overwrite

        window.console.log 
    

    if you need to.

    This works in my app:

       try {
            if (typeof(window.console) != "undefined") {
                window.console = {};
                window.console.log = function () {
                };
                window.console.info = function () {
                };
                window.console.warn = function () {
                };
                window.console.error = function () {
                };
            }
    
            if (typeof(alert) !== "undefined") {
                alert = function ()
                {
    
                }
            }
    
        } catch (ex) {
    
        }
    
    0 讨论(0)
  • 2020-11-22 17:38

    Redefine the console.log function in your script.

    console.log = function() {}
    

    That's it, no more messages to console.

    EDIT:

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

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

    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.

    0 讨论(0)
  • 2020-11-22 17:38

    I wrote a ES2015 solution ( use only with Webpack ).

    class logger {
      static isEnabled = true;
    
      static enable () {
        if(this.constructor.isEnabled === true){ return; }
    
        this.constructor.isEnabled = true;
      }
    
      static disable () {
        if(this.constructor.isEnabled === false){ return; }
    
        this.constructor.isEnabled = false;
      }
    
      static log () {
        if(this.constructor.isEnabled === false ) { return; }
    
        const copy = [].slice.call(arguments);
    
        window['console']['log'].apply(this, copy);
      }
    
      static warn () {
        if(this.constructor.isEnabled === false ) { return; }
    
        const copy = [].slice.call(arguments);
    
        window['console']['warn'].apply(this, copy);
      }
    
      static error () {
        if(this.constructor.isEnabled === false ) { return; }
    
        const copy = [].slice.call(arguments);
    
        window['console']['error'].apply(this, copy);
      }
    }
    

    Description:

    1. Along with logger.enable and logger.disable you can use console.['log','warn','error'] methods as well using logger class.
    2. By using logger class for displaying, enabling or disabling messages makes the code much cleaner and maintainable.
    3. The code below shows you how to use the logger class:
      • logger.disable() - disable all console messages
      • logger.enable() - enable all console messages
      • logger.log('message1', 'message2') - works exactly like console.log.
      • logger.warn('message1', 'message2') - works exactly like console.warn.
      • logger.error('message1', 'message2') - works exactly like console.error. Happy coding..
    0 讨论(0)
  • 2020-11-22 17:39

    I am surprised that of all those answers no one combines:

    • No jquery
    • Anonymous function to not pollute global namespace
    • Handle case where window.console not defined
    • Just modify the .log function of the console

    I'd go for this:

    (function () {
    
        var debug = false
    
        if (debug === false) {
            if ( typeof(window.console) === 'undefined') { window.console = {}; }
            window.console.log = function () {};
        }
    })()
    
    0 讨论(0)
  • 2020-11-22 17:39

    If you use Grunt you can add a task in order to remove/comment the console.log statements. Therefore the console.log are no longer called.

    https://www.npmjs.org/package/grunt-remove-logging-calls

    0 讨论(0)
  • 2020-11-22 17:41

    The following is more thorough:

    var DEBUG = false;
    if(!DEBUG){
        if(!window.console) window.console = {};
        var methods = ["log", "debug", "warn", "info"];
        for(var i=0;i<methods.length;i++){
            console[methods[i]] = function(){};
        }
    }
    

    This will zero out the common methods in the console if it exists, and they can be called without error and virtually no performance overhead. In the case of a browser like IE6 with no console, the dummy methods will be created to prevent errors. Of course there are many more functions in Firebug, like trace, profile, time, etc. They can be added to the list if you use them in your code.

    You can also check if the debugger has those special methods or not (ie, IE) and zero out the ones it does not support:

    if(window.console && !console.dir){
    var methods = ["dir", "dirxml", "trace", "profile"]; //etc etc
        for(var i=0;i<methods.length;i++){
            console[methods[i]] = function(){};
        }
    }
    
    0 讨论(0)
提交回复
热议问题