1

我在我的项目中使用 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.")
4

1 回答 1

0

您可以在https://www.structlog.org/en/stable/testing.html中找到有关 structlog 测试功能的文档

捕获部分可以使用capture_logs(上下文管理器)或使用CapturingLogger(较低级别)来完成。

要获取发射记录器的名称,请确保添加add_logger_name处理器。

于 2021-07-05T17:48:38.887 回答