Django Log Request ID
django-log-request-id is a Django middleware and log filter that automatically attaches a unique request ID to every log message generated as part of a web request. This greatly simplifies tracing and debugging in complex or distributed systems by allowing all related log entries for a single request to be easily correlated. The current version is 2.1.2, and the library maintains an active release cadence with frequent updates.
Warnings
- breaking Version 2.0.0 removed the `requests.Session` passthrough functionality. Code relying on this feature will break when upgrading to 2.0.0 or later.
- gotcha The `RequestIDMiddleware` should be placed as high as possible in your `MIDDLEWARE` tuple, ideally at the very top, to ensure the request ID is available for all subsequent middleware and application logic. Incorrect placement may result in logs from earlier middleware not containing the request ID.
- gotcha Prior to version 2.1.0, logging user attributes via `LOG_USER_ATTRIBUTE` could inadvertently cause the session to be touched, potentially leading to unwanted side effects like setting a `Vary` header. Version 2.1.0 introduced `LOG_USER_ATTRIBUTE = None` to explicitly prevent user attribute logging and avoid session interaction.
- breaking Version 1.7.0 dropped support for older, unsupported Django versions. Upgrading to 1.7.0 or later with an outdated Django installation may lead to incompatibilities and errors.
- gotcha If you rely on external systems (e.g., load balancers, proxies) to provide a request ID via a custom header, ensure your `LOG_REQUEST_ID_HEADER` setting in Django is correctly configured. The header name must conform to Django's `request.META` key format (e.g., `HTTP_X_REQUEST_ID` for an `X-Request-ID` header).
Install
-
pip install django-log-request-id
Imports
- RequestIDMiddleware
from log_request_id.middleware import RequestIDMiddleware
- RequestIDFilter
from log_request_id.filters import RequestIDFilter
Quickstart
import logging
# settings.py
# Add to MIDDLEWARE. It should be at the very top.
MIDDLEWARE = [
'log_request_id.middleware.RequestIDMiddleware',
# ... other middleware
]
# Configure LOGGING
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'request_id': {
'()': 'log_request_id.filters.RequestIDFilter'
}
},
'formatters': {
'standard': {
'format': '[%(asctime)s] [%(levelname)s] [%(request_id)s] %(name)s: %(message)s'
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard',
'filters': ['request_id']
}
},
'loggers': {
'': {
'handlers': ['console'],
'level': 'INFO',
'propagate': True
},
'django': {
'handlers': ['console'],
'level': 'INFO',
'propagate': False
}
}
}
# In your application code (e.g., views.py)
logger = logging.getLogger(__name__)
logger.info("This log message will include the request ID.")