Size-Based Log File Rotation
Configure Python logging with a rotating file handler that caps file size, keeps numbered backups, and flushes each record.
Code
import logging
import shutil
from logging.handlers import RotatingFileHandler
from pathlib import Path
def build_logger(
path: str, *, max_bytes: int = 1_000_000, backups: int = 3
) -> logging.Logger:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
logger = logging.getLogger("demo.rotation")
logger.setLevel(logging.INFO)
logger.propagate = False
if not logger.handlers:
handler = RotatingFileHandler(
target, maxBytes=max_bytes, backupCount=backups, encoding="utf-8"
)
handler.setFormatter(
logging.Formatter("%(asctime)s %(levelname)s %(message)s")
)
logger.addHandler(handler)
return logger
if __name__ == "__main__":
log = build_logger("build/logs/app.log", max_bytes=300, backups=2)
for index in range(12):
log.info("request %d completed", index)
for handler in log.handlers:
handler.flush()
handler.close()
log.handlers.clear()
files = sorted(path.name for path in Path("build/logs").glob("app.log*"))
print("files:", files)
print("latest:", Path("build/logs/app.log").read_text(encoding="utf-8").splitlines()[-1])
shutil.rmtree("build")
How it works
Everything happens inside the function build_logger.
Iteration happens inside for index in range(12) — everything outside it runs once. From logging it pulls RotatingFileHandler, Path — the imports name exactly which library surface the snippet touches.
What to watch for
- Plan for an install step:
loggingis a real dependency, resolved by the package manager.
Using it
The primary signature is def build_logger( path: str, *, max_bytes: int = 1_000_000, backups: int = 3 ) -> logging.Logger
Output lines are prefixed (files:, latest:), making each step’s effect easy to spot.
Key statements
def build_logger(
path: str, *, max_bytes: int = 1_000_000, backups: int = 3
) -> logging.Logger:
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does this require external packages?
- Yes — `logging`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.