How to quickly and conveniently disable all console.log statements in my code?(如何快速方便地禁用我的代码中的所有 console.log 语句?)
问题描述
有什么方法可以关闭我的 JavaScript 代码中的所有 console.log
语句以进行测试?
Is there any way to turn off all console.log
statements in my JavaScript code, for testing purposes?
推荐答案
在脚本中重新定义 console.log 函数.
Redefine the console.log function in your script.
console.log = function() {}
就是这样,没有更多消息要控制台.
That's it, no more messages to console.
扩展 Cide 的想法.一个自定义记录器,您可以使用它来从您的代码中切换登录/关闭.
Expanding on Cide's idea. A custom logger which you can use to toggle logging on/off from your code.
从我的 Firefox 控制台:
From my Firefox console:
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!');
}
);
如何使用上面的记录器"?在您的就绪事件中,调用 logger.disableLogger 以便不记录控制台消息.在要将消息记录到控制台的方法中添加对 logger.enableLogger 和 logger.disableLogger 的调用.
How to use the above 'logger'? In your ready event, call logger.disableLogger so that console messages are not logged. Add calls to logger.enableLogger and logger.disableLogger inside the method for which you want to log messages to the console.
这篇关于如何快速方便地禁用我的代码中的所有 console.log 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何快速方便地禁用我的代码中的所有 console.l


基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01