By Zack Burt

2009-07-31 23:50:31 8 Comments

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


@Jaskaran Singh 2019-12-28 17:31:19

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 = [];

    window['console']['log'].apply(this, copy);

  static warn () {
    if(this.constructor.isEnabled === false ) { return; }

    const copy = [];

    window['console']['warn'].apply(this, copy);

  static error () {
    if(this.constructor.isEnabled === false ) { return; }

    const copy = [];

    window['console']['error'].apply(this, copy);


  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..

@Sunny_Sid 2019-09-20 10:20:55

After doing some research and development for this problem, I came across this solution which will hide warnings/Errors/Logs as per your choice.

    (function () {
    var origOpen =; = function () {        
        console.warn = function () { };
        window['console']['warn'] = function () { };
        this.addEventListener('load', function () {                        
            console.warn('Something bad happened.');
            window['console']['warn'] = function () { };

Add this code before JQuery plugin (e.g /../jquery.min.js) even as this is JavaScript code that does not require JQuery. Because some warnings are in JQuery itself.


@7ynk3r 2019-08-01 22:50:40

A simplification of

switch (process.env.LOG_LEVEL) {
  case 'ERROR':
    console.warn = function() {};
  case 'WARN': = function() {};
  case 'INFO':
    console.log = function() {};
  case 'LOG':
    console.debug = function() {};
    console.dir = function() {};

@Manohar Reddy Poreddy 2017-09-13 05:51:51

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):

    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
        case 'dir':
        case 'log':
            console.debug = function () {};
            console.silly = function () {};
        case 'info':
            console.debug = function () {};
            console.silly = function () {};
            console.dir = function () {};
            console.log = function () {};
        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 () {};
   = function () {};
  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' 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.

@Andrew Nessin 2018-08-18 07:23:30

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")
    ); });

@kmonsoor 2018-05-29 16:52:41

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");

@SolutionYogi 2009-07-31 23:54:40

Redefine the console.log function in your script.

console.log = function() {}

That's it, no more messages to console.


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)

                            window['console']['log'] = oldConsoleLog;

    pub.disableLogger = function disableLogger()
                            oldConsoleLog = console.log;
                            window['console']['log'] = function() {};

    return pub;


        console.log('hi', 'hiya');
        console.log('this wont show up in console');

        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.

@SolutionYogi 2009-08-01 00:58:19

Please provide detail as to what doesn't work? Does the above line give you an error? If yes, what's the error message?

@Eugene Lazutkin 2009-08-01 01:56:01

Works for me in IE8. ;-)

@SolutionYogi 2009-08-01 02:48:49

The code overwrites and restores console.log function. If IE7 supports console.log method, it should work.

@DA. 2009-10-28 16:29:08

console.log = function() {} does not seem to work in Firefox. You still get a 'console is not defined' error.

@OZZIE 2013-05-31 09:26:23

Firefox 20.0.1 logs everything even when it's supposed to be disabled in your code

@Dementic 2017-01-16 13:06:44

What a horrible solution. Modifying console.log... Why not just a have a boolean and a conditional function for logging?

@pmiranda 2017-03-31 14:27:10

var console = {}; first

@nu everest 2017-06-01 23:43:33

Prefer oldConsoleLog === null

@yeaske 2017-11-06 22:59:19

Don't forget to implement for console.error,, console.warn etc.

@TheCleverIdiot 2018-03-29 05:55:22

to disable all functions of console, I simply did this... for (i in console) { console[i] = function () { }; }

@user3326078 2019-01-10 06:06:51

@Bojidar Stanchev 2019-01-16 10:25:19

Why is the worst hackfix ever the top comment here?

@Kapil Raghuwanshi 2019-07-05 20:30:49

With ES6 arrow functions, just write - console.log = () => { };

@Michae Pavlos Michael 2017-05-08 15:42:15

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




@agm-dev 2017-04-25 22:11:01

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;

@Gabriel De Oliveira Rohden 2016-11-12 18:17:58

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[] = oldConsole[];
        //Make sure the setEnable will be callable from original one.
        console[].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:});
        //replace the original with the empty one.
        console[] = fn;
        //set the enable function
        console[].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;

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.
//Put the set enabled function on the original console using the defined flags and set them.

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)

@Rodrigo Assis 2017-09-15 18:28:50

do you think that this could be used to enable the console.log in production environment on the fly? like open Chrome console, run console.log.setEnabled(true) and start seeing logs

@Gabriel De Oliveira Rohden 2017-09-18 17:06:59

@RodrigoAssis yes, it will work. I've created this just to do not lose the caller line and enable anywhere, but this isn't the best way to do it. The best way for logs is use the short circuit way like: var debug = false; debug && console.log(1/3) because you don't need to evaluate the log content if it isn't enabled (in this case 1/3 will not be evaluated), don't lose the caller line and can enable it easily too (if don't vars as consts).

@graphefruit 2016-07-21 14:43:42

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


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


if you need to.

This works in my app:

   try {
        if (typeof(window.console) != "undefined") {
            window.console = {};
            window.console.log = function () {
   = function () {
            window.console.warn = function () {
            window.console.error = function () {

        if (typeof(alert) !== "undefined") {
            alert = function ()


    } catch (ex) {


@Panini Luncher 2019-10-27 20:04:57

Thanks for the "warning". HOWEVER, I had my cordova-based app released onto GooglePlay store, tested it with phone devices and all were fine. I may assume your warning was limited to "windows-based" app store? ... HOWEVER, it is good advise to put the ops within try-catch bracket just in case it blow up. Hence the thumbs-up.

@Sunny R Gupta 2016-07-04 09:29:28

I developed a library for this usecase:


  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.

@Iman Mohamadi 2016-06-12 20:44:41

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>'security');

logeek('some message').at('copy');       //this won't be logged
logeek('other message').at('secturity'); //this would be logged

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

@Xavier13 2015-05-08 10:02:30

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

@istepaniuk 2015-01-06 11:27:44

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.

@Marco Sulla 2015-08-07 10:54:38

"other libraries you use may revert your changes": if I disable console.log at the very start, they can't revert to the old function. Well, they can rewrite the console.log source code, but why? "it may be a good idea to write your own logger object/function that wraps around the console object": I've done this in past and it's a bad idea. The trace of the console output refers to the wrapper and not to the line that invokes it, making debugging more difficult.

@istepaniuk 2015-08-10 21:19:37

@LucasMalor "at the very start" implies the code is coupled to that infrastructure thus limiting its reusability. It is difficult to generalized though; A game, some DOM animations are not the same as domain logic inside a complex SPA, the later shouldn't be browser-aware, let alone knowing about something called "console". In that case you should have a proper testing strategy instead of hacking some console.log('Look ma, it reaches this point'); in your code, when everything else fails you can indeed use the debugger; instruction.

@Marco Sulla 2015-08-12 10:15:53

"the code is coupled to that infrastructure": the code probably, but the pattern not. If you create a common basic template for your pages where logging functions are disabled, it's a logic that you can apply everywhere. "the later shouldn't be browser-aware": well, so you shouldn't use JS :P

@dudewad 2015-08-31 21:57:51

@MarcoSulla I think he's getting at writing cleaner code. Saying " shouldn't use JS" is a bit heavy handed. Ideally, as a programmer, no matter what your environment is, you should modularize as much as possible; if it doesn't care about browsers, then you can deploy it in more places: that's one less dependency to worry about breaking your stuff. So, IMHO yeah, he's actually right. Keep in mind that you started by saying "If you create a common basic template..." which in and of itself introduces a dependency. This kind of thinking is what complicates software. Food for thought.

@spinn 2018-03-09 10:54:52

Adobe SiteCatalyics throws a lot of junk in my console and makes a hassle of debugging in some cases. So being able to temporarily disable console.log when I execute a third-party call would be pretty useful for me

@locka 2020-05-15 10:46:41

Browsers aren't the only applications these days which use JS (e.g. electron, nodejs). And in any deployment you may have a really noisy console that you want to dampen it down by replacing the console object with something else..

@Swanidhi 2014-12-17 17:40:04

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

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

@sleblanc 2015-04-14 19:44:53

I'd go one step further and wrap this in a logger function/class. Something like this: function myLog(msg) { if (debug) { console.log(msg); } }

@Swanidhi 2015-05-01 21:37:46

If using Angular, you can use it as a global configuration in your application.js file and use it as a global property to switch the logs on /off. Remember, console will not be undefined if you have the developers toolbar open in IE.

@jdborowy 2014-10-14 20:34:49

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.

@Justin 2013-01-08 21:02:03

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() {    
    console.log('this should not show');

    console.log('This will show');

@Joey Schooley 2013-09-09 20:51:31

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

@kikeenrique 2013-02-14 14:49:42

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.debug = console.warn = console.trace = console.dir = console.dirxml = = console.groupEnd = console.time =    console.timeEnd = console.assert = console.profile = function() {};

@Stijn Geukens 2012-05-31 14:35:49

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.

@Stijn Geukens 2013-02-11 08:34:28

I have not implemented such a solution, not did I see it. It's theoretical so far.

@Tom McKearney 2012-03-02 15:15:09

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.

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

Fore more docs, check out the Documentation


@Scott Greenfield 2011-09-22 14:31:39

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.debug = console.warn = console.trace = console.dir = console.dirxml = = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};

@GuruM 2013-02-11 06:50:03

For IE specific logging disabling see Chris S. answer.

@Chris S 2011-05-20 18:40:38

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

@mwilcox 2009-08-01 14:52:51

The following is more thorough:

var DEBUG = false;
    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(){};

@Muganwas 2020-03-20 13:20:14

This worked for me perfectly, although I tweaked it a little bit, I checked for environment(I only want it disabled in production)

@Cide 2009-07-31 23:55:06

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);

@Zack Burt 2009-08-01 00:05:48

Thanks, although this means I need to rewrite all my console.log statements as debug.log.

@OpenSource 2009-08-01 00:13:06

This is the right way to do it - ofcourse if you are starting from scratch.

@BaroqueBobcat 2009-08-01 00:34:26

It is also the right way to do it if you have a good find/replace function in your editor.

@Nelson 2009-08-01 00:40:27

No need to write your own wrapper, btw, at least if you're using jQuery. The jQuery Debugging Plugin works great. As a bonus it provides emulation of console.log on browsers without it.

@Cide 2009-08-01 00:41:42

The only [minor] problem, of course, being that you need to install a plugin. :) Good to know, though - thanks!

@redsquare 2009-08-01 00:54:12

well not install, rather include the plugin on your page

@Eugene Lazutkin 2009-08-01 01:53:27

Good idea, but it doesn't work everywhere: IE8 defines console.log, but doesn't define console.log.apply. Bummer.

@DA. 2010-02-05 01:07:13

Doesn't look like that second option works in <=IE7. You get a 'console is not defined' error in those browsers.

@GuruM 2013-02-11 06:54:52

To make it work in IE7 etc please have a look at 'Chris S.' answer.

@Gabriël 2014-12-04 15:30:51

Having been there and done that; wrapping it prevents you from using the Firebug feature that allows you to click directly to the line that caused the log message, as it will always jump to your wrapper method.

Related Questions

Sponsored Content

67 Answered Questions

[SOLVED] How to replace all occurrences of a string?

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

25 Answered Questions

[SOLVED] How does JavaScript .prototype work?

39 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

77 Answered Questions

[SOLVED] What is the JavaScript version of sleep()?

  • 2009-06-04 14:41:10
  • fmsf
  • 2718060 View
  • 2376 Score
  • 77 Answer
  • Tags:   javascript sleep

49 Answered Questions

[SOLVED] Validate decimal numbers in JavaScript - IsNumeric()

7 Answered Questions

[SOLVED] Why does Google prepend while(1); to their JSON responses?

54 Answered Questions

Sponsored Content