Python 如何从其他模块禁用记录器?
我在我的项目中使用了几个模块,但是,这些模块从记录器输出大量日志,这很烦人。因此,我通过以下方式关闭日志:Python 如何从其他模块禁用记录器?,python,logging,Python,Logging,我在我的项目中使用了几个模块,但是,这些模块从记录器输出大量日志,这很烦人。因此,我通过以下方式关闭日志: boto_log = logging.getLogger("boto") boto_log.setLevel(logging.CRITICAL) es_log = logging.getLogger("elasticsearch") es_log.setLevel(logging.CRITICAL) urllib3_log = logging.getLogger("urllib3") ur
boto_log = logging.getLogger("boto")
boto_log.setLevel(logging.CRITICAL)
es_log = logging.getLogger("elasticsearch")
es_log.setLevel(logging.CRITICAL)
urllib3_log = logging.getLogger("urllib3")
urllib3_log.setLevel(logging.CRITICAL)
虽然这样做有效,但代码看起来很冗长。是否有更好、更简单的方法可以做到这一点?可能是您可以重构它,以便剪切一些样板文件:
for _ in ("boto", "elasticsearch", "urllib3"):
logging.getLogger(_).setLevel(logging.CRITICAL)
您可以使用
logging.config.dictConfig
或logging.config.fileConfig
禁用现有记录器
import logging.config
logging.config.dictConfig({
'version': 1,
# Other configs ...
'disable_existing_loggers': True
})
您还可以在现有记录器上循环并手动禁用
for name, logger in logging.root.manager.loggerDict.iteritems():
logger.disabled=True
您应该确切地知道应该进行除盐的记录器的名称<代码>“urllib3.connectionpool”!=“urllib3”
您可以从
logging.root.manager.loggerDict
获取所有记录器(不包括根记录器)的列表
for _ in logging.root.manager.loggerDict:
logging.getLogger(_).setLevel(logging.CRITICAL)
# logging.getLogger(_).disabled = True # or use this instead of CRITICAL if you'd rather completely disable it
这使您可以灵活地放入自己的过滤器等,如果您希望保留一些日志记录程序。因此,我仍然需要自己迭代所有使用日志记录程序的模块?可能有人想出了更好的方法,但至少这不是很详细。我会说“显式优于隐式”,所以我认为显式禁用我想要禁用的日志(而不是自动禁用并因此丢失一些重要消息)不是一个坏主意。看起来是清晰性和易用性之间的一个很好的折衷。“显式优于隐式”我同意这一点:)
for _ in logging.root.manager.loggerDict:
logging.getLogger(_).setLevel(logging.CRITICAL)
# logging.getLogger(_).disabled = True # or use this instead of CRITICAL if you'd rather completely disable it