Django Request ID
django-request-id is a Python library for Django that augments each HTTP request with a unique ID, primarily for improved logging and tracing across services. It is currently at version 1.0.0 and maintains a stable release cadence, focusing on core functionality and compatibility with recent Django versions.
Common errors
-
ModuleNotFoundError: No module named 'request_id.middleware'
cause The `django-request-id` library is either not installed or the middleware path in `settings.py` is incorrect.fixInstall the library using `pip install django-request-id`. Verify that `request_id.middleware.RequestIDMiddleware` is correctly spelled and listed in your `settings.MIDDLEWARE`. -
Request ID not appearing in my Django logs
cause The `RequestIDFilter` is not correctly applied to your logging handler, or your formatter string does not include `{request_id}`.fixIn `settings.py`, ensure your `LOGGING` configuration includes a filter like `LOGGING['filters']['request_id'] = {'()': 'request_id.logging.RequestIDFilter'}`. Then, apply this filter to your handler, e.g., `LOGGING['handlers']['console']['filters'] = ['request_id']`. Finally, make sure your formatter `format` string contains `{request_id}`. -
AttributeError: 'LogRecord' object has no attribute 'request_id'
cause This error typically occurs if you're trying to access `record.request_id` within a custom logging filter or handler, but the `RequestIDFilter` (which adds this attribute) has not been applied to the `LogRecord`.fixEnsure that `request_id.logging.RequestIDFilter` is correctly configured and applied to the specific logging handler(s) that process the logs you are inspecting or modifying.
Warnings
- gotcha The request ID will not appear in your logs unless you explicitly configure the logging system to use `RequestIDFilter` and include `{request_id}` in your formatter strings.
- gotcha When integrating with upstream proxies or load balancers, be aware that `django-request-id` will use an existing `X-Request-ID` header if present. If you need it to always generate a new ID, you might need to ensure the header is not passed from the proxy or configure the proxy to override it.
- gotcha The default header used for injecting/extracting the request ID is `X-Request-ID`. If your infrastructure uses a different header name, you'll need to configure `REQUEST_ID_HEADER` and `REQUEST_ID_RESPONSE_HEADER` in your Django settings.
Install
-
pip install django-request-id
Imports
- RequestIDMiddleware
from django_request_id.middleware import RequestIDMiddleware
from request_id.middleware import RequestIDMiddleware
- RequestIDFilter
from django_request_id.logging import RequestIDFilter
from request_id.logging import RequestIDFilter
Quickstart
import os
# settings.py
# Add the middleware to your Django project
MIDDLEWARE = [
# ... other middleware (e.g., 'django.middleware.security.SecurityMiddleware')
'request_id.middleware.RequestIDMiddleware',
# ... other middleware (e.g., 'django.contrib.sessions.middleware.SessionMiddleware')
]
# Configure logging to include the request ID
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'request_id': {
'()': 'request_id.logging.RequestIDFilter'
}
},
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {request_id} {module} {process:d} {thread:d} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'filters': ['request_id'], # Apply the filter to a handler
'formatter': 'verbose',
}
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'INFO',
'propagate': True,
},
},
}
# Example usage in a Django view or signal (for testing, not part of quickstart setup itself)
# import logging
# logger = logging.getLogger(__name__)
# def my_view(request):
# logger.info('This message should have a request ID.')
# return HttpResponse('Hello world')