Eden
Eden

Reputation: 1120

How to use RotatingFileHandler with the root logger

I configure the root logger:

logging.basicConfig(filename='logfile.log', level=logging.DEBUG)

Then I put log messages in my code like this:

logging.debug("This is a log message")

Question: How do I add a RotatingFileHandler such that my logs will be rotated?

Note: I do not want a logger instance which I then have to pass around everywhere.

Upvotes: 0

Views: 372

Answers (1)

blues
blues

Reputation: 5185

You can do this by using the handlers kwarg of basicConfig. Be aware that this needs to be an iterable and you can not use the filename argument together with it.

import logging
import logging.handlers

rot_handler = logging.handlers.RotatingFileHandler('filename.txt')
logging.basicConfig(level=logging.DEBUG, handlers=[rot_handler])

Link to relevant part of documentation: https://docs.python.org/3/library/logging.html#logging.basicConfig

Upvotes: 2

Related Questions