如何禁用其他模块的记录器?

shi*_*eng 8 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")
urllib3_log.setLevel(logging.CRITICAL)
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但代码看起来很冗长.有没有更好,更简单的方法可以做到这一点?

Leo*_*o.Z 8

您可以使用logging.config.dictConfig或禁用现有的记录器logging.config.fileConfig

import logging.config
logging.config.dictConfig({
    'version': 1,
    # Other configs ...
    'disable_existing_loggers': True
})
Run Code Online (Sandbox Code Playgroud)

您还可以遍历现有记录器并手动禁用。

for name, logger in logging.root.manager.loggerDict.iteritems():
    logger.disabled=True
Run Code Online (Sandbox Code Playgroud)


fan*_*ous 7

您可以从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
Run Code Online (Sandbox Code Playgroud)

如果您希望实际保留一些记录器,这使您可以灵活地放入自己的过滤器等。


Pau*_*ine 6

也许你可以重构它以削减一些样板:

for _ in ("boto", "elasticsearch", "urllib3"):
    logging.getLogger(_).setLevel(logging.CRITICAL)
Run Code Online (Sandbox Code Playgroud)

  • 有人可能想出了更好的方法,但至少这不是那么冗长。我会说“显式比隐式更好”,所以我认为明确禁用我想要禁用的日志并不是一个坏主意(而不是自动执行并因此丢失一些重要消息)。看起来在清晰度和易用性之间取得了很好的折衷。 (3认同)