是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?


当前回答

下面是更详细的:

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

这将把控制台中存在的通用方法归零,并且可以毫无错误地调用它们,而且几乎没有性能开销。在像IE6这样没有控制台的浏览器的情况下,将创建虚拟方法以防止错误。当然,Firebug中还有更多的函数,比如跟踪、配置文件、时间等。如果在代码中使用它们,则可以将它们添加到列表中。

你也可以检查调试器是否有这些特殊的方法(ie, ie),并将不支持的方法归零:

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

其他回答

下面是更详细的:

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

这将把控制台中存在的通用方法归零,并且可以毫无错误地调用它们,而且几乎没有性能开销。在像IE6这样没有控制台的浏览器的情况下,将创建虚拟方法以防止错误。当然,Firebug中还有更多的函数,比如跟踪、配置文件、时间等。如果在代码中使用它们,则可以将它们添加到列表中。

你也可以检查调试器是否有这些特殊的方法(ie, ie),并将不支持的方法归零:

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

我这样写道:

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

    }
}

不幸的是,它在使用严格模式下不起作用。

使用console。fn。setEnabled = setEnabled然后是console。fn。setEnabled(false) fn可以是几乎任何控制台函数。 你的情况是:

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

我还写了这个:

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

所以你只需要在FLAGS中加入默认值(在执行上面的代码之前),比如FLAGS. log = false,日志功能将在默认情况下被禁用,仍然可以调用console.log.setEnabled(true)来启用它

如果你使用Webpack,你可以使用Terser插件来完全排除console.log函数调用。

这样你就可以有一个干净的生产应用程序包,它不会暴露不必要的信息,但在调试版本中仍然有所有这些信息。

https://github.com/terser/terser#compress-options

drop_console(默认值:false)——传递true以丢弃对控制台的调用。*功能。如果你希望删除一个特定的函数调用,如console.info和/或在删除函数调用后保留函数参数的副作用,则使用pure_funcs代替。

minimizer: [
    new TerserPlugin({
        terserOptions: {
            compress: {
                pure_funcs: [ 'console.log' ]
            }
        }
    }),
]

或者你也可以使用drop_console: true来排除所有控制台调用。

这是在JS 2020中引入的。在浏览器上globalThis和window一样,在nodejs上globalThis和global一样等等。在任何环境上,它将直接指向全局对象,因此这段代码将在任何支持JS2020的env上工作了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

对于任何现代浏览器& nodejs v12或更新版本,你应该使用这个:

globalThis.console.log = () => null;
globalThis.console.warn = () => null;
globalThis.console.info = () => null;
globalThis.console.error = () => null;

我之前用过温斯顿记录器。

现在,我使用以下简单的代码从经验:

从cmd/命令行设置环境变量(在Windows上): cmd setx LOG_LEVEL信息

或者,如果你愿意,你可以在你的代码中有一个变量,但上面更好。

Restart cmd/ command line, or, IDE/ editor like Netbeans 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; } 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

现在,根据点1中的LOG_LEVEL设置(例如,setx LOG_LEVEL日志和重新启动命令行),上面的一些将打印,其他将不打印

希望这有帮助。