Sub topic 10
Rotating log files
This chapter assumes you can create a logger, attach a handler, and set a formatter. If those steps are new, review the chapters on handlers and formatters first.
Why rotate
A FileHandler appends forever. On a long-running service the file grows until it fills the disk, and a single huge file is hard to search or ship elsewhere. Rotation caps the size: when the current file is full, the handler renames it and starts a new one. Old files are deleted once the limit you set is reached.
Rotating by size
RotatingFileHandler, from logging.handlers, rotates when the file reaches maxBytes.
import logging
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler(
"app.log", maxBytes=1_000_000, backupCount=3, encoding="utf-8"
)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Rotates after about 1 MB and keeps 3 old files")The two key arguments:
maxBytesis the size at which rotation happens. A value of0means never rotate.backupCountis how many old files to keep. A value of0also means never rotate, because there is nowhere to put the old file.
When app.log is full, the handler shifts the files: app.log.2 becomes app.log.3, app.log.1 becomes app.log.2, and app.log becomes app.log.1. A fresh app.log is then opened. The oldest file beyond backupCount is deleted.
The total disk use is therefore bounded by roughly maxBytes * (backupCount + 1). With the values above that is about 4 MB.
Rotating by time
If you want one file per day instead, use TimedRotatingFileHandler.
import logging
from logging.handlers import TimedRotatingFileHandler
handler = TimedRotatingFileHandler(
"daily.log", when="midnight", backupCount=7, encoding="utf-8"
)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
logger = logging.getLogger("myapp.daily")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("A new file starts at midnight; 7 old files are kept")The when argument accepts values such as "S", "M", "H", "D", "midnight", and "W0" to "W6" for a weekday. Rotated files get a date suffix, for example daily.log.2026-11-25, instead of a number.
Common errors
- Multiple processes writing one file. Rotation renames the file, and each process has its own open handle and its own idea of the current size. Processes can rename each other's files or write to a file that was already rotated. The standard library does not support this safely. Use one process that owns the file, such as a
QueueListeneror a logging server, or send logs to a system service. - Forgetting
backupCount. The default is0, so a handler with onlymaxBytesnever rotates and the file keeps growing. - Adding the handler twice. If setup code runs on every import or request, each message is written several times. Configure handlers once, at startup.
- Relative paths.
"app.log"is resolved against the current working directory, which may differ between a terminal and a service manager. Use an absolute path for deployed code. - Rotation on Windows. Renaming fails if another process has the file open, for example an editor or a log viewer. Close those tools or log to a directory they do not watch.
Exercise
A handler is created with RotatingFileHandler("app.log", maxBytes=500_000, backupCount=2). Roughly how much disk space can the log files use at most, and which file holds the newest messages?
Show answer
About 1.5 MB (500,000 bytes times three files: app.log plus two backups). The newest messages are always in app.log. The oldest are in app.log.2, and anything older is deleted at the next rotation.
Exercise
You set maxBytes=1_000_000 but leave backupCount at its default. The log file reaches 5 MB. Why?
Show answer
The default backupCount is 0, which disables rotation, so the handler keeps appending to the same file. Set backupCount to 1 or more.