Python日志:在时间格式中使用毫秒

280 投票
17 回答
178752 浏览
提问于 2025-04-16 19:14

默认情况下,logging.Formatter('%(asctime)s') 打印的时间格式是这样的:

2011-06-09 10:54:40,638

其中的638是毫秒。我需要把逗号改成点:

2011-06-09 10:54:40.638

为了格式化时间,我可以使用:

logging.Formatter(fmt='%(asctime)s',datestr=date_format_str)

不过,文档里没有说明怎么格式化毫秒。我找到了一些讨论微秒的问题,但是a) 我更想要毫秒,b) 下面的代码在我用的Python 2.6上不管用,因为有%f

logging.Formatter(fmt='%(asctime)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')

17 个回答

69

加上毫秒是个更好的选择,谢谢。这里是我在Blender中使用Python 3.5.3进行的修改。

import logging

logging.basicConfig(level=logging.DEBUG, 
    format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
log = logging.getLogger(__name__)
log.info("Logging Info")
log.debug("Logging Debug")
95

请注意,除非你需要支持所有的ISO 8601格式代码,否则Craig McDaniel的解决方案更好。


logging.Formatter的formatTime方法看起来是这样的:

def formatTime(self, record, datefmt=None):
    ct = self.converter(record.created)
    if datefmt:
        s = time.strftime(datefmt, ct)
    else:
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        s = "%s,%03d" % (t, record.msecs)
    return s

注意到"%s,%03d"中的逗号。这个问题不能通过指定datefmt来解决,因为ct是一个time.struct_time对象,而这些对象并不记录毫秒。

如果我们把ct的定义改成datetime对象,而不是struct_time,那么(至少在现代版本的Python中)我们可以调用ct.strftime,这样就可以使用%f来格式化微秒:

import logging
import datetime as dt

class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s,%03d" % (t, record.msecs)
        return s

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler()
logger.addHandler(console)

formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')
console.setFormatter(formatter)

logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.

或者,如果想要毫秒,可以把逗号改成小数点,并且省略datefmt参数:

class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s.%03d" % (t, record.msecs)
        return s

...
formatter = MyFormatter(fmt='%(asctime)s %(message)s')
...
logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.
530

这个方法也应该可以用:

logging.Formatter(
    fmt='%(asctime)s.%(msecs)03d',
    datefmt='%Y-%m-%d,%H:%M:%S'
)

撰写回答