How to Use Log Levels DEBUG INFO WARNING ERROR in Python
Demonstrates Python's logging levels (DEBUG, INFO, WARNING, ERROR) with basicConfig and a logger, showing how severity filtering controls output.
Python code
11 linesimport logging
# Configure a mock logger to demonstrate log levels
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
logger = logging.getLogger("mock_logger")
# Simulate events at each severity level
logger.debug("Detailed diagnostic info")
logger.info("General system operation")
logger.warning("Potential issue detected")
logger.error("Operation failed")
Output
DEBUG: Detailed diagnostic info
INFO: General system operation
WARNING: Potential issue detected
ERROR: Operation failed
How it works
The logging.basicConfig call sets the root logger's level to DEBUG and defines a format that prefixes each message with its level name. logger.debug, logger.info, logger.warning, and logger.error map to the four severity levels. Because the threshold is DEBUG, all messages at DEBUG and above are emitted to the console. Each Logger object in Python is hierarchical; getLogger("mock_logger") creates a child of the root logger and inherits its configuration. The output shows how levels let you filter noisy diagnostics from production.
Common mistakes
- Setting the level on a child logger only, not root, causing unexpected filtering
- Using `print()` for logging, losing level filtering and structured output
- Forgetting that `basicConfig` does nothing if a handler already exists
Variations
- Set `logging.basicConfig(level=logging.WARNING)` to suppress DEBUG and INFO messages
- Use `logger.log(logging.INFO, "message")` for dynamic level selection
Real-world use cases
- Setting log levels to DEBUG in development and WARNING in production to keep noise down.
- In a data pipeline, logging ERROR for failed batches and INFO for successful ones.
- Sending WARNING and ERROR logs to a monitoring service like Sentry for alerting.
Sponsored
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Check if a Timestamp Falls in a Daily Maintenance Window in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
Keep learning
Related tutorials and quizzes for this topic.