objectif
Configurer un logger avec rotation par taille et format horodaté.
code minimal
import logging, logging.handlers, tempfile, pathlib
log_path = pathlib.Path(tempfile.gettempdir()) / "app.log"
handler = logging.handlers.RotatingFileHandler(log_path, maxBytes=1024, backupCount=3, encoding="utf-8")
fmt = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
handler.setFormatter(fmt)
logger = logging.getLogger("app")
logger.setLevel(logging.INFO)
logger.handlers = [handler]
logger.info("hello")
logger.info("world")
exists_and_nonempty = log_path.exists() and log_path.stat().st_size > 0
print(exists_and_nonempty) # attendu: True
utilisation
import logging
logging.getLogger("app").info("ligne")
print(True)
variante(s) utile(s)
import logging
console = logging.StreamHandler()
console.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logging.getLogger("app").addHandler(console)
print(isinstance(console, logging.Handler))
notes
- backupCount contrôle le nombre de fichiers gardés.
- Configurez le logger une seule fois au démarrage.