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

51,395

Solution 1

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 2

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 3

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

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

Solution 4

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 5

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.

Share:
51,395
vsync
Author by

vsync

Client-side web developer (since 2005) 👍 javascript 👍 html 👍 css 👍 web design http://codepen.io/vsync/ https://github.com/yairEO?tab=repositories http://www.sudokubum.com/

Updated on July 09, 2022

Comments

  • vsync
    vsync almost 2 years

    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?