-->
Written by: Marlon Colca
Posted on 02 May 2025 - 13 days ago
python logging loguru
Now it's time to take logging seriously
After your first logger.info("Hello world")
, it’s time to take logging seriously.
In this post, we’ll cover how to configure rotation, retention, compression, and how to combine console + file logging effectively for real-world use cases.
from loguru import logger
logger.add("app.log")
logger.info("Starting the application")
But that doesn’t scale. In production, you need to control:
How large your logs can grow.
How long to keep them.
How to archive them.
Where to send them.
logger.add("app.log", rotation="10 MB")
Or rotate daily:
logger.add("app.log", rotation="00:00") # Every midnight
Automatically delete old logs:
logger.add("app.log", rotation="10 MB", retention="7 days")
Or keep just the last 5 files:
logger.add("app.log", rotation="10 MB", retention=5)
If you’re storing logs, compress them to save space:
logger.add("app.log", rotation="100 MB", retention="10 days", compression="zip")
Also supports "gz"
, "tar"
, etc.
Send different log levels to different outputs:
logger.add(sys.stderr, level="INFO") # Only INFO+ to console
logger.add("debug.log", level="DEBUG") # Full details to file
from loguru import logger
import sys
logger.remove() # Clear default handlers
logger.add(
"app.log",
rotation="10 MB",
retention="10 days",
compression="zip",
level="DEBUG"
)
logger.add(sys.stderr, level="INFO")
import os
level = "DEBUG" if os.getenv("ENV") == "dev" else "INFO"
logger.add("app.log", level=level, rotation="5 MB", retention="7 days")
Loguru makes it easy to set up a production-grade logging system in just a few lines. You get power and simplicity, without the headache of configuring the standard logging module.
👉 Structured logging with Loguru for ELK and other observability tools
When you're sending logs to ELK, Datadog, or any log aggregator, plain text isn't enough.