Python日志记录:以毫秒为单位的时间格式 [英] Python logging: use milliseconds in time format

查看:970
本文介绍了Python日志记录:以毫秒为单位的时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,logging.Formatter('%(asctime)s')使用以下格式打印:

By default logging.Formatter('%(asctime)s') prints with the following format:

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

其中638是毫秒.我需要将逗号更改为点:

where 638 is the millisecond. I need to change the comma to a dot:

2011-06-09 10:54:40.638

设置时间格式:

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

但是文档没有指定毫秒格式.我发现此SO问题谈论微秒,但是a)我更喜欢毫秒,并且b)由于%f,以下内容在Python 2.6(我正在开发的)上不起作用:

however the documentation doesn't specify how to format milliseconds. I've found this SO question which talks about microseconds, but a) I would prefer milliseconds and b) the following doesn't work on Python 2.6 (which I'm working on) due to the %f:

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

推荐答案

请注意,克雷格·麦克丹尼尔(Craig McDaniel)的解决方案是显然更好.

Please note Craig McDaniel's solution is clearly better.

logging.Formatter的formatTime方法如下所示:

logging.Formatter's formatTime method looks like this:

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不能解决此问题,因为cttime.struct_time,并且这些对象不记录毫秒.

Notice the comma in "%s,%03d". This can not be fixed by specifying a datefmt because ct is a time.struct_time and these objects do not record milliseconds.

如果我们更改ct的定义以使其成为datetime对象而不是struct_time,则(至少在现代版本的Python中)我们可以调用ct.strftime,然后可以使用设置微秒格式:

If we change the definition of ct to make it a datetime object instead of a struct_time, then (at least with modern versions of Python) we can call ct.strftime and then we can use %f to format microseconds:

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参数:


Or, to get milliseconds, change the comma to a decimal point, and omit the datefmt argument:

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.

这篇关于Python日志记录:以毫秒为单位的时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆