【问题标题】:Log milliseconds with pytest使用 pytest 记录毫秒数
【发布时间】:2020-09-07 17:42:15
【问题描述】:

目标

pytest 的日志输出上显示毫秒数。

我尝试过的事情

pytest 文档伪装成use time.strftime 兼容字符串进行日志记录,所以我不能像datetime.strftime 那样使用%f 格式的微秒数

pytest.ini

[pytest]
log_cli = True
log_cli_format = %(asctime)s %(levelname)s %(message)s
log_cli_level = DEBUG
#log_cli_date_format = %H:%M:%S:%f

test_this.py

import logging

def test_me():
  logging.info('something')
$ python3 -m pytest
==== test session starts ====
[...]

test_this.py::test_me
----- live log call -----
19:18:10 INFO something
PASSED                                                                                                                          [100%]

=== 1 passed in 0.01s ===

我不明白的地方

pytestlog_cli_format documents

设置一个logging兼容的字符串,用于格式化实时日志消息。

但是,默认情况下,logging utility 以毫秒为单位记录 %(asctime)s

创建日志记录时的人类可读时间。默认情况下,格式为“2003-07-08 16:49:45,896”(逗号后面的数字是时间的毫秒部分)。

问题

有没有简单的解决方案来显示毫秒?日志包默认的方式是什么?它必须是hacky吗?

【问题讨论】:

    标签: python logging pytest


    【解决方案1】:

    即使 pytest 覆盖了默认的日志记录日期格式,LogRecords attributes 中的额外 %(msecs)d 似乎也正是针对此类问题的。

    pytest.ini

    [pytest]
    log_cli = True
    log_cli_format = %(asctime)s.%(msecs)03d %(levelname)s %(message)s
    log_cli_level = DEBUG
    

    输出

    $ python3 -m pytest
    ==== test session starts ====
    [...]
    
    test_this.py::test_me
    ----- live log call -----
    19:56:57.249 INFO something
    PASSED                                                                                                                          [100%]
    
    === 1 passed in 0.01s ===
    

    【讨论】:

    • 谢谢!不过,我会使用%(msecs)03d。这样,5 ms 而不是 249 ms 将打印为 19:56:57.005,而不是 19:56:57.5
    猜你喜欢
    • 2013-07-27
    • 2011-09-11
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2015-10-17
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多