如何快速方便地禁用我的代码中的所有 console.log 语句?

Posted

技术标签:

【中文标题】如何快速方便地禁用我的代码中的所有 console.log 语句?【英文标题】:How to quickly and conveniently disable all console.log statements in my code? 【发布时间】:2010-11-15 23:15:07 【问题描述】:

有什么方法可以关闭我的 javascript 代码中的所有 console.log 语句以进行测试?

【问题讨论】:

使用支持“全部替换”的文本编辑器,将“console.log”替换为“//console.log” @helloandre - 如果你使用日志、信息、警告调试和错误,这会有点烦人 希望我们能达到浏览器实现自动绕过控制台语句的地步,除非启用了浏览器的调试工具。 下面的答案很棒,但您不必在这个问题上重新发明***。看看picolog。它具有与(NodeJS 的)控制台兼容的 API,因此您可以将其用作替代品。它支持开箱即用的日志记录级别,可在浏览器、NodeJS 和 Nashorn 上运行,可以从查询字符串(浏览器)或环境变量 PICOLOG_LEVEL(节点)轻松配置,而且它超级小.小于 900 字节的压缩和压缩。免责声明:我是作者。 有一种简单的方法可以覆盖所有console 函数。看看stapp.space/disable-javascript-console-on-production 【参考方案1】:

在脚本中重新定义 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!');
    
 );

如何使用上面的“记录器”?在您的就绪事件中,调用 logger.disableLogger 以便不记录控制台消息。在要将消息记录到控制台的方法中添加对 logger.enableLogger 和 logger.disableLogger 的调用。

【讨论】:

请详细说明什么不起作用?上面的行是否给您一个错误?如果是,错误信息是什么? 代码覆盖并恢复了console.log函数。如果 IE7 支持 console.log 方法,它应该可以工作。 console.log = function() 在 Firefox 中似乎不起作用。您仍然会收到“未定义控制台”错误。 Firefox 20.0.1 记录所有内容,即使它应该在您的代码中被禁用 多么可怕的解决方案。正在修改 console.log... 为什么不只使用布尔值和条件函数来记录日志?【参考方案2】:

以下更彻底:

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)并将其不支持的方法清零:

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

【讨论】:

这对我来说非常有效,虽然我稍微调整了一下,但我检查了环境(我只希望在生产中禁用它)【参考方案3】:

据我从documentation 得知,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);
    

【讨论】:

谢谢,虽然这意味着我需要将所有 console.log 语句重写为 debug.log。 这是正确的做法——当然,如果你是从头开始的话。 如果你的编辑器有很好的查找/替换功能,这也是正确的做法。 不需要编写自己的包装器,顺便说一句,至少如果您使用的是 jQuery。 jQuery 调试插件效果很好。作为奖励,它在没有它的浏览器上提供了对 console.log 的模拟。 trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug 唯一的[小]问题,当然,是你需要安装一个插件。 :) 不过很高兴知道 - 谢谢!【参考方案4】:

你不应该!

覆盖内置函数不是一个好习惯。也不能保证您会抑制所有输出,您使用的其他库可能会还原您的更改,并且还有其他功能可能会写入控制台; .dir().warning().error().debug().assert()

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

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

【讨论】:

"other libraries you use may revert your changes": 如果我一开始就禁用console.log,他们就无法恢复到旧功能。好吧,他们可以重写console.log 源代码,但为什么呢? "it may be a good idea to write your own logger object/function that wraps around the console object":我过去做过这个,这是个坏主意。控制台输出的跟踪指的是包装器,而不是调用它的行,这使得调试更加困难。 @LucasMalor “一开始”暗示代码与该基础设施耦合,从而限制了其可重用性。但是很难一概而论;一个游戏,一些 DOM 动画与复杂 SPA 中的域逻辑不同,后者不应该是浏览器感知的,更不用说知道所谓的“控制台”。在这种情况下,你应该有一个适当的测试策略,而不是在你的代码中修改一些console.log('Look ma, it reaches this point');,当其他一切都失败时,你确实可以使用debugger; 指令。 "the code is coupled to that infrastructure":可能是代码,但不是模式。如果您为禁用日志功能的页面创建通用基本模板,那么您可以在任何地方应用这种逻辑。 "the later shouldn't be browser-aware": 好吧,所以你不应该使用 JS :P @MarcoSulla 我认为他正在编写更简洁的代码。说“....你不应该使用 JS”有点笨拙。理想情况下,作为程序员,无论你的环境是什么,都应该尽可能地模块化;如果它不关心浏览器,那么您可以将它部署在更多地方:这减少了担心破坏您的东西的依赖。所以,恕我直言,是的,他实际上是对的。请记住,您从说“如果您创建一个通用的基本模板......”开始,这本身就引入了依赖关系。这种想法使软件复杂化。值得深思。 Adobe SiteCatalyics 在我的控制台中抛出了很多垃圾,并且在某些情况下给调试带来了麻烦。因此,当我执行第三方调用时能够暂时禁用 console.log 对我来说非常有用【参考方案5】:

我知道这是一篇旧帖子,但它仍然会出现在 Google 搜索结果的顶部,所以这里有一个更优雅的非 jQuery 解决方案,适用于最新的 Chrome、FF 和 IE。

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

【讨论】:

【参考方案6】:

只需更改标志DEBUG 即可覆盖console.log 函数。这应该可以解决问题。

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

【讨论】:

我会更进一步,将其包装在一个记录器函数/类中。像这样的东西:function myLog(msg) if (debug) console.log(msg); 如果使用 Angular,您可以将其用作 application.js 文件中的全局配置,并将其用作全局属性来打开/关闭日志。请记住,如果您在 IE 中打开了开发人员工具栏,控制台将不会未定义。【参考方案7】:

我知道你问过如何禁用 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() ;

【讨论】:

对于 IE 特定的日志记录禁用,请参阅 Chris S. 回答。【参考方案8】:

我很惊讶所有这些答案中没有人结合:

没有 jquery 匿名函数不污染全局命名空间 处理未定义 window.console 的情况 只需修改控制台的.log函数

我愿意这样做:

(function () 

    var debug = false

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

【讨论】:

【参考方案9】:

在我也搜索过这个问题并在我的 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) 

    

【讨论】:

感谢您的“警告”。但是,我将基于科尔多瓦的应用程序发布到 GooglePlay 商店,用手机设备对其进行了测试,一切都很好。我可能会假设您的警告仅限于“基于 Windows”的应用商店? ...但是,最好将操作放在 try-catch 支架中,以防万一它爆炸。因此竖起大拇指。【参考方案10】:

如果您使用的是 IE7,则不会定义控制台。所以更适合 IE 的版本是:

if (typeof console == "undefined" || typeof console.log == "undefined") 

   var console =  log: function()  ; 

【讨论】:

【参考方案11】:

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

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

【讨论】:

【参考方案12】:

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

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

【讨论】:

【参考方案13】:

我一直在使用以下方法来处理他的问题:-

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

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

所以,而不是

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

使用

logger("my","log");

【讨论】:

【参考方案14】:

我之前使用过winston logger。

现在我正在使用以下更简单的代码:

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

    cmd
    setx LOG_LEVEL info
    

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

    重启 cmd/ 命令行,或者,像 Netbeans 这样的 IDE/ 编辑器

    下面有类似代码:

    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;
    
    

    现在使用所有控制台。*如下:

    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 log 并重新启动命令行),上面的某些内容将打印,其他内容将不会打印

希望有所帮助。

【讨论】:

【参考方案15】:

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

通过这种方式,您可以获得一个干净的生产应用程序包,它不会暴露不必要的信息,但在您的调试版本中仍然包含所有这些信息。

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

drop_console (default: false) -- 传递 true 以放弃对 console.* 函数的调用。如果您希望删除特定的函数调用,例如 console.info 和/或在删除函数调用后保留函数参数的副作用,请改用 pure_funcs。

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

您也可以使用drop_console: true 排除所有控制台调用。

【讨论】:

【参考方案16】:

警告:无耻插件!

您还可以使用像我的 JsTrace 对象这样的东西来进行模块化跟踪,并具有模块级“切换”功能,以便仅打开您当时想看到的内容。

http://jstrace.codeplex.com

(还有一个 NuGet 包,供关心的人使用)

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

您可以像这样更改它们:

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

更多文档,请查看the Documentation

T

【讨论】:

【参考方案17】:

我在这个网址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.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time =    console.timeEnd = console.assert = console.profile = function() ;

【讨论】:

【参考方案18】:

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

特点:

    它安全地覆盖了 console.log。 请注意控制台是否不可用(哦,是的,您也需要考虑这一点。) 存储所有日志(即使它们被禁止)以供以后检索。 处理主要的控制台功能,如logwarnerrorinfo

开放修改,并会在有新建议出现时更新。

【讨论】:

【参考方案19】:

这应该覆盖 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);

【讨论】:

【参考方案20】:

https://***.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() ;


【讨论】:

【参考方案21】:

这是我写的:

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

【讨论】:

你认为这可以用来在生产环境中动态启用console.log吗?比如打开 Chrome 控制台,运行 console.log.setEnabled(true) 并开始查看日志 @RodrigoAssis 是的,它会起作用的。我创建它只是为了不丢失呼叫者线路并在任何地方启用,但这不是最好的方法。日志的最佳方式是使用短路方式,例如:var debug = false; debug &amp;&amp; console.log(1/3),因为如果未启用日志内容,则无需评估(在这种情况下,1/3 将不会评估),不要丢失调用者行,也可以轻松启用它(如果不将 vars 作为 consts)。【参考方案22】:

我禁用/覆盖所有console.* 功能的综合解决方案是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");
)();

【讨论】:

【参考方案23】:

如果你使用 gulp,那么你可以使用this 插件:

使用以下命令安装此插件:

npm install gulp-remove-logging

接下来,将此行添加到您的 gulpfile 中:

var gulp_remove_logging = require("gulp-remove-logging");

最后,将配置设置(见下文)添加到您的 gulpfile。

任务配置

gulp.task("remove_logging", function() 
     return gulp.src("src/javascripts/**/*.js")
    .pipe(
      gulp_remove_logging()
    )
    .pipe(
      gulp.dest(
        "build/javascripts/"
      )
    ); );

【讨论】:

【参考方案24】:

仅禁用console.log

console.log = function() ;

禁用所有写入控制台的函数:

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


【讨论】:

【参考方案25】:

这是我刚刚研究的一个相当详尽的解决方案。我涵盖了来自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.替换所有“控制台”。用“记录器”。在你的脚本中

4.用法

就像“控制台”一样使用。但使用“记录器”。

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; //log clearing code will no longer clear the console.

编辑

在我的最新项目中使用我的解决方案一段时间后,我意识到很难记住我应该使用logger. 而不是console.。所以出于这个原因,我决定覆盖console。这是我更新的解决方案:

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
;

现在您可以照常使用console.

【讨论】:

【参考方案26】:
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');

【讨论】:

【参考方案27】:

您可以使用 javascript AOP(例如 jquery-aop)拦截所有对 console.debug/log 的调用(周围),如果某些全局变量设置为 false,则不要继续实际调用。

您甚至可以(不时)进行 ajax 调用,这样您就可以更改服务器上启用/禁用日志的行为,这对于在暂存环境等中遇到问题时启用调试非常有趣。

【讨论】:

我没有实现过这样的解决方案,没有看到。到目前为止,这是理论上的。【参考方案28】:

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

【讨论】:

【参考方案29】:

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

    (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 本身中。

谢谢!!

【讨论】:

【参考方案30】:

我写了一个 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);
  

说明:

    除了 logger.enable 和 logger.disable,您还可以使用 console.['log','warn','error'] 方法以及使用 logger 类。 通过使用 logger 类来显示、启用或禁用消息,使代码更加简洁和可维护。 下面的代码向您展示了如何使用记录器类: logger.disable() - 禁用所有控制台消息 logger.enable() - 启用所有控制台消息 logger.log('message1', 'message2') - 与 console.log 完全一样。 logger.warn('message1', 'message2') - 与 console.warn 完全一样。 logger.error('message1', 'message2') - 与 console.error 完全一样。 编码愉快..

【讨论】:

以上是关于如何快速方便地禁用我的代码中的所有 console.log 语句?的主要内容,如果未能解决你的问题,请参考以下文章

如何以编程方式禁用 C# 控制台应用程序的快速编辑模式?

如何使用 jQuery 禁用 div 或 table 中的所有元素

如何根据另一个参数的值有条件地禁用 Storybook 中的控件?

Qt:QVideoWidget 不显示并禁用应用程序中的所有按钮或极大地减慢应用程序的速度

快速禁用 UIScrollView 中的垂直滚动?

如果不需要填写所有输入,如何禁用按钮?