TimedRotatingFileHandler中"when='D' "和"when='midnight'"有什么区别?

8

TimedRotatingFileHandler在Python日志模块中,when='D'when='midnight'有什么区别?
我从官方文档中无法理解。


你在说什么?能否提供一些上下文信息? - AMACB
1
如果你喜欢 Kurt Raschke 的回答(就像你似乎喜欢,我也是),你应该将其标记为已接受的答案。 - Vinay Sajip
我不知道怎么做 @VinaySajip - dae
1
@dae 看这里:http://meta.stackexchange.com/a/23139 - Vinay Sajip
2个回答

25
存在两个与TimedRotatingFileHandler有关的参数: wheninterval。 对于when的大部分可能值(例如,D表示天,H表示小时),都需要和interval一起使用。 例如,如果指定了when='D', interval=7,则日志将每七天轮换一次。 同样地,如果指定了when='H',interval=12,则日志将每隔十二小时轮换一次,从启动脚本时开始计算。 特殊情况是when='midnight',此时不使用interval参数,并且日志会在每天午夜定期滚动,无论脚本启动的时间是什么(请参见此处源代码)。

3
可能我说错了,但在源代码中即使 "when='midnight'",间隔参数似乎仍然被使用。请参阅源代码:https://github.com/python/cpython/blob/c879ff247ae1b67a790ff98d2d59145302cd4e4e/Lib/logging/handlers.py#L246看起来午夜被视为“D”,但具有特定的午夜时间。 - Brown nightingale

3

扩展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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接