Excellent question! This is a cornerstone of writing robust Python applications.
The undisputed "most popular" logging package in Python is the one built right into the language: the logging module.
1. The Standard Library: logging
This is, by far, the most widely used logging solution in the Python ecosystem.
Basic Example:
import logging
# Basic configuration: log to the console at the INFO level
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# In a library, you would typically do this:
logger = logging.getLogger(__name__)
logger.info("This is an informational message.")
logger.warning("This is a warning message.")
logger.error("An error occurred!", exc_info=True) # exc_info=True adds traceback info
2. Popular Modern Alternatives
While logging is the standard, its verbosity has led to the rise of popular third-party libraries designed for a better developer experience, especially in applications (as opposed to libraries).
The two most popular alternatives are Loguru and structlog.
Loguru
Tagline: "Python logging made simple."
Loguru is incredibly popular for its ease of use and sensible defaults. It aims to take the pain out of logging.
- Why people love it:
- Zero-Configuration Setup: You can import it and start using it immediately with colorful, well-formatted output.
- Better Tracebacks: On an exception, it automatically prints a much more readable traceback, showing the values of variables in the stack.
- Effortless File Logging: Rotating files, compressing old logs, and setting retention policies is trivial.
- "Sane" by Default: It just works out of the box in a way most developers would want.
Loguru Example:
# pip install loguru
from loguru import logger
# No configuration needed for console logging!
logger.info("This is an informational message from Loguru.")
logger.warning("This is a warning.")
# Effortless file logging
logger.add("file_{time}.log", rotation="500 MB") # Rotates when the file reaches 500 MB
logger.error("This will go to the console AND the file.")
# Example of its excellent exception logging
try:
result = 1 / 0
except ZeroDivisionError:
logger.exception("What a mess!")
structlog
Tagline: "Structured Logging for Python."
structlog is the go-to choice when your primary concern is structured logging. This means your logs are intended to be easily parsed by machines (like log aggregators such as Splunk, Datadog, or the ELK stack).
- Why people love it:
- Machine-Readable Output: It excels at producing logs as key-value pairs, typically in JSON format.
- Processing Pipeline: You configure a pipeline of processors that add context (e.g., timestamp, log level, request ID) to your log entries in a structured way.
- Framework Integration: It has excellent support for integrating with web frameworks like Django and Flask to automatically add request-specific context.
- Plays Nicely with Others: It can be configured to use the standard
logging module as its final output, so you get the benefits of both.
structlog Example:
# pip install structlog
import structlog
# Basic configuration to output JSON
structlog.configure(
processors=[
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer(),
]
)
log = structlog.get_logger()
log.info("user.logged_in", user_id=123, user_email="test@example.com")
log.error("payment.failed", order_id="abc-456", reason="insufficient_funds")
Output would look like:
{"event": "user.logged_in", "user_id": 123, "user_email": "test@example.com", "level": "info", "timestamp": "2023-10-27T10:30:00.123456Z"}
{"event": "payment.failed", "order_id": "abc-456", "reason": "insufficient_funds", "level": "error", "timestamp": "2023-10-27T10:30:01.234567Z"}
Summary: Which one should you use?
| Library | Best For | Key Strength |
|---|
logging | Libraries, large/complex applications, environments where external dependencies are forbidden. | The Standard. Universal compatibility and ultimate flexibility. |
Loguru | Applications, scripts, and projects where developer experience and readability are top priorities. | Simplicity. "Logging for humans" with amazing defaults. |
structlog | Applications that feed into log analysis platforms (Splunk, Datadog, etc.). Microservices. | Structured Data. "Logging for machines" with a clean, extensible pipeline. |