A bit of background:
The Python docs say:
In the case of
{}-formatting, you can specify formatting flags by placing them after the attribute name, separated from it with a colon. For example: a placeholder of{msecs:03d}would format a millisecond value of 4 as 004.
However, this does not work, since the logging record's msecs value is actually a float:
>>> record.msecs
275.38108825683594
so trying to use the example {} formatting in the docs raises a ValueError:
>>> f'{record.msecs:03d}'
*** ValueError: Unknown format code 'd' for object of type 'float'
Old-style %-formating with 03d works fine for a float:
>>> '%03d' % record.msecs
'275'
Based on the above findings, I used a float format specification in my logging definition, like this:
logging.basicConfig(
level=logging.INFO,
format="{asctime}.{msecs:0>3.0f} [{levelname:.1s}] {message}",
datefmt="%Y-%m-%d %H:%M:%S",
style="{",
)
which seemed to be working well, until I noticed this log entry:
2021-03-25 22:37:18.993 [I] ...
2021-03-25 22:37:18.997 [I] ...
2021-03-25 22:37:18.1000 [I] ...
2021-03-25 22:37:19.002 [I] ...
2021-03-25 22:37:19.004 [I] ...
which happens when the logging record's msecs float value is >= 999.5:
>>> t1 = 999.499999
>>> t2 = 999.5
>>> print(f"{t1:0>3.0f} {t2:0>3.0f}")
999 1000
Obviously I'd prefer .1000 to be logged as .000 (rounding without overflowing the 3-digit length) if there was a way to also increment the {asctime} part of the timestamp by a second. But I'd be fine with just logging .999 (truncating to int instead of rounding) since this overflow only happens a very small percent of the time, and for my purposes this logging isn't that critical.
Any way to do this, other than going back to old-style %-based formatting?