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


在脚本中重新定义console.log函数。

console.log = function() {}

够了,不再给控制台发消息了。

编辑:

扩展了Cide的想法。一个自定义记录器,您可以使用它从代码中切换登录。

从我的Firefox控制台:

var logger = function()
{
    var oldConsoleLog = null;
    var pub = {};

    pub.enableLogger =  function enableLogger() 
                        {
                            if(oldConsoleLog == null)
                                return;

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

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

    return pub;
}();

$(document).ready(
    function()
    {
        console.log('hello');

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

        logger.enableLogger();
        console.log('This will show up!');
    }
 );

如何使用上面的“记录器”?在就绪事件中,调用记录器。disableLogger使控制台消息不被记录。向记录器添加调用。enabllogger和logger。在希望将消息记录到控制台的方法中的disableLogger。

据我从文档中得知,Firebug没有提供任何变量来切换调试状态。相反,将console.log()包装在一个有条件地调用它的包装器中,即:

DEBUG = true; // set to false to disable debugging
function debug_log() {
    if ( DEBUG ) {
        console.log.apply(this, arguments);
    }
}

为了不需要改变所有现有的调用,你可以使用这个代替:

DEBUG = true; // set to false to disable debugging
old_console_log = console.log;
console.log = function() {
    if ( DEBUG ) {
        old_console_log.apply(this, arguments);
    }
}

下面是更详细的:

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

如果你使用IE7,控制台将不会被定义。所以一个更IE友好的版本是:

if (typeof console == "undefined" || typeof console.log == "undefined") 
{
   var console = { log: function() {} }; 
}

我知道你问如何禁用console.log,但这可能是你真正想要的。这样就不必显式地启用或禁用控制台。它只是为那些没有打开或安装它的人防止那些讨厌的控制台错误。

if(typeof(console) === 'undefined') {
    var console = {};
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

警告:无耻的插头!

您还可以使用类似我的JsTrace对象的东西来进行模块化跟踪,并具有模块级别的“切换”功能,从而只打开您当时想要看到的内容。

http://jstrace.codeplex.com

(也有一个NuGet包,为那些谁关心)

所有级别默认为“error”,尽管你可以关闭它们。 不过,我想不出为什么您不希望看到错误

你可以这样改变它们:

Trace.traceLevel('ModuleName1', Trace.Levels.log);
Trace.traceLevel('ModuleName2', Trace.Levels.info);

要获得更多文档,请查看文档

T

你可以使用javascript AOP(例如jquery-aop)来拦截所有对console.debug/log的调用,如果某个全局变量被设置为false,就不进行实际的调用。

您甚至可以(不时地)执行ajax调用,这样就可以更改服务器上启用/禁用日志的行为,当在登台环境或类似环境中遇到问题时启用调试,这可能非常有趣。

这是来自SolutionYogi和Chris s的答案的混合。它维护console.log行号和文件名。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() {    
    MYAPP.disableLog();    
    console.log('this should not show');

    MYAPP.enableLog();
    console.log('This will show');
});

我在这个url中找到了一段更高级的代码。

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

我知道这是一个老帖子,但它仍然弹出在谷歌结果的顶部,所以这里有一个更优雅的非jquery解决方案,在最新的Chrome, FF和IE中工作。

(function (original) {
    console.enableLogging = function () {
        console.log = original;
    };
    console.disableLogging = function () {
        console.log = function () {};
    };
})(console.log);

如果你使用Grunt,你可以添加一个任务来删除/注释console.log语句。因此console.log不再被调用。

https://www.npmjs.org/package/grunt-remove-logging-calls

只需更改标志DEBUG以覆盖console.log函数。这应该能奏效。

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

你不应该!

重写内置函数不是一个好的做法。也不能保证你会抑制所有输出,你使用的其他库可能会与你的更改冲突,还有其他函数可能会写入控制台;.warning .dir (), (), . error (), .debug (), . assert()等。

正如一些人建议的那样,您可以定义一个DEBUG_MODE变量并有条件地记录日志。根据代码的复杂性和性质,编写自己的记录器对象/函数可能是一个好主意,它包装了控制台对象并内置了此功能。那将是处理仪器的正确地方。

也就是说,出于“测试”的目的,您可以编写测试,而不是打印到控制台。如果您不做任何测试,而那些console.log()行只是编写代码的辅助,那么只需删除它们。

令我惊讶的是,在所有这些答案中,没有人把它们结合起来:

没有jquery 匿名函数不污染全局命名空间 窗口的句柄情况。控制台未定义 只需修改控制台的.log函数

我会选这个:

(function () {

    var debug = false

    if (debug === false) {
        if ( typeof(window.console) === 'undefined') { window.console = {}; }
        window.console.log = function () {};
    }
})()

你可以使用logeek,它可以让你控制你的日志消息的可见性。你可以这样做:

<script src="bower_components/dist/logeek.js"></script>

logeek.show('security');

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

你也可以使用logeek.show('nothing')来完全禁用每条日志消息。

我为这个用例开发了一个库:https://github.com/sunnykgupta/jsLogger

特点:

它会安全地覆盖console.log。 注意控制台是否不可用(哦,是的,你也需要考虑这个因素)。 存储所有日志(即使它们被抑制)以供以后检索。 处理主要控制台功能,如日志,警告,错误,信息。

是开放的修改,并将更新每当有新的建议。

在我搜索了这个问题以及在我的cordova应用程序中尝试后,我只是想警告每个windows phone的开发者不要覆盖

    console.log

因为应用程序在启动时会崩溃。

如果你幸运的话,它不会崩溃,但在商店中提交它会导致应用程序崩溃。

只是覆盖

    window.console.log 

如果你需要的话。

这在我的应用程序工作:

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

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

            }
        }

    } catch (ex) {

    }

我这样写道:

//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)来启用它

这应该覆盖window.console的所有方法。你可以把它放在你的脚本部分的最上面,如果你在一个PHP框架上,你只能在你的应用程序环境是生产的时候打印这段代码,或者当某种调试标志被禁用的时候。然后,代码中的所有日志都将在开发环境或调试模式下工作。

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;
})(window.console);

我一直在用以下方法来处理这个问题:-

var debug = 1;
var logger = function(a,b){ if ( debug == 1 ) console.log(a, b || "");};

将debug设置为1以启用调试。然后在输出调试文本时使用记录器函数。它还设置为接受两个参数。

所以,与其

console.log("my","log");

use

logger("my","log");

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

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

从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日志和重新启动命令行),上面的一些将打印,其他将不打印

希望这有帮助。

我的全面解决方案禁用/覆盖所有控制台。*函数在这里。

当然,请确保在检查必要的上下文之后包含它。例如,只包含在产品版本中,它不会轰炸任何其他关键组件等。

这里引用一下:

“使用严格的”; (() => { Var控制台=(窗口。控制台=窗口。控制台|| {}); [ “维护”、“清楚”、“数”、“调试”,“dir”、“dirxml”, "error", "exception", "group", " groupcollapse ", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time" "timeEnd" "timeStamp" "trace" "warn" ]。forEach(方法=> { Console [method] = () => {}; }); console.log("此消息不应该在控制台日志中可见"); })();

如果你正在使用gulp,那么你可以使用这个插件:

使用下面的命令安装这个插件: NPM安装gulp-remove-logging 接下来,将这一行添加到gulpfile中: Var gulp_remove_logging = require("gulp-remove-logging"); 最后,将配置设置(见下文)添加到gulpfile中。 任务配置 饮而尽。任务("remove_logging",函数(){ 返回gulp.src (" src / javascript / * * / * . js”) .pipe ( gulp_remove_logging () ) .pipe ( gulp.dest ( “构建/ javascript /” ) ); });

https://stackoverflow.com/a/46189791/871166的简化

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

在对这个问题做了一些研究和开发之后,我遇到了这个解决方案,它将根据您的选择隐藏警告/错误/日志。

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

将此代码添加到JQuery插件(例如/../ JQuery. min.js)之前,即使这是不需要JQuery的JavaScript代码。因为有些警告是JQuery本身的。

谢谢! !

我写了一个ES2015解决方案(仅用于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 = [].slice.call(arguments);

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

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

    const copy = [].slice.call(arguments);

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

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

    const copy = [].slice.call(arguments);

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

描述:

Along with logger.enable and logger.disable you can use console.['log','warn','error'] methods as well using logger class. By using logger class for displaying, enabling or disabling messages makes the code much cleaner and maintainable. 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..

我认为2020年最简单、最容易理解的方法是创建一个像log()这样的全局函数,你可以选择以下方法之一:

const debugging = true;

function log(toLog) {
  if (debugging) {
    console.log(toLog);
  }
}
function log(toLog) {
  if (true) { // You could manually change it (Annoying, though)
    console.log(toLog);
  }
}

你可以说这些功能的缺点是:

您仍然在运行时调用函数 您必须记住在第二个选项中更改调试变量或if语句 您需要确保在加载所有其他文件之前加载了该函数

And my retorts to these statements is that this is the only method that won't completely remove the console or console.log function which I think is bad programming because other developers who are working on the website would have to realize that you ignorantly removed them. Also, you can't edit JavaScript source code in JavaScript, so if you really want something to just wipe all of those from the code you could use a minifier that minifies your code and removes all console.logs. Now, the choice is yours, what will you do?

如果你使用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来排除所有控制台调用。

一行代码设置devMode为true/false;

console.log = devMode ?console.log:() => {};

禁用console.log:

console.log = function() {};

禁用所有写入控制台的功能。

for (let func in console) {
   console[func] = function() {};
}

我自己弄明白后发现了这个帖子。以下是我的解决方案:

const testArray = {
  a: 1,
  b: 2
};
const verbose = true; //change this to false to turn off all comments
const consoleLog = (...message) => {
  return verbose ? console.log(...message) : null;
};

console.log("from console.log", testArray);
consoleLog("from consoleLog", testArray);
// use consoleLog() for the comments you want to be able to toggle.

这是我刚刚研究的一个相当详尽的解决方案。我介绍了https://developer.mozilla.org/en-US/docs/Web/API/console中所有完全支持的控制台方法

1. 创建js文件“logger.js”,并将以下代码放入其中

logger = {
    assert: function() {
        if(logger.active && logger.doAssert) {
            console.assert.apply(null,arguments);
        }
    },
    clear: function() {
        if(logger.active && logger.doClear) {
            console.clear();
        }
    },
    count: function() {
        if(logger.active && logger.doCount) {
            console.count.apply(null,arguments);
        }
    },
    countReset: function() {
        if(logger.active && logger.doCountReset) {
            console.countReset.apply(null,arguments);
        }
    },
    debug: function() {
        if(logger.active && logger.doDebug) {
            console.debug.apply(null,arguments);
        }
    },
    dir: function() {
        if(logger.active && logger.doDir) {
            console.dir.apply(null,arguments);
        }
    },
    dirxml: function() {
        if(logger.active && logger.doDirxml) {
            console.dirxml.apply(null,arguments);
        }
    },
    error: function() {
        if(logger.active && logger.doError) {
            console.error.apply(null,arguments);
        }
    },
    group: function() {
        if(logger.active && logger.doGroup) {
            console.group.apply(null,arguments);
        }
    },
    groupCollapsed: function() {
        if(logger.active && logger.doGroup) {
            console.groupCollapsed.apply(null,arguments);
        }
    },
    groupEnd: function() {
        if(logger.active && logger.doGroup) {
            console.groupEnd.apply(null,arguments);
        }
    },
    info: function() {
        if(logger.active && logger.doInfo) {
            console.info.apply(null,arguments);
        }
    },
    log: function() {
        if(logger.active && logger.doLog) {
            console.log.apply(null,arguments);
        }
    },
    table: function() {
        if(logger.active && logger.doTable) {
            console.table.apply(null,arguments);
        }
    },
    time: function() {
        if(logger.active && logger.doTime) {
            console.time.apply(null,arguments);
        }
    },
    timeEnd: function() {
        if(logger.active && logger.doTime) {
            console.timeEnd.apply(null,arguments);
        }
    },
    timeLog: function() {
        if(logger.active && logger.doTime) {
            console.timeLog.apply(null,arguments);
        }
    },
    trace: function() {
        if(logger.active && logger.doTrace) {
            console.trace.apply(null,arguments);
        }
    },
    warn: function() {
        if(logger.active && logger.doWarn) {
            console.warn.apply(null,arguments);
        }
    },
    active: true,
    doAssert: true,
    doClear: true,
    doCount: true,
    doCountReset: true,
    doDebug: true,
    doDir: true,
    doDirxml: true,
    doError: true,
    doGroup: true,
    doInfo: true,
    doLog: true,
    doTable: true,
    doTime: true,
    doTrace: true,
    doWarn: true
};

2. 在所有脚本之前,在所有页面中都包含日志

3.将脚本中的所有“console.”替换为“logger.”

4. 使用

就像"console "一样,但是和"logger "连用

logger.clear();
logger.log("abc");

最后禁用部分或全部日志

//disable/enable all logs
logger.active = false; //disable
logger.active = true; //enable

//disable some logs
logger.doLog = false; //disable
logger.doInfo = false; //disable

logger.doLog = true; //enable
logger.doInfo = true; //enable

logger.doClear = false; //log clearing code will no longer clear the console.

EDIT

在我最近的项目中使用我的解决方案一段时间后,我意识到很难记住我应该使用logger。而不是主机。所以出于这个原因,我决定重写控制台。这是我的最新解决方案:

const consoleSubstitute = console;
console = {
    assert: function() {
        if(console.active && console.doAssert) {
            consoleSubstitute.assert.apply(null,arguments);
        }
    },
    clear: function() {
        if(console.active && console.doClear) {
            consoleSubstitute.clear();
        }
    },
    count: function() {
        if(console.active && console.doCount) {
            consoleSubstitute.count.apply(null,arguments);
        }
    },
    countReset: function() {
        if(console.active && console.doCountReset) {
            consoleSubstitute.countReset.apply(null,arguments);
        }
    },
    debug: function() {
        if(console.active && console.doDebug) {
            consoleSubstitute.debug.apply(null,arguments);
        }
    },
    dir: function() {
        if(console.active && console.doDir) {
            consoleSubstitute.dir.apply(null,arguments);
        }
    },
    dirxml: function() {
        if(console.active && console.doDirxml) {
            consoleSubstitute.dirxml.apply(null,arguments);
        }
    },
    error: function() {
        if(console.active && console.doError) {
            consoleSubstitute.error.apply(null,arguments);
        }
    },
    group: function() {
        if(console.active && console.doGroup) {
            consoleSubstitute.group.apply(null,arguments);
        }
    },
    groupCollapsed: function() {
        if(console.active && console.doGroup) {
            consoleSubstitute.groupCollapsed.apply(null,arguments);
        }
    },
    groupEnd: function() {
        if(console.active && console.doGroup) {
            consoleSubstitute.groupEnd.apply(null,arguments);
        }
    },
    info: function() {
        if(console.active && console.doInfo) {
            consoleSubstitute.info.apply(null,arguments);
        }
    },
    log: function() {
        if(console.active && console.doLog) {
            if(console.doLogTrace) {
                console.groupCollapsed(arguments);
                consoleSubstitute.trace.apply(null,arguments);
                console.groupEnd();
            } else {
                consoleSubstitute.log.apply(null,arguments);
            }
        }
    },
    table: function() {
        if(console.active && console.doTable) {
            consoleSubstitute.table.apply(null,arguments);
        }
    },
    time: function() {
        if(console.active && console.doTime) {
            consoleSubstitute.time.apply(null,arguments);
        }
    },
    timeEnd: function() {
        if(console.active && console.doTime) {
            consoleSubstitute.timeEnd.apply(null,arguments);
        }
    },
    timeLog: function() {
        if(console.active && console.doTime) {
            consoleSubstitute.timeLog.apply(null,arguments);
        }
    },
    trace: function() {
        if(console.active && console.doTrace) {
            consoleSubstitute.trace.apply(null,arguments);
        }
    },
    warn: function() {
        if(console.active && console.doWarn) {
            consoleSubstitute.warn.apply(null,arguments);
        }
    },
    active: true,
    doAssert: true,
    doClear: true,
    doCount: true,
    doCountReset: true,
    doDebug: true,
    doDir: true,
    doDirxml: true,
    doError: true,
    doGroup: true,
    doInfo: true,
    doLog: true,
    doLogTrace: false,
    doTable: true,
    doTime: true,
    doTrace: true,
    doWarn: true
};

现在你可以使用控制台。像往常一样。

在其他答案的基础上,我个人希望只关闭代码的特定部分(ES6模块,但简单的单独脚本也可以)。


// old console to restore functionality
const consoleHolder = window.console;

// arbitrary strings, for which the console stays on (files which you aim to debug)
const debuggedHandlers = ["someScript", "anotherScript"];

// get console methods and create a dummy with all of them empty
const consoleMethodKeys = Object.getOwnPropertyNames(window.console).filter(item => typeof window.console[item] === 'function');
const consoleDummy = {};
consoleMethodKeys.forEach(method => consoleDummy[method] = () => {});

export function enableConsoleRedirect(handler) {
  if (!debuggedHandlers.includes(handler)) {
    window.console = consoleDummy;
  }
}

export function disableConsoleRedirect() {
  window.console = consoleHolder;
}

然后,只需将这个模块导入到您希望能够切换调试模式的任何文件中,在文件顶部调用enable函数,在底部调用disable函数。

如果希望在简单脚本中使用它,可能需要将顶部包装在匿名函数中和/或稍微重新组织它,以最大限度地减少名称空间污染。

此外,你可能想要只使用true/false而不是字符串处理程序,并在当前使用的文件中切换调试模式。

console.log('pre');
/* pre content */ 
// define a new console
let preconsole = Object.assign({}, window.console);
let aftconsole = Object.assign({}, window.console, {
    log: function(text){
        preconsole.log(text);
        preconsole.log('log');
    }
});
console = aftconsole;
/* content */

console.log('content');

/* end of content */
console = preconsole;
console.log('aft');

当使用React时,你可以利用钩子来管理它,这样它就被限制在你的组件范围内

import { useEffect, useRef } from "react";

type LoggingReplacements = {
  debug?: typeof console["debug"];
  error?: typeof console["error"];
  info?: typeof console["info"];
  log?: typeof console["log"];
  warn?: typeof console["warn"];
};
/**
 * This replaces console.XXX loggers with custom implementations.  It will restore console log on unmount of the component.
 * @param replacements a map of replacement loggers.  They're all optional and only the functions defined will be replaced.
 */
export function useReplaceLogging({
  debug,
  error,
  info,
  log,
  warn,
}: LoggingReplacements): void {
  const originalConsoleDebug = useRef(console.debug);
  const originalConsoleError = useRef(console.error);
  const originalConsoleInfo = useRef(console.info);
  const originalConsoleLog = useRef(console.log);
  const originalConsoleWarn = useRef(console.warn);
  if (debug) {
    console.debug = debug;
  }
  if (error) {
    console.error = error;
  }
  if (info) {
    console.info = info;
  }
  if (log) {
    console.log = log;
  }
  if (warn) {
    console.warn = warn;
  }
  useEffect(() => {
    return function restoreConsoleLog() {
      console.debug = originalConsoleDebug.current;
      console.error = originalConsoleError.current;
      console.info = originalConsoleInfo.current;
      console.log = originalConsoleLog.current;
      console.warn = originalConsoleWarn.current;
    };
  }, []);
}

在https://github.com/trajano/react-hooks/tree/master/src/useReplaceLogging上编写测试代码

这是在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;

嘿~让我们用现代的2022方式来做~

ES6中引入了代理和反射。这些是我们正在寻找的工具,使console.log被条件“禁用”。

在传统的方法中,你必须创建另一个函数,像这样:

    let console_disabled = true;

    function console_log() {
      if (!console_disabled) {
        console.log.apply(console, arguments); //Dev Tools will mark the coding line here
      }
    }

但是,这将创建另一个函数,并且您无法使用Dev Tools中显示的编码行记录消息。

这就是2022年之路。

// Disable Console Log without altering debug coding line. // No override original `console` object let console_disabled = false; const nullFunc = function(){}; const _console = new Proxy(console, { get(target, prop, receiver){ if(prop==='log' && console_disabled){ return nullFunc; } return Reflect.get(...arguments) } }); console_disabled = true; _console.log('you cannot see me'); console_disabled = false; _console.log('you can see me @ line 18'); console_disabled = true; _console.log('you cannot see me'); console_disabled = false; _console.log('you can see me @ line 22');

您还可以重写原来的控制台对象。

// Disable Console Log without altering debug coding line. // Override original `console` object let console_disabled = false; const nullFunc = function(){}; console = new Proxy(console, { get(target, prop, receiver){ if(prop==='log' && console_disabled){ return nullFunc; } return Reflect.get(...arguments) } }); console_disabled = true; console.log('you cannot see me'); console_disabled = false; console.log('you can see me @ line 18'); console_disabled = true; console.log('you cannot see me'); console_disabled = false; console.log('you can see me @ line 22');

有关代理和反射的详细信息, 请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

这就是我的方法。https://github.com/jchnxu/guard-with-debug 免责声明:我是这个小实用程序的作者

localStorage.debug = [
    'enable/console/log/in/this/file.ts',
    'enable/console/log/in/this/folder/*',
    '-disable/console/log/in/this/file.ts',
    '-disable/console/log/in/this/folder/*',
    
    // enable all
    '*',
].join(',');

这种方法的好处是我们可以基于文件名启用/禁用,在以下情况下尤其有用

跨多个复杂模块调试 输出内容很大,在视觉上令人不安 通过触摸代码库快速打开/关闭日志记录,当您只是部署到有更多日志的生产环境时,这会更安全。

为什么要触摸console.log?危险吗?

这多少有点自以为是。我发现自己写了很多主机游戏。而不是更标准的方式从'xxx' && logger.info(…)导入记录器。我想原因是console.log是js原生的,它感觉更自然。

这个插件只是给console.log添加了一个保护,而不是猴子补丁。它是安全的。

并且你可以安全地移除所有的控制台。使用该插件登录生产,或者使用与上面相同的配置保留您想要的插件。