How to quickly and conveniently disable all consol

2019-01-01 02:46发布

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

23条回答
浪荡孟婆
2楼-- · 2019-01-01 03:13

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)

查看更多
荒废的爱情
3楼-- · 2019-01-01 03:16

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

查看更多
十年一品温如言
4楼-- · 2019-01-01 03:17

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");
查看更多
裙下三千臣
5楼-- · 2019-01-01 03:18

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() {}
}
查看更多
人间绝色
6楼-- · 2019-01-01 03:20

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

查看更多
泛滥B
7楼-- · 2019-01-01 03:21

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(){};
    }
}
查看更多
登录 后发表回答