How do I disable console.log when I am not debugging?

JavascriptDebuggingLogging

Javascript Problem Overview


I have many console.log (or any other console calls) in my code and I would like to use them only when my app is in some kind of "debug mode".

I can't seem to use some kind of logger function and internally use console.log because then I wouldn't know what line fired it. Maybe only with a try/catch, but my logs are very general and I don't want try/catch in my code.

What would you recommend?

Javascript Solutions


Solution 1 - Javascript

I would probably abuse the short-circuiting nature of JavaScript's logical AND operator and replace instances of:

console.log("Foo.");

With:

DEBUG && console.log("Foo.");

Assuming DEBUG is a global variable that evaluates to true if debugging is enabled.

This strategy avoids neutering console.log(), so you can still call it in release mode if you really have to (e.g. to trace an issue that doesn't occur in debug mode).

Solution 2 - Javascript

Just replace the console.log with an empty function for production.

if (!DEBUG_MODE_ON) {
    console = console || {};
    console.log = function(){};
}

Solution 3 - Javascript

Clobbering global functions is generally a bad idea.

Instead, you could replace all instances of console.log in your code with LOG, and at the beginning of your code:

var LOG = debug ? console.log.bind(console) : function () {};

This will still show correct line numbers and also preserve the expected console.log function for third party stuff if needed.

Solution 4 - Javascript

Since 2014, I simply use GULP (and recommend everyone to, it's an amazing tool), and I have a package installed which is called stripDebug which does that for you.

(I also use uglify and closureCompiler in production)


Update (June 20, 2019)

There's a Babel Macro that automatically removes all console statements:

https://www.npmjs.com/package/dev-console.macro

Solution 5 - Javascript

One more way to disable console.log in production and keep it in development.

// overriding console.log in production
if(window.location.host.indexOf('localhost:9000') < 0) {
	console.log = function(){};
}

You can change your development settings like localhost and port.

Solution 6 - Javascript

This Tiny wrapper override will wrap the original console.log method with a function that has a check inside it, which you can control from the outside, deepening if you want to see console logs and not.

I chose window.allowConsole just as an example flag but in real-life use it would probably be something else. depending on your framework.

(function(cl){
  console.log = function(){
    if( window.allowConsole )
      cl(...arguments); 
  }
})(console.log)

#Usage:

// in development (allow logging)
window.allowConsole = true;
console.log(1,[1,2,3],{a:1});

// in production (disallow logging)
window.allowConsole = false;
console.log(1,[1,2,3],{a:1});

This override should be implement as "high" as possible in the code hierarchy so it would "catch" all logs before then happen. This could be expanded to all the other console methods such as warn, time, dir and so on.

Solution 7 - Javascript

Simple.

Add a little bash script that finds all references to console.log and deletes them.

Make sure that this batch script runs as part of your deployment to production.

Don't shim out console.log as an empty function, that's a waste of computation and space.

Solution 8 - Javascript

This code works for me:

if(console=='undefined' || !console || console==null) {
  var console = {
    log : function (string) {
        // nothing to do here!!
    }
  }
}

Solution 9 - Javascript

enter image description here

The newest versions of chrome show which line of code in which file fired console.log. If you are looking for a log management system, you can try out logeek it allows you to control which groups of logs you want to see.

Solution 10 - Javascript

// In Development:
var debugMode = true

// In Prod:
var debugMode = false

// This function logs console messages when debugMode is true .
function debugLog(logMessage) {
    if (debugMode) {
        console.log(logMessage);
    }
}

// Use the function instead of console.log
debugLog("This is a debug message");

Solution 11 - Javascript

console can out put not just log but errors warnings etc. Here is a function to override all console outputs

(function () {
    var method;
    var noop = function noop() { };
    var methods = [
    'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
    'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
    'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
    'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];
        console[method] = noop;
    }
}());

Refer to detailed post here https://stapp.space/disable-javascript-console-on-production/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvsyncView Question on Stackoverflow
Solution 1 - JavascriptFrédéric HamidiView Answer on Stackoverflow
Solution 2 - JavascriptbjorndView Answer on Stackoverflow
Solution 3 - JavascriptnamuolView Answer on Stackoverflow
Solution 4 - JavascriptvsyncView Answer on Stackoverflow
Solution 5 - JavascriptvineshView Answer on Stackoverflow
Solution 6 - JavascriptvsyncView Answer on Stackoverflow
Solution 7 - JavascriptRaynosView Answer on Stackoverflow
Solution 8 - JavascriptAttakinsky BlancoView Answer on Stackoverflow
Solution 9 - JavascriptIman MohamadiView Answer on Stackoverflow
Solution 10 - JavascriptdeepakssnView Answer on Stackoverflow
Solution 11 - JavascriptSachin NaikView Answer on Stackoverflow