Log milliseconds with pytest

Viewed 700

Goal

Show milliseconds on the logging output of pytest.

Things I tried

pytest documentation pretends to use time.strftime compatible strings for logging, so I cannot use the %f format for microseconds as with datetime.strftime

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 ===

What I don't understand

The pytest log_cli_format documents

Sets a logging-compatible string used to format live logging messages.

However, by default the logging utility logs %(asctime)s with milliseconds

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).

Question

Is there any easy solution to show milliseconds? The way the logging package does by default? Does it have to be hacky?

1 Answers

Even if pytest overwrites the default date format for logging, the extra %(msecs)d from the LogRecords attributes seems to be there for that kind of problem exactly.

pytest.ini

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

output

$ 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 ===
Related