1

I am setting up python logger using config. I want log file to contain date (and possibly time). I also want for that date, each log file to be of only particular size and to keep only 3 such old log files.

For example, I will like to get log files of following form:

mylog-2018-09-11.log
mylog-2018-09-11.log.1
mylog-2018-09-11.log.2
mylog-2018-09-11.log.3

I tried RotatingFileHandler using config of following form as explained here:

config = {
    #...
    'handlers': {
        'file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'mplog.log',
            'mode': 'w',
            'formatter': 'detailed',
            'maxBytes': 10000,
            'backupCount': 3
        },
    },
    #...
}
logging.config.dictConfig(config)

and it produces log files as follows:

mylog.log
mylog.log.1
mylog.log.2
mylog.log.3

But I am unable to understand, how can I get date in the log file names. Is it possible to do it with configs and with some handler say RotatingFileHandler or TimeRotatingFileHandler? Or say can I somehow set the log file name to contain date after dictConfig() call?

Mahesha999
  • 22,693
  • 29
  • 116
  • 189

1 Answers1

0

Your example shows a RotatingFileHandler which rotates files based on size rather than date. You need to use TimedRotatingFileHandler as documented here. You can configure it in the same way as you have done RotatingFileHandler.

Update: If you want to restrict both by date and size, you will need to use a handler subclass which does exactly what you want.

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
  • Are you sure? `maxBytes` is present in the arguments of [`RotatingFileHandler`](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.RotatingFileHandler), but is not present in [`TimedRotatingFileHandler`](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) – Mahesha999 Sep 18 '18 at 13:08
  • When I said "in the same way", I meant "in the same _general_ way", not "_exactly_ the same way". – Vinay Sajip Sep 18 '18 at 19:33
  • Sorry not still able understand. What do you mean by "handler subclass"? I have to write custom one? Any link? – Mahesha999 Sep 19 '18 at 10:56
  • [...continued] also does [this](https://stackoverflow.com/a/45447081/1317018) answer suggest that its not possible? – Mahesha999 Sep 19 '18 at 11:33
  • Sorry, no link (I don't think it's a common requirement). Yes, you have to write custom code, and it _is_ possible if you know what you want to achieve. – Vinay Sajip Sep 19 '18 at 15:09