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



Question:

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


Solution:1

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.


Solution:2

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(){};      }  }  


Solution:3

As far as I can tell from the documentation, Firebug doesn't supply any variable to toggle debug state. Instead, wrap console.log() in a wrapper that conditionally calls it, i.e.:

DEBUG = true; // set to false to disable debugging  function debug_log() {      if ( DEBUG ) {          console.log.apply(this, arguments);      }  }  

To not have to change all the existing calls, you can use this instead:

DEBUG = true; // set to false to disable debugging  old_console_log = console.log;  console.log = function() {      if ( DEBUG ) {          old_console_log.apply(this, arguments);      }  }  


Solution:4

I know you asked how to disable console.log, but this might be what you're really after. This way you don't have to explicitly enable or disable the console. It simply prevents those pesky console errors for people who don't have it open or installed.

if(typeof(console) === 'undefined') {      var console = {};      console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};  }  


Solution:5

I realize this is an old post but it still pops up at the top of Google results, so here is a more elegant non-jQuery solution that works in the latest Chrome, FF, and IE.

(function (original) {      console.enableLogging = function () {          console.log = original;      };      console.disableLogging = function () {          console.log = function () {};      };  })(console.log);  


Solution:6

You should not!

It is not a good practice to overwrite built-in functions. There is also no guarantee that you will suppress all output, other libraries you use may revert your changes and there are other functions that may write to the console; .dir(), .warning(), .error(), .debug(), .assert() etc.

As some suggested, you could define a DEBUG_MODE variable and log conditionally. Depending on the complexity and nature of your code, it may be a good idea to write your own logger object/function that wraps around the console object and has this capability built-in. That would be the right place to do deal with instrumentation.

That said, for 'testing' purposes you can write tests instead of printing to the console. If you are not doing any testing, and those console.log() lines were just an aid to write your code, simply delete them.


Solution:7

Just change the flag DEBUG to override the console.log function. This should do the trick.

var DEBUG = false;  // ENABLE/DISABLE Console Logs  if(!DEBUG){    console.log = function() {}  }  


Solution:8

If you're using IE7, console won't be defined. So a more IE friendly version would be:

if (typeof console == "undefined" || typeof console.log == "undefined")   {     var console = { log: function() {} };   }  


Solution:9

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 () {};      }  })()  


Solution:10

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) {        }  


Solution:11

This a hybrid of answers from SolutionYogi and Chris S. It maintains the console.log line numbers and file name. Example jsFiddle.

// Avoid global functions via a self calling anonymous one (uses jQuery)  (function(MYAPP, $, undefined) {      // Prevent errors in browsers without console.log      if (!window.console) window.console = {};      if (!window.console.log) window.console.log = function(){};        //Private var      var console_log = console.log;          //Public methods      MYAPP.enableLog = function enableLogger() { console.log = console_log; };         MYAPP.disableLog = function disableLogger() { console.log = function() {}; };    }(window.MYAPP = window.MYAPP || {}, jQuery));      // Example Usage:  $(function() {          MYAPP.disableLog();          console.log('this should not show');        MYAPP.enableLog();      console.log('This will show');  });  


Solution:12

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


Solution:13

Warning: Shameless plug!

You could also use something like my JsTrace object to have modular tracing with module-level "switching" capability to only turn on what you want to see at the time.

http://jstrace.codeplex.com

(Also has a NuGet package, for those who care)

All levels default to "error", though you can shut them "off". Though, I can't think of why you would NOT want to see errors

You can change them like this:

Trace.traceLevel('ModuleName1', Trace.Levels.log);  Trace.traceLevel('ModuleName2', Trace.Levels.info);  

Fore more docs, check out the Documentation

T


Solution:14

I found a little more advanced piece of code in this url JavaScript Tip: Bust and Disable console.log:

var DEBUG_MODE = true; // Set this value to false for production    if(typeof(console) === 'undefined') {     console = {}  }    if(!DEBUG_MODE || typeof(console.log) === 'undefined') {     // FYI: Firebug might get cranky...     console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time =    console.timeEnd = console.assert = console.profile = function() {};  }  


Solution:15

I developed a library for this usecase: https://github.com/sunnykgupta/jsLogger

Features:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.

Is open for modifications and will be updated whenever new suggestions come up.


Solution:16

Ive been using the following to deal with he problem:-

var debug = 1;  var logger = function(a,b){ if ( debug == 1 ) console.log(a, b || "");};  

Set debug to 1 to enable debugging. Then use the logger function when outputting debug text. It's also set up to accept two parameters.

So, instead of

console.log("my","log");  

use

logger("my","log");  


Solution:17

I wrote this:

//Make a copy of the old console.  var oldConsole = Object.assign({}, console);    //This function redefine the caller with the original one. (well, at least i expect this to work in chrome, not tested in others)  function setEnabled(bool) {      if (bool) {          //Rewrites the disable function with the original one.          console[this.name] = oldConsole[this.name];          //Make sure the setEnable will be callable from original one.          console[this.name].setEnabled = setEnabled;      } else {          //Rewrites the original.          var fn = function () {/*function disabled, to enable call console.fn.setEnabled(true)*/};          //Defines the name, to remember.          Object.defineProperty(fn, "name", {value: this.name});          //replace the original with the empty one.          console[this.name] = fn;          //set the enable function          console[this.name].setEnabled = setEnabled        }  }  

Unfortunately it doesn't work on use strict mode.

So using console.fn.setEnabled = setEnabled and then console.fn.setEnabled(false) where fn could be almost any console function. For your case would be:

console.log.setEnabled = setEnabled;  console.log.setEnabled(false);  

I wrote this too:

var FLAGS = {};      FLAGS.DEBUG = true;      FLAGS.INFO = false;      FLAGS.LOG = false;      //Adding dir, table, or other would put the setEnabled on the respective console functions.    function makeThemSwitchable(opt) {      var keysArr = Object.keys(opt);      //its better use this type of for.      for (var x = 0; x < keysArr.length; x++) {          var key = keysArr[x];          var lowerKey = key.toLowerCase();          //Only if the key exists          if (console[lowerKey]) {              //define the function              console[lowerKey].setEnabled = setEnabled;              //Make it enabled/disabled by key.              console[lowerKey].setEnabled(opt[key]);          }      }  }  //Put the set enabled function on the original console using the defined flags and set them.  makeThemSwitchable(FLAGS);  

so then you just need to put in the FLAGS the default value (before execute the above code), like FLAGS.LOG = false and the log function would be disabled by default, and still you could enabled it calling console.log.setEnabled(true)


Solution:18

I have used winston logger earlier.

Nowadays I am using below simpler code from experience:

  1. Set the environment variable (example, on Windows):

    setx LOG_LEVEL info  

Of course, this could be a variable in your code if you like.

  1. Restart 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, some of the above will print, others won't print


Solution:19

My comprehensive solution to disable/override all console.* functions is here.

Of course, please make sure you are including it after checking necessary context. For example, only including in production release, it's not bombing any other crucial components etc.

Quoting it here:

"use strict";  (() => {    var console = (window.console = window.console || {});    [      "assert", "clear", "count", "debug", "dir", "dirxml",      "error", "exception", "group", "groupCollapsed", "groupEnd",      "info", "log", "markTimeline", "profile", "profileEnd", "table",      "time", "timeEnd", "timeStamp", "trace", "warn"    ].forEach(method => {      console[method] = () => {};    });    console.log("This message shouldn't be visible in console log");  })();


Solution:20

If you're using gulp, then you can use this plugin:

Install this plugin with the command:

npm install gulp-remove-logging

Next, add this line to your gulpfile:

var gulp_remove_logging = require("gulp-remove-logging");

Lastly, add the configuration settings (see below) to your gulpfile.

Task Configuration

gulp.task("remove_logging", function() {       return gulp.src("src/javascripts/**/*.js")      .pipe(        gulp_remove_logging()      )      .pipe(        gulp.dest(          "build/javascripts/"        )      ); });  


Solution:21

You could use javascript AOP (e.g. jquery-aop) to intercept all calls to console.debug/log (around) and do not proceed with the actual invocation if some global variable is set to false.

You could even do an ajax call (now and then) so you can change the log enabled/disabled behavior on the server which can be very interesting to enable debugging when facing an issue in a staging environment or such.


Solution:22

You can use logeek, It allows you to control your log messages visibility. Here is how you do that:

<script src="bower_components/dist/logeek.js"></script>    logeek.show('security');    logeek('some message').at('copy');       //this won't be logged  logeek('other message').at('secturity'); //this would be logged  

You can also logeek.show('nothing') to totally disable every log message.


Solution:23

This should override all methods of window.console. You can put it on the very top of your scripts section, and if you are on a PHP framework you can only print this code when your app environment is production, or if some kind of debug flag is disabled. Then you would have all your logs in your code working on development environments or in debug mode.

window.console = (function(originalConsole){      var api = {};      var props = Object.keys(originalConsole);      for (var i=0; i<props.length; i++) {          api[props[i]] = function(){};      }      return api;  })(window.console);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »