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


当前回答

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

其他回答

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

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

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

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

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

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

这里引用一下:

“使用严格的”; (() => { Var控制台=(窗口。控制台=窗口。控制台|| {}); [ “维护”、“清楚”、“数”、“调试”,“dir”、“dirxml”, "error", "exception", "group", " groupcollapse ", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time" "timeEnd" "timeStamp" "trace" "warn" ]。forEach(方法=> { Console [method] = () => {}; }); 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?

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