Python

logging.basicConfig with Rotating File

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A solid logging setup: rich format, rotating file handler so logs don't fill the disk, plus a console handler at a higher level so noisy DEBUG only goes to the file.
Python
Raw
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path

def setup_logging(log_dir: str = "logs", level: int = logging.INFO) -> None:
    Path(log_dir).mkdir(parents=True, exist_ok=True)

    fmt = logging.Formatter(
        "%(asctime)s %(levelname)-7s [%(name)s] %(message)s",
        datefmt="%Y-%m-%dT%H:%M:%S",
    )

    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    # File: everything, rotated at 5 MB × 3 backups
    fh = RotatingFileHandler(f"{log_dir}/app.log", maxBytes=5_000_000, backupCount=3)
    fh.setFormatter(fmt); fh.setLevel(logging.DEBUG); root.addHandler(fh)
    # Console: INFO and up only
    ch = logging.StreamHandler()
    ch.setFormatter(fmt); ch.setLevel(level); root.addHandler(ch)

setup_logging(level=logging.INFO)
log = logging.getLogger("myapp.startup")
log.info("Service started on port %d", 8080)
log.debug("This goes to file only")
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.