Python日志记录:覆盖日志时间
作者:互联网
在Python’s documentation之后,我试图覆盖logging.Formatter.converter以控制记录的时间.如下所示 – 毫秒未被覆盖(它们是当前时间毫秒).
怎么会?我怎样才能控制毫秒?
>>> 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
解决方法:
覆盖logging.Formatter.formatTime()而不是:
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
如果在此过程中需要所有记录器,则可以覆盖类函数本身,但在代码遇到的第一个导入日志记录语句之后立即执行此操作:
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
标签:python,time,simulation,logging,milliseconds 来源: https://codeday.me/bug/20190626/1293078.html