Sub topic 10
Rotating log files
This chapter assumes you can create a logger, attach a handler and a formatter, and know that a handler has its own level. If FileHandler is new to you, review the earlier chapter on handlers first.
Why a log file needs rotation
A plain FileHandler appends to one file forever. On a long-running service, that file eventually fills the disk, becomes too large to open in an editor, and is slow to search. Rotation fixes this by closing the current file at a chosen moment and starting a new one. Old files are renamed and, after a limit, deleted.
The logging.handlers module provides two main handlers for this:
RotatingFileHandlerrotates by file size.TimedRotatingFileHandlerrotates by clock time.
A third, WatchedFileHandler, does not rotate anything itself. It cooperates with an external tool such as logrotate. All three are covered below.
Size-based rotation with RotatingFileHandler
RotatingFileHandler takes a file name, maxBytes, and backupCount. When writing the next record would push the file past maxBytes, the handler rotates.
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 rotation works like this:
app.log.2is renamed toapp.log.3.app.log.1is renamed toapp.log.2.app.logis renamed toapp.log.1.- A new, empty
app.logis opened.
The oldest file, which would become app.log.4, is deleted. The newest records are always in app.log, and a higher suffix means older data. The total disk use is therefore bounded by roughly maxBytes * (backupCount + 1).
Watching it happen
You can see rotation on a small scale by choosing a tiny maxBytes. This script runs as shown.
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
handler = RotatingFileHandler(
"demo.log", maxBytes=200, backupCount=2, encoding="utf-8"
)
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
logger = logging.getLogger("demo")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
for i in range(20):
logger.info("Message number %d", i)
handler.close()
print(sorted(p.name for p in Path(".").glob("demo.log*")))Each line is about 23 bytes, so a file holds roughly eight lines. The script prints ['demo.log', 'demo.log.1', 'demo.log.2']. The earliest messages are gone because only two backups are kept.
Settings that surprise people
- If
maxBytesis0, the file never rotates. This is the default, so forgetting the argument gives you an ordinaryFileHandler. - If
backupCountis0, the file also never rotates, even whenmaxBytesis set. Rotation needs somewhere to put the old file, so usebackupCount=1or more. maxBytesis measured in bytes of the encoded text, so passencodingexplicitly. Otherwise the platform's default encoding is used, and the same message can have different sizes on different machines.- The size check happens before each write, so a single record larger than
maxBytesstill ends up written whole in a file of its own.
Time-based rotation with TimedRotatingFileHandler
Time-based rotation suits logs you want to find by date, such as "what happened on Tuesday". The handler takes when and interval.
import logging
from logging.handlers import TimedRotatingFileHandler
handler = TimedRotatingFileHandler(
"app.log", when="midnight", backupCount=7, encoding="utf-8", utc=True
)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("A new file starts at midnight UTC and 7 old files are kept")The common values of when are listed here.
| `when` | Meaning |
|---|---|
| `"S"`, `"M"`, `"H"`, `"D"` | Every `interval` seconds, minutes, hours, or days |
| `"midnight"` | Every day at midnight, or at `atTime` if you pass a `datetime.time` |
| `"W0"` to `"W6"` | Weekly, on a weekday (0 is Monday) |
Rotated files get a date suffix, for example app.log.2026-11-25, instead of a number. The suffix is derived from when, so a handler that rotates every hour uses a suffix with the hour in it. Here backupCount=7 means the handler keeps the seven newest dated files and deletes older ones. If backupCount is 0, nothing is ever deleted.
Pass utc=True unless you have a reason not to. Without it, the handler uses local time, and the rotation moments shift when daylight saving changes. Servers in different time zones also then produce files that do not line up.
A subtle point is that the rotation time is computed when the handler is created, and it is checked only when a record is emitted. If no message arrives for three days, the file is rotated when the next message arrives, not at midnight. The old file then contains the date of the rotation moment, not the date of the data inside it.
Compressing rotated files
Both handlers let you customize what happens to the old file through two attributes, namer and rotator. The namer changes the name of the rotated file. The rotator does the actual move. This example compresses each rotated file with gzip.
import gzip
import logging
import os
import shutil
from logging.handlers import RotatingFileHandler
def namer(name):
return name + ".gz"
def rotator(source, dest):
with open(source, "rb") as f_in, gzip.open(dest, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(source)
handler = RotatingFileHandler(
"app.log", maxBytes=1_000_000, backupCount=5, encoding="utf-8"
)
handler.namer = namer
handler.rotator = rotator
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Old files are stored as app.log.1.gz, app.log.2.gz, and so on")The handler shifts files with the same namer, so the numbered chain becomes app.log.1.gz, app.log.2.gz, and so on. Compression runs inside the logging call that triggers rotation, so that one call is slow for large files. If that matters, combine this with the queue-based setup from a later chapter.
Rotation and multiple processes
Rotation assumes one writer. Each handler keeps its own open file and its own idea of the file size. If two processes write to the same app.log with RotatingFileHandler, you can get these failures:
- Process A renames the file, but process B keeps writing into the renamed file through its open handle.
- Both processes try to rename
app.logtoapp.log.1and one of them overwrites the other's data. - On Windows, the rename fails with a
PermissionErrorbecause another process has the file open.
The standard library has no safe fix for this inside the handlers. The usual solutions are:
- Give each process its own log file, for example by including the process ID in the file name.
- Send records from all processes to one process that owns the file, for example with
QueueHandlerorSocketHandler. - Write to standard output and let the platform (systemd, Docker, Kubernetes) collect and rotate the output.
Rotation done by another tool
On Linux, logrotate is often already managing log files. It renames app.log from the outside, and a Python process that keeps writing to its old file handle would write into the renamed file. WatchedFileHandler solves this by checking, before each write, whether the file at the path still has the same device and inode. If it changed, the handler closes and reopens the path.
import logging
from logging.handlers import WatchedFileHandler
handler = WatchedFileHandler("app.log", encoding="utf-8")
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Reopens app.log if logrotate moves it")This handler is meant for Unix-like systems. On Windows, files cannot be renamed while open, so it does not apply.
Choosing a handler
| Situation | Handler |
|---|---|
| Single process, want to cap disk use | `RotatingFileHandler` |
| Single process, want one file per day | `TimedRotatingFileHandler` |
| `logrotate` manages the file | `WatchedFileHandler` |
| Several processes write logs | One writer process fed by a queue, or per-process files |
| Container or managed platform | `StreamHandler` to stdout, no file at all |
Common mistakes
- Creating the handler twice, for example by running setup code on every import. Each handler opens the file, and records are written more than once.
- Forgetting to call
handler.close()orlogging.shutdown()in short scripts and tests. Open handles stop you from deleting the files on Windows. - Expecting
backupCountto count days withTimedRotatingFileHandlerwhenwhen="H". It counts files, so seven files hold seven hours. - Relative file names.
"app.log"resolves against the current working directory, which differs between a terminal and a service manager. Use an absolute path in production.
Exercise
A service uses RotatingFileHandler("svc.log", maxBytes=5000000, backupCount=4). Roughly how much disk can its logs use at most, and which file holds the newest records? Then explain why the same service, started with maxBytes=5000000 but no backupCount argument, will eventually fill the disk.
Show answer
At most about 25 MB, which is maxBytes (backupCount + 1) = 5 MB 5. The newest records are in svc.log, and svc.log.1 through svc.log.4 hold progressively older data. The default backupCount is 0, and when it is 0 rotation never happens, so the handler keeps appending to one file and the maxBytes limit is ignored.
Exercise
You run four gunicorn worker processes that all log through a RotatingFileHandler to /var/log/app.log. After a rotation some log lines are missing. What is the cause, and name two ways to fix it?
Show answer
Each worker has its own handler with its own open file and size count, so they rename and write to the file without coordinating. A worker may keep writing to a file that another worker has already renamed. Fixes: give each worker its own file (for example by including the process ID in the name), or send all records to one process through a QueueHandler or SocketHandler, or log to stdout and let the platform collect and rotate the output.