是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?
当前回答
在我搜索了这个问题以及在我的cordova应用程序中尝试后,我只是想警告每个windows phone的开发者不要覆盖
console.log
因为应用程序在启动时会崩溃。
如果你幸运的话,它不会崩溃,但在商店中提交它会导致应用程序崩溃。
只是覆盖
window.console.log
如果你需要的话。
这在我的应用程序工作:
try {
if (typeof(window.console) != "undefined") {
window.console = {};
window.console.log = function () {
};
window.console.debug = function () {
};
window.console.info = function () {
};
window.console.warn = function () {
};
window.console.error = function () {
};
}
if (typeof(alert) !== "undefined") {
alert = function ()
{
}
}
} catch (ex) {
}
其他回答
在脚本中重新定义console.log函数。
console.log = function() {}
够了,不再给控制台发消息了。
编辑:
扩展了Cide的想法。一个自定义记录器,您可以使用它从代码中切换登录。
从我的Firefox控制台:
var logger = function()
{
var oldConsoleLog = null;
var pub = {};
pub.enableLogger = function enableLogger()
{
if(oldConsoleLog == null)
return;
window['console']['log'] = oldConsoleLog;
};
pub.disableLogger = function disableLogger()
{
oldConsoleLog = console.log;
window['console']['log'] = function() {};
};
return pub;
}();
$(document).ready(
function()
{
console.log('hello');
logger.disableLogger();
console.log('hi', 'hiya');
console.log('this wont show up in console');
logger.enableLogger();
console.log('This will show up!');
}
);
如何使用上面的“记录器”?在就绪事件中,调用记录器。disableLogger使控制台消息不被记录。向记录器添加调用。enabllogger和logger。在希望将消息记录到控制台的方法中的disableLogger。
我一直在用以下方法来处理这个问题:-
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");
我自己弄明白后发现了这个帖子。以下是我的解决方案:
const testArray = {
a: 1,
b: 2
};
const verbose = true; //change this to false to turn off all comments
const consoleLog = (...message) => {
return verbose ? console.log(...message) : null;
};
console.log("from console.log", testArray);
consoleLog("from consoleLog", testArray);
// use consoleLog() for the comments you want to be able to toggle.
我为这个用例开发了一个库:https://github.com/sunnykgupta/jsLogger
特点:
它会安全地覆盖console.log。 注意控制台是否不可用(哦,是的,你也需要考虑这个因素)。 存储所有日志(即使它们被抑制)以供以后检索。 处理主要控制台功能,如日志,警告,错误,信息。
是开放的修改,并将更新每当有新的建议。
据我从文档中得知,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);
}
}
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何在Visual c++中保持控制台窗口打开?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象