Structlog:如何测试由哪个处理程序发出的内容

2024-06-02 06:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在项目中使用structlog,我想(单元)测试哪个处理程序发出了哪个消息。有没有一种规范的方法可以做到这一点?我注意到pytest structlog,但在那里找不到任何这样的功能。或者我可以从stdlib/pytest中使用一些东西吗

假设我的最小示例如下所示

# implementation
import logging.handlers

import structlog

structlog.configure(
    wrapper_class=structlog.make_filtering_bound_logger(logging.NOTSET),
    context_class=dict,
    logger_factory=structlog.stdlib.LoggerFactory(),
    cache_logger_on_first_use=False,
)

h1 = logging.StreamHandler()
h1.setLevel(logging.ERROR)

h2 = logging.StreamHandler()
h2.setLevel(logging.DEBUG)

logging.root.addHandler(h1)
logging.root.addHandler(h2)


# test
import structlog

from dummy import minimal


def test_minimal(log):
    logger = structlog.getLogger()

    logger.warn("I am a warning.")
    logger.error("I am an error.")

    assert log.has("I am a warning.")
    assert log.has("I am an error.")

    # how to test what has been emitted by which handler?
    # assert not log.handler1.has("I am a warning.")

Tags: testimportlogpytestloggingerrorh2assert