← retour aux snippets

logging: rotation avec RotatingFileHandler

Faire tourner les logs par taille en conservant un historique.

python logging #logging#rotation#files

objectif

Faire tourner les logs par taille en conservant un historique.

code minimal

import logging, logging.handlers, tempfile, pathlib

with tempfile.TemporaryDirectory() as tmp:
    log = pathlib.Path(tmp) / "app.log"
    h = logging.handlers.RotatingFileHandler(log, maxBytes=100, backupCount=2, encoding="utf-8")
    fmt = logging.Formatter("%(message)s")
    h.setFormatter(fmt)
    lg = logging.getLogger("app")
    lg.setLevel(logging.INFO)
    lg.addHandler(h)
    for i in range(50):
        lg.info("x"*5)
    h.flush(); h.close()
    files = list(log.parent.glob("app.log*"))
    print(len(files) >= 1)  # attendu: True

utilisation

import logging
logging.getLogger("demo").info("hello")
print(True)

variante(s) utile(s)

import logging, logging.handlers, tempfile, pathlib
with tempfile.TemporaryDirectory() as tmp:
    log = pathlib.Path(tmp) / "t.log"
    h = logging.handlers.TimedRotatingFileHandler(log, when="S", interval=1, backupCount=1, encoding="utf-8")
    h.close()
    print(True)

notes

  • RotatingFileHandler tourne à la taille; TimedRotatingFileHandler tourne au temps.
  • Configurez backupCount pour limiter le nombre de fichiers.