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


当前回答

在其他答案的基础上,我个人希望只关闭代码的特定部分(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而不是字符串处理程序,并在当前使用的文件中切换调试模式。

其他回答

我认为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?

这是来自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');
});

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

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

警告:无耻的插头!

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

http://jstrace.codeplex.com

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

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

你可以这样改变它们:

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

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

T

据我从文档中得知,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);
    }
}