python - 正确使用 nullHandler 禁用来自特定包的日志消息

标签 python logging configuration-files

我想停止外部模块来淹没我的日志文件,就像这个问题一样: Disable logging for a particular package 受答案启发的配置文件如下。我用的是python3.2

我的问题是,它不起作用:“handlers=nullHandler”行引发了这个:

Traceback (most recent call last):
  File "./tree_browser", line 44, in <module>
    logging.config.fileConfig('../log/logging.conf')
  File "/usr/lib/python3.2/logging/config.py", line 79, in fileConfig
    _install_loggers(cp, handlers, disable_existing_loggers)
  File "/usr/lib/python3.2/logging/config.py", line 202, in _install_loggers
    log.addHandler(handlers[hand])
KeyError: 'nullHandler'

而且我找不到使用这个 nullHandler 的方法。 配置文件是:

[loggers]
keys=root,RPIO

[handlers]
keys=fileHandler

[formatters]
keys=defaultFormatter

[logger_root]
level=DEBUG
handlers=fileHandler

[logger_RPIO]
level=NOTSET
handlers=nullHandler
qualname=_RPIO.py
propagate=0

[handler_nullHandler]
class=NullHandler
level=DEBUG

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=defaultFormatter
filemode=w
args=('../log/pilberry_core.log',)

[formatter_defaultFormatter]
format=%(asctime)s %(filename)s: %(funcName)s: %(message)s
datefmt=%Y/%m/%d %H:%M:%S

其他失败的尝试:在不定义 [handler_nullHandler] 的情况下尝试,使用 nullHandler 或 NullHandler 作为格式化程序,它总是以同样的方式失败。

请注意,如果我禁用 RPIO_logger(通过从 [loggers] 键部分中删除 RPIO),则其余部分可以正常工作。

那么,使用 nullHandler 的正确方法是什么?

最佳答案

在您的handlers部分中,您只列出fileHandler。因此,当您读取该配置时,它会构建一个仅包含 fileHandlerhandlers 字典。因此,当您尝试使用 nullHandler 时,您会收到 KeyError,因为它不在字典中。

我猜这是一个简单的拼写错误,但如果不是,请参阅 Configuration file format在文档中:

The file must contain sections called [loggers], [handlers] and [formatters] which identify by name the entities of each type which are defined in the file. For each such entity, there is a separate section which identifies how that entity is configured.

换句话说,仅具有 handler_nullHandler 部分不会创建名为 nullHandler 的处理程序;在 handlers 部分中包含 keys=...,nullHandler,... 即可实现此目的。

关于python - 正确使用 nullHandler 禁用来自特定包的日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25227854/

相关文章:

java - 如何在 IntelliJ 中快速输入记录器定义?

java - 调试日志记录不适用于特定处理程序

design-patterns - 哪些设计模式可以应用于配置设置问题?

security - Service Fabric 配置磁盘位置

ruby-on-rails - 使用 capistrano 和 svn 部署 rails 时,您将 app-config-files 放在哪里

Python 更新函数内的值并重用它

python - Pandas ,在字符串中打印变量

python - 如何将两个训练有素的神经网络权重矩阵合并为一个?

python - 大型 python tornado 项目的最佳结构是什么?

c# - 从执行反向 P/Invoke 的函数返回时发生访问冲突