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


当前回答

你可以使用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')来完全禁用每条日志消息。

其他回答

如果你正在使用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 /” ) ); });

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

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

这就是我的方法。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添加了一个保护,而不是猴子补丁。它是安全的。

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

在脚本中重新定义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。

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

特点:

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

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