是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?
当前回答
在对这个问题做了一些研究和开发之后,我遇到了这个解决方案,它将根据您的选择隐藏警告/错误/日志。
(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本身的。
谢谢! !
其他回答
你可以使用javascript AOP(例如jquery-aop)来拦截所有对console.debug/log的调用,如果某个全局变量被设置为false,就不进行实际的调用。
您甚至可以(不时地)执行ajax调用,这样就可以更改服务器上启用/禁用日志的行为,当在登台环境或类似环境中遇到问题时启用调试,这可能非常有趣。
我的全面解决方案禁用/覆盖所有控制台。*函数在这里。
当然,请确保在检查必要的上下文之后包含它。例如,只包含在产品版本中,它不会轰炸任何其他关键组件等。
这里引用一下:
“使用严格的”; (() => { Var控制台=(窗口。控制台=窗口。控制台|| {}); [ “维护”、“清楚”、“数”、“调试”,“dir”、“dirxml”, "error", "exception", "group", " groupcollapse ", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time" "timeEnd" "timeStamp" "trace" "warn" ]。forEach(方法=> { Console [method] = () => {}; }); console.log("此消息不应该在控制台日志中可见"); })();
我写了一个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);
}
}
描述:
Along with logger.enable and logger.disable you can use console.['log','warn','error'] methods as well using logger class. By using logger class for displaying, enabling or disabling messages makes the code much cleaner and maintainable. The code below shows you how to use the logger class: logger.disable() - disable all console messages logger.enable() - enable all console messages logger.log('message1', 'message2') - works exactly like console.log. logger.warn('message1', 'message2') - works exactly like console.warn. logger.error('message1', 'message2') - works exactly like console.error. Happy coding..
我为这个用例开发了一个库:https://github.com/sunnykgupta/jsLogger
特点:
它会安全地覆盖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)来启用它
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何在Visual c++中保持控制台窗口打开?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?