Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between "when='D' " and "when='midnight'" for TimedRotatingFileHandler?

Tags:

python

logging

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.

like image 752
dae Avatar asked Feb 17 '16 03:02

dae


2 Answers

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).

like image 132
Kurt Raschke Avatar answered Oct 18 '22 23:10

Kurt Raschke


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
like image 39
Vojtech Sokol Avatar answered Oct 18 '22 22:10

Vojtech Sokol