Pytest 日志记录忽略 pytest.ini 中的选项

Pytest logging ignores options in pytest.ini

我有一个测试我是运行:

pytest --capture=no --verbose --rootdir=testing/ testing/tests/docker_test.py

来自 /home/user/development/。该测试检查某些容器是否 运行 并使用 Python 3.6 的默认日志记录框架。测试文件里面的记录器配置如下:

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(asctime)s %(levelname)s %(message)s")

内部测试我使用记录器如下:

logger.info(f"TEST SUCCESSFUL: container {container_name} is running")
logger.info(f"TEST SUCCESSFUL: all required containers are running")

里面testing(根目录)我有一个文件pytest.ini:

[pytest]
log_level = INFO
log_cli_level = INFO
log_format = %(asctime)s %(levelname)s %(message)s
log_cli_format = %(asctime)s %(levelname)s %(message)s
log_date_format = %H:%M:%S
log_cli_date_format = %H:%M:%S

基本上我不希望任何日期出现在时间戳中,我希望 pytest 在我 运行 测试时实时记录到命令行。

一方面,我想知道 asctime 代表什么。看起来像 "ascii time"。我不想要标准化的时间戳,而是我在 pytest.ini 中描述的格式。这就是为什么我也尝试使用 datedatetimetimestamp 而不是 asctime,所有这些都会导致错误。所以我想 asctime 是获得时间戳的唯一方法。

然而,pytest 似乎忽略了我在我的 pytest.ini 文件中设置的所有选项,尽管表明它找到了文件,当我 运行 测试时:

cachedir: testing/.pytest_cache
rootdir: /home/user/development/testing, inifile: pytest.ini

如何更改 pytest 日志记录中的时间戳?

我猜你缺少的是 pytest.ini 中的 log_cli = 1(或 true/yes/等)。除此之外,使用您提供的配置,日志记录以您在 log_cli_format 中指定的格式打印。您甚至可以将 pytest.ini 减少为:

[pytest]
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s %(levelname)s %(message)s
log_cli_date_format = %H:%M:%S

此外,上述配置将负责测试会话中的根记录器配置,因此您不需要在测试中为实时记录配置记录器。只需在测试中调用记录器:

import logging

def test_spam():
    logger = logging.getLogger(__name__)
    logger.info('spam')
    logger.warning('eggs')
    logger.error('bacon')

这将打印:

$ pytest
============================== test session starts ================================
platform linux -- Python 3.6.5, pytest-3.4.1, py-1.5.3, pluggy-0.6.0 -- /data/gentoo64/usr/bin/python3.6
cachedir: .pytest_cache
rootdir: /data/gentoo64/home/u0_a82/projects/Whosebug/so-50677656, inifile: pytest.ini
plugins: mock-1.6.3, cov-2.5.1, flaky-3.4.0
collected 1 item

testing/tests/test_docker.py::test_logs
---------------------------------- live log call ----------------------------------
16:29:12 INFO spam
16:29:13 WARNING eggs
16:29:13 ERROR bacon
PASSED                                                                       [100%]
============================ 1 passed in 1.08 seconds =============================

For one I am wondering what asctime stands for

logging docs 对此有点简洁:

Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).

但是,asctime 并不意味着记录将始终使用 time.asctime - it's only the default datetime format used when you don't pass your own to the logging.Formatter (second argument in the formatter constructor) 格式化。