如何管理日志

pytest 会自动捕获级别为 WARNING 或更高级别的日志消息,并像捕获 stdout 和 stderr 一样,在每个失败测试的单独部分中显示它们。

不带选项运行

pytest

显示失败的测试如下

----------------------- Captured stdlog call ----------------------
test_reporting.py    26 WARNING  text going to logger
----------------------- Captured stdout call ----------------------
text going to stdout
----------------------- Captured stderr call ----------------------
text going to stderr
==================== 2 failed in 0.02 seconds =====================

默认情况下,每个捕获的日志消息都会显示模块、行号、日志级别和消息。

如果需要,可以通过传递特定的格式化选项,将日志和日期格式指定为 logging 模块支持的任何格式

pytest --log-format="%(asctime)s %(levelname)s %(message)s" \
        --log-date-format="%Y-%m-%d %H:%M:%S"

显示失败的测试如下

----------------------- Captured stdlog call ----------------------
2010-04-10 14:48:44 WARNING text going to logger
----------------------- Captured stdout call ----------------------
text going to stdout
----------------------- Captured stderr call ----------------------
text going to stderr
==================== 2 failed in 0.02 seconds =====================

这些选项也可以通过配置文件进行自定义

[pytest]
log_format = "%(asctime)s %(levelname)s %(message)s"
log_date_format = "%Y-%m-%d %H:%M:%S"
[pytest]
log_format = %(asctime)s %(levelname)s %(message)s
log_date_format = %Y-%m-%d %H:%M:%S

特定的记录器(logger)可以通过 --log-disable={logger_name} 禁用。此参数可以多次传递

pytest --log-disable=main --log-disable=testing

此外,可以在测试失败时完全禁止报告捕获的内容(stdout、stderr 和日志),使用

pytest --show-capture=no

caplog 夹具

在测试内部,可以更改捕获日志消息的日志级别。这由 caplog 夹具支持

def test_foo(caplog):
    caplog.set_level(logging.INFO)

默认情况下,级别是在根记录器(root logger)上设置的,但为方便起见,也可以设置任何记录器的日志级别

def test_foo(caplog):
    caplog.set_level(logging.CRITICAL, logger="root.baz")

设置的日志级别会在测试结束时自动恢复。

也可以使用上下文管理器在 with 块内临时更改日志级别

def test_bar(caplog):
    with caplog.at_level(logging.INFO):
        pass

同样,默认情况下会影响根记录器的级别,但也可以使用以下方式更改任何记录器的级别

def test_bar(caplog):
    with caplog.at_level(logging.CRITICAL, logger="root.baz"):
        pass

最后,测试运行期间发送给记录器的所有日志在夹具中均可用,形式为 logging.LogRecord 实例和最终的日志文本。这在您想要对消息内容进行断言时非常有用

def test_baz(caplog):
    func_under_test()
    for record in caplog.records:
        assert record.levelname != "CRITICAL"
    assert "wally" not in caplog.text

有关日志记录的所有可用属性,请参阅 logging.LogRecord 类。

如果您只需要确保在给定的记录器名称下记录了具有特定严重性和消息的某些消息,也可以使用 record_tuples

def test_foo(caplog):
    logging.getLogger().info("boo %s", "arg")

    assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]

您可以调用 caplog.clear() 来重置测试中捕获的日志记录

def test_something_with_clearing_records(caplog):
    some_method_that_creates_log_records()
    caplog.clear()
    your_test_method()
    assert ["Foo"] == [rec.message for rec in caplog.records]

caplog.records 属性仅包含当前阶段的记录,因此在 setup 阶段它仅包含设置日志,callteardown 阶段也同理。

要访问其他阶段的日志,请使用 caplog.get_records(when) 方法。举个例子,如果您想确保使用某个夹具的测试从不记录任何警告,您可以在拆卸(teardown)期间检查 setupcall 阶段的记录,如下所示

@pytest.fixture
def window(caplog):
    window = create_window()
    yield window
    for when in ("setup", "call"):
        messages = [
            x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
        ]
        if messages:
            pytest.fail(f"warning messages encountered during testing: {messages}")

完整 API 请见 pytest.LogCaptureFixture

警告

caplog 夹具会向根记录器添加一个处理程序以捕获日志。如果根记录器在测试期间被修改(例如使用 logging.config.dictConfig),此处理程序可能会被移除,从而导致无法捕获日志。为避免这种情况,请确保任何根记录器配置仅添加到现有处理程序中。

实时日志(Live Logs)

通过将 log_cli 配置选项设置为 true,pytest 会在日志记录发出时直接将其输出到控制台。

您可以通过传递 --log-cli-level 来指定打印到控制台的日志记录的最低级别。此设置接受如 logging 文档 中所示的日志级别名称或数值。

此外,您还可以指定 --log-cli-format--log-cli-date-format,它们在未提供时默认与 --log-format--log-date-format 镜像,但仅应用于控制台日志处理程序。

所有 CLI 日志选项也可以在配置文件中设置。选项名称为

如果您需要将整个测试套件的日志记录调用保存到文件,可以传递 --log-file=/path/to/log/file。此日志文件默认以写模式打开,这意味着它会在每次测试会话中被覆盖。如果您希望以追加模式打开文件,则可以传递 --log-file-mode=a。请注意,无论是在 CLI 上传递还是在配置文件中声明,日志文件位置的相对路径始终相对于当前工作目录解析。

您还可以通过传递 --log-file-level 来指定日志文件的记录级别。此设置接受如 logging 文档 中所示的日志级别名称或数值。

此外,您还可以指定 --log-file-format--log-file-date-format,它们等同于 --log-format--log-date-format,但应用于日志文件处理程序。

所有日志文件选项也可以在配置文件中设置。选项名称为

您可以调用 set_log_path() 来动态自定义 log_file 路径。此功能被视为 实验性 的。请注意,set_log_path() 会遵循 log_file_mode 选项。

自定义颜色

如果启用了彩色终端输出,日志级别将会着色。通过 add_color_level() 支持更改默认颜色或为自定义日志级别设置颜色。示例

@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    logging_plugin = config.pluginmanager.get_plugin("logging-plugin")

    # Change color on existing log level
    logging_plugin.log_cli_handler.formatter.add_color_level(logging.INFO, "cyan")

    # Add color to a custom log level (a custom log level `SPAM` is already set up)
    logging_plugin.log_cli_handler.formatter.add_color_level(logging.SPAM, "blue")

警告

此功能及其 API 被视为 实验性 的,可能会在不同版本间发生更改,恕不另行通知。

发布说明

此功能作为 pytest-catchlog 插件的直接替代品引入,它们之间存在冲突。在引入此功能时,与 pytest-capturelog 的向后兼容 API 已被移除,因此如果您仍然需要 pytest-catchlog,可以通过在配置文件中添加以下内容来禁用内置功能

[pytest]
addopts = ["-p", "no:logging"]
[pytest]
addopts = -p no:logging

pytest 3.4 中的不兼容更改

此功能是在 3.3 中引入的,在收到社区反馈后,在 3.4 中进行了一些 不兼容的更改

  • 除非通过 log_level 配置或 --log-level 命令行选项明确要求,否则不再更改日志级别。这允许用户自行配置记录器对象。设置 log_level 将设置全局捕获的级别,因此如果某个特定的测试需要比这更低的级别,请使用 caplog.set_level() 功能,否则该测试容易失败。

  • 实时日志 默认禁用,可以通过将 log_cli 配置选项设置为 true 来启用。启用后,详细程度会增加,以便每个测试的日志可见。

  • 实时日志 现在发送到 sys.stdout,不再需要 -s 命令行选项即可工作。

如果您想部分恢复 3.3 版本的日志记录行为,可以在配置文件中添加这些选项

[pytest]
log_cli = true
log_level = "NOTSET"
[pytest]
log_cli = true
log_level = NOTSET

关于导致这些更改的讨论的更多详细信息,请参阅 #3013