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.

Easy Python 3.9+ Aug 9, 2026 Observability & SRE 13 views 0 copies

Python code

11 lines
Python 3.9+
import 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

stdout
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

  1. Set `logging.basicConfig(level=logging.WARNING)` to suppress DEBUG and INFO messages
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Observability & SRE

Related tutorials and quizzes for this topic.