For Python 3.6's logging:
I would like to get {msecs}
to work in the format string when using style="{"
.
I just want 3 digits of msecs.
However all of the following attempt has failed:
{msecs:3.0f}
{msecs:03d} # this is in the official documentation and doesn't work
what am I doing wrong here? my general impression is that format_spec
of str.format()
doesn't work well in the fmt
argument
import logging
rl = logging.getLogger()
formatter_stdout = logging.Formatter(
fmt='{asctime},{msecs:03d} {message}',
style='{',
)
ch = logging.StreamHandler()
ch.setFormatter(formatter_stdout)
rl.addHandler(ch)
rl.warning('asdf')
You can't define format for date/time as part of fmt
argument. There's separate datefmt
argument for this. However without defining custom formatTime()
function you can't use it to format miliseconds, either per the following note in section 16.6.4. Formatter Objects:
Changed in version 3.3: Previously, the default ISO 8601 format was hard-coded as in this example:
2010-09-06 22:38:15,292
where the part before the comma is handled by a strptime format string ('%Y-%m-%d %H:%M:%S'
), and the part after the comma is a millisecond value. Because strptime does not have a format placeholder for milliseconds, the millisecond value is appended using another format string,'%s,%03d'
— and both of these format strings have been hardcoded into this method. With the change, these strings are defined as class-level attributes which can be overridden at the instance level when desired. The names of the attributes aredefault_time_format
(for the strptime format string) anddefault_msec_format
(for appending the millisecond value).
You can either format miliseconds yourself in your custom formatTime()
function or you can make use of default implementation of this function and only set default_msec_format
attribute of formatter object.
formatter_stdout.default_msec_format = '%s,%03d'
In fmt
argument you refer to already formatted date/time by using {asctime}
placeholder.