TimedRotatingFileHandler
在Python日志模块中,when='D'
和when='midnight'
有什么区别?
我从官方文档中无法理解。
TimedRotatingFileHandler
在Python日志模块中,when='D'
和when='midnight'
有什么区别?
我从官方文档中无法理解。
TimedRotatingFileHandler
有关的参数: when
和 interval
。 对于when
的大部分可能值(例如,D
表示天,H
表示小时),都需要和interval
一起使用。 例如,如果指定了when='D', interval=7
,则日志将每七天轮换一次。 同样地,如果指定了when='H',interval=12
,则日志将每隔十二小时轮换一次,从启动脚本时开始计算。 特殊情况是when='midnight'
,此时不使用interval
参数,并且日志会在每天午夜定期滚动,无论脚本启动的时间是什么(请参见此处源代码)。扩展Kurt Raschke的回答和Brownnightingale的评论:
你甚至可以将when="midnight"
参数与interval
结合使用,而且从Python 3.4开始,你甚至可以使用新参数atTime
,这样你就可以每隔一天旋转日志 (when='d', interval=2
),每个午夜旋转日志(when='midnight', interval=2
)或每个白天的其他时间,例如正午(when='midnight', interval=2, atTime=datetime.time()
):
import datetime
import logging.handlers
import time
noon = datetime.time(hour=12)
handler = logging.handlers.TimedRotatingFileHandler(
filename='daily.log',
when='d',
interval=2)
handler_midnight = logging.handlers.TimedRotatingFileHandler(
filename='daily.log',
when='midnight',
interval=2)
handler_noon = logging.handlers.TimedRotatingFileHandler(
filename='daily.log',
when='midnight',
atTime=noon,
interval=2)
current_time = int(time.time())
rollover_time = handler.computeRollover(current_time)
rollover_time_midnight = handler_midnight.computeRollover(current_time)
rollover_time_noon = handler_noon.computeRollover(current_time)
print('current time: {}'.format(datetime.datetime.fromtimestamp(current_time)))
print('next log rotation: {}'.format(datetime.datetime.fromtimestamp(rollover_time)))
print('next midnight log rotation: {}'.format(datetime.datetime.fromtimestamp(rollover_time_midnight)))
print('next noon log rotation: {}'.format(datetime.datetime.fromtimestamp(rollover_time_noon)))
current time: 2020-03-11 14:22:32
next log rotation: 2020-03-13 14:22:32
next midnight log rotation: 2020-03-12 00:00:00
next noon log rotation: 2020-03-12 12:00:00