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

后端 未结 28 2632
深忆病人
深忆病人 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:20

    I have used winston logger earlier.

    Nowadays I am using below simpler code from experience:

    1. Set the environment variable from cmd/ command line (on Windows):

      cmd
      setx LOG_LEVEL info
      

    Or, you could have a variable in your code if you like, but above is better.

    1. Restart cmd/ command line, or, IDE/ editor like Netbeans

    2. Have below like code:

      console.debug = console.log;   // define debug function
      console.silly = console.log;   // define silly function
      
      switch (process.env.LOG_LEVEL) {
          case 'debug':
          case 'silly':
              // print everything
              break;
      
          case 'dir':
          case 'log':
              console.debug = function () {};
              console.silly = function () {};
              break;
      
          case 'info':
              console.debug = function () {};
              console.silly = function () {};
              console.dir = function () {};
              console.log = function () {};
              break;
      
          case 'trace':   // similar to error, both may print stack trace/ frames
          case 'warn':    // since warn() function is an alias for error()
          case 'error':
              console.debug = function () {};
              console.silly = function () {};
              console.dir = function () {};
              console.log = function () {};
              console.info = function () {};
              break;
      }
      
    3. Now use all console.* as below:

      console.error(' this is a error message '); // will print
      console.warn(' this is a warn message '); // will print
      console.trace(' this is a trace message '); // will print
      console.info(' this is a info message '); // will print, LOG_LEVEL is set to this
      
      console.log(' this is a log message '); // will NOT print
      console.dir(' this is a dir message '); // will NOT print
      console.silly(' this is a silly message '); // will NOT print
      console.debug(' this is a debug message '); // will NOT print
      

    Now, based on your LOG_LEVEL settings made in the point 1 (like, setx LOG_LEVEL log and restart command line), some of the above will print, others won't print

    Hope that helped.

提交回复
热议问题