python记录日志,Python日志记录:覆盖日志时间

Following Python's documentation, I'm trying to override logging.Formatter.converter in order to control the time logged.

As you can see below - the milliseconds were not overriden (they are the current time milliseconds).

How come? How can I control the milliseconds as well?

>>> import logging, datetime

>>> formatter = logging.Formatter('%(asctime)s:%(message)s')

>>> handler = logging.StreamHandler()

>>> handler.setFormatter(formatter)

>>> def sim_time(t):

... return datetime.datetime(2000,1,2,3,4,5,678).timetuple()

...

>>> formatter.converter = sim_time

>>> log = logging.getLogger('test')

>>> log.addHandler(handler)

>>> log.info('hi')

2000-01-02 03:04:05,898:hi

>>> log.info('hi')

2000-01-02 03:04:05,914:hi

>>> log.info('hi')

2000-01-02 03:04:05,434:hi

解决方案

override logging.Formatter.formatTime() instead with this:

def sim_time(record, datefmt=None):

return datetime.datetime(2000,1,2,3,4,5,678).strftime('%Y-%m-%d %H:%M:%S,%f')[:-3]

formatter.formatTime = sim_time

If you need it for all loggers in this process, you can override the class function itself, but do this right after the first import logging statement your code encounters:

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

return datetime.datetime(2000,1,2,3,4,5,678).strftime('%Y-%m-%d %H:%M:%S,%f')[:-3]

import logging

logging.Formatter.formatTime = sim_time

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值