In this lesson, you will learn how to automatically append persistent identifiers, such as request IDs or user sessions, to every log entry without manually updating every log.info() call in your code.
The Problem of Isolated Logs
When debugging a complex application, a log message like "Database query failed" is often useless because it doesn't tell you who triggered the query or which specific web request caused the error. If you manually pass user_id into every log statement, your code becomes cluttered and prone to human error.
Using logging.LoggerAdapter
A LoggerAdapter acts as a wrapper around your standard logger. It allows you to define "contextual" data once and automatically inject it into every log record produced by that adapter.
import logging
# Set up a basic logger
logger = logging.getLogger("app")
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s | User: %(user_id)s')
# Create an adapter with context
user_context = {"user_id": "user_123"}
adapter = logging.LoggerAdapter(logger, user_context)
# Now, every log call includes the user_id automatically
adapter.info("Processing payment")
adapter.info("Database connection closed")
Filtering for Dynamic Context
While an adapter is great for static context, what if you need to track something that changes per request, like a unique request_id? You can use a logging.Filter to inject data dynamically into every log record as it passes through the system. By attaching a filter to your logger or handler, you can reach into the record object and add custom attributes on the fly.
Whenever you need to track a transaction across multiple function calls, simply set that ID in your filter, and your entire application will automatically "tag" every log line with that identifier until the task is complete. This keeps your business logic clean while ensuring your logs provide the full story of what happened during a specific user interaction.
Key Takeaway: Use LoggerAdapter for persistent context and logging.Filter for dynamic metadata to ensure every log entry provides the essential background information needed for effective debugging.