Python日志记录:覆盖日志时间 [英] Python logging: override log time
本文介绍了Python日志记录:覆盖日志时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
按照 Python的文档,我正在尝试覆盖logging.Formatter.converter
以控制记录的时间.
如下所示-毫秒未覆盖(它们是当前时间毫秒).
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
推荐答案
使用以下方法覆盖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
如果在此过程中所有记录器都需要它,则可以覆盖类函数本身,但是可以在代码遇到的第一个import logging
语句之后立即执行此操作:
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
这篇关于Python日志记录:覆盖日志时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文