Django Log Request ID

2.1.2 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

To integrate django-log-request-id, first add the `RequestIDMiddleware` to the top of your `MIDDLEWARE` setting. Then, define `RequestIDFilter` in your `LOGGING` configuration, and ensure your logging handlers use this filter and your formatters include `%(request_id)s` to display the unique ID.

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.")

view raw JSON →