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


当前回答

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

特点:

它会安全地覆盖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而不是字符串处理程序,并在当前使用的文件中切换调试模式。

我这样写道:

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

嘿~让我们用现代的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添加了一个保护,而不是猴子补丁。它是安全的。

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

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