What's the difference between when='D'
and when='midnight'
for TimedRotatingFileHandler
in python logging module?
I can't get it from the official document.
There are two relevant parameters to TimedRotatingFileHandler
: when
, and interval
. Most of the possible values for when
, such as D
for days, or H
for hours, work in conjunction with interval
—for example, if when='D', interval=7
were specified, then the log would be rotated every seven days. Similarly, if when='H', interval=12
were specified, then the log would be rotated every twelve hours, starting when the script is launched. when='midnight'
is a special case, in that the interval
parameter is not used, and the log is rolled over on a daily basis at midnight, regardless of the time when the script is launched (see the source here).
To expand Kurt Raschke's answer and Brownnightingale's coment:
You can even combine the when="midnight"
parameter with interval
and from python 3.4 you can even use new parameter atTime
, so you can rotate the log every other day (when='d', interval=2
), every other midnight (when='midnight', interval=2
) or every other time of day, e.g. noon (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)))
which will output something like this:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With