Zel*_*ahl 4 python logging pytest
我有一个正在运行的测试:
pytest --capture=no --verbose --rootdir=testing/ testing/tests/docker_test.py
Run Code Online (Sandbox Code Playgroud)
从/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")
Run Code Online (Sandbox Code Playgroud)
在内部测试中,我使用记录器如下:
logger.info(f"TEST SUCCESSFUL: container {container_name} is running")
logger.info(f"TEST SUCCESSFUL: all required containers are running")
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
基本上我不希望时间戳中包含任何日期,并且我希望 pytest 在运行测试时实时记录到命令行。
一方面,我想知道什么asctime代表。它看起来像“ascii 时间”。我不想要一个标准化的时间戳,而是我在pytest.ini. 这就是为什么我也尝试使用date,datetime和timestamp,而不是asctime,所有都导致错误。所以我想这asctime是获得时间戳的唯一方法。
但是,pytest 似乎忽略了我在我的pytest.ini文件中设置的所有选项,尽管表明它在我运行测试时找到了该文件:
cachedir: testing/.pytest_cache
rootdir: /home/user/development/testing, inifile: pytest.ini
Run Code Online (Sandbox Code Playgroud)
如何更改 pytest 日志记录中的时间戳?
我猜你缺少的是log_cli = 1(或true/ yes/etc)在你的pytest.ini. 除此之外,通过配置,您将获得日志记录以您在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
Run Code Online (Sandbox Code Playgroud)
此外,上面的配置将处理测试会话中的根记录器配置,因此您不需要在测试中配置记录器以进行实时日志记录。只需在测试中调用记录器:
import logging
def test_spam():
logger = logging.getLogger(__name__)
logger.info('spam')
logger.warning('eggs')
logger.error('bacon')
Run Code Online (Sandbox Code Playgroud)
这将打印:
$ 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/stackoverflow/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 =============================
Run Code Online (Sandbox Code Playgroud)
对于一个我想知道 asctime 代表什么
该日志文件是关于有点简洁:
创建 LogRecord 的人类可读时间。默认情况下,它的格式为“2003-07-08 16:49:45,896”(逗号后面的数字是时间的毫秒部分)。
但是,asctime并不意味着记录将始终使用格式化time.asctime- 它只是当您不将自己的日期时间格式传递给logging.Formatter(格式化程序构造函数中的第二个参数)时使用的默认日期时间格式。
| 归档时间: |
|
| 查看次数: |
1587 次 |
| 最近记录: |