如何管理日志

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.ini 文件进行自定义

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

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

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

此外,还可以通过以下方式完全禁用失败测试中捕获内容的报告 (stdout、stderr 和日志)

pytest --show-capture=no

caplog fixture

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

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

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

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 实例和最终日志文本的形式在 fixture 上可用。这在您想要断言消息内容时非常有用

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 阶段只包含 setup 日志,callteardown 阶段也是如此。

要访问其他阶段的日志,请使用 caplog.get_records(when) 方法。例如,如果您想确保使用特定 fixture 的测试永远不会记录任何警告,您可以在 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 fixture 会向根日志记录器添加一个处理程序以捕获日志。如果在测试期间修改了根日志记录器(例如使用 logging.config.dictConfig),此处理程序可能会被移除,导致无法捕获日志。为避免这种情况,请确保任何根日志记录器配置仅添加到现有处理程序中。

实时日志

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

您可以通过传递 --log-cli-level 来指定要打印到控制台的日志记录级别(等于或高于该级别的日志记录)。此设置接受日志级别名称或数字值,具体请参阅 logging 文档

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

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

  • log_cli_level

  • log_cli_format

  • log_cli_date_format

如果您需要将整个测试套件的日志调用记录到文件中,可以传递 --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,但应用于日志文件处理程序。

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

  • log_file

  • log_file_mode

  • log_file_level

  • log_file_format

  • log_file_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.ini 中添加以下内容来禁用内部功能

[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 版本的日志记录行为,可以将这些选项添加到您的 ini 文件中

[pytest]
log_cli=true
log_level=NOTSET

有关导致这些更改的讨论详情,请参阅 #3013