gpt4 book ai didi

Python 库默认 NullHandler 在单元测试时导致错误

转载 作者:行者123 更新时间:2023-12-01 00:49:11 25 4
gpt4 key购买 nike

我正在尝试为我正在编写的 api 库设置默认记录器。 Python 文档指出在库中设置一个 NullHandler,然后让使用该库的开发人员确定应如何处理日志记录。

Note It is strongly advised that you do not add any handlers other than NullHandler to your library’s loggers. This is because the configuration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers ‘under the hood’, you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements.

https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial

import logging
logging.getLogger('foo').addHandler(logging.NullHandler())

因此,对于像 myapi.py 这样的模块,我可能有:

log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler)

class MyApi: ...

然后在单元测试文件中,我将设置实际的日志处理程序。

import logging
log = logging.getLogger('myapi')
log.handlers = []
log.addHandler(logging.StreamHandler(sys.stdout))
log.setLevel(logging.DEBUG)

class MyApiTests(unittest.TestCase): ...

我遇到的问题是 NullHandler 在运行单元测试时会导致出现错误消息。

  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1590, in callHandlers
if record.levelno >= hdlr.level:
AttributeError: type object 'NullHandler' has no attribute 'level'

我已经尝试了多种方法来消除该错误。首先,我尝试删除现有的处理程序;日志处理程序 = []。这似乎并没有带来任何改变。我还尝试设置日志级别; log.setLevel(日志记录.DEBUG)。我仍然收到错误。

我一定错过了什么。谁能解释如何删除 NullHandler 或防止错误消息?

最佳答案

这是因为您将类而不是实例添加到处理程序列表中。

log.addHandler(logging.NullHandler)

应该是

log.addHandler(logging.NullHandler())

关于Python 库默认 NullHandler 在单元测试时导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56709525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com