是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?
当前回答
我这样写道:
//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)来启用它
其他回答
我认为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?
https://stackoverflow.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() {};
}
在其他答案的基础上,我个人希望只关闭代码的特定部分(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而不是字符串处理程序,并在当前使用的文件中切换调试模式。
嘿~让我们用现代的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
如果你正在使用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 /” ) ); });
推荐文章
- 如何通过参数和重定向stdin从一个文件到程序运行在gdb?
- 右击是Javascript事件吗?
- 如何找到JavaScript数组中包含的最大数字?
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)