python logging 默认级别_python logging 毫秒级别的时间打印

为查看代码性能需毫秒级打印,因Python的time包无毫秒datefmt,所以重写logging中取时间的函数。在datefmt为None时,用datetime包中的时间替代,实例化Formater时使用该类并设置datefmt为None即可。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要查看代码性能,所以需要毫秒级别的打印。但是,在logging包中,查了源码之后确认使用的是time包的datefmt。而查看Python的doc文档,在time包中并没有提供毫秒的datefmt,所以,只能重写logging中取时间的函数。如下:

class Formatter(logging.Formatter):

def formatTime(self, record, datefmt=None):

"""

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which

wants to make use of a formatted time. This method can be overridden

in formatters to provide for any specific requirement, but the

basic behaviour is as follows: if datefmt (a string) is specified,

it is used with time.strftime() to format the creation time of the

record. Otherwise, the ISO8601 format is used. The resulting

string is returned. This function uses a user-configurable function

to convert the creation time to a tuple. By default, time.localtime()

is used; to change this for a particular formatter instance, set the

'converter' attribute to a function with the same signature as

time.localtime() or time.gmtime(). To change it for all formatters,

for example if you want all logging times to be shown in GMT,

set the 'converter' attribute in the Formatter class.

"""

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)

s = str(datetime.datetime.now())

return s

此处,在datefmt为None的时候,使用datetime包中的时间替代。

之后,只要在实例化Formater的时候使用该类,并设置datefmt为None即可。

formatter = Formatter(fmt, datefmt=None)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值