python 使用 {} 样式记录毫秒格式

python logging msecs format with {} style

对于 Python 3.6 的日志记录:

我想让 {msecs} 在使用 style="{" 时在格式字符串中工作。 我只想要 3 位数的毫秒数。 然而,以下所有尝试都失败了:
{msecs:3.0f}
{msecs:03d} # this is in the official documentation and doesn't work
我在这里做错了什么?我的总体印象是 str.format()format_specfmt 参数

中效果不佳
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')

您不能将 date/time 的格式定义为 fmt 参数的一部分。为此有单独的 datefmt 参数。但是,如果不定义自定义 formatTime() 函数,则不能使用它来格式化毫秒,或者根据 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 are default_time_format (for the strptime format string) and default_msec_format (for appending the millisecond value).

您可以在您的自定义 formatTime() 函数中自己格式化毫秒,或者您可以使用此函数的默认实现并仅设置格式化程序对象的 default_msec_format 属性。

formatter_stdout.default_msec_format = '%s,%03d'

fmt 参数中,您通过使用 {asctime} 占位符引用 已格式化 date/time。

这个有效:

fmt='{asctime}.{msecs:03.0f} …'

不确定为什么它使用浮点数表示毫秒,但确实如此。