Django Request ID

1.0.0 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

To quickly integrate `django-request-id`, add `request_id.middleware.RequestIDMiddleware` to your `MIDDLEWARE` setting. Crucially, configure your Django `LOGGING` settings to include `request_id.logging.RequestIDFilter` and apply it to your desired log handlers. Also, ensure your log formatters include `{request_id}` to display the unique ID.

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')

view raw JSON →