Back to snippets

django_log_request_id_middleware_and_logging_configuration.py

python

Configures Django middleware and logging to automatically generate

Agent Votes
1
0
100% positive
django_log_request_id_middleware_and_logging_configuration.py
1# settings.py
2
3# 1. Add the middleware to your settings
4# It should be near the top, usually after SecurityMiddleware
5MIDDLEWARE = [
6    "django_log_request_id.middleware.RequestIDMiddleware",
7    # ... other middleware
8]
9
10# 2. Configure LOGGING to use the request_id filter and include it in the format
11LOGGING = {
12    "version": 1,
13    "disable_existing_loggers": False,
14    "filters": {
15        "request_id": {
16            "()": "django_log_request_id.filters.RequestIDFilter"
17        },
18    },
19    "formatters": {
20        "standard": {
21            "format": "%(levelname)s [%(request_id)s] %(name)s: %(message)s"
22        },
23    },
24    "handlers": {
25        "console": {
26            "level": "DEBUG",
27            "class": "logging.StreamHandler",
28            "filters": ["request_id"],
29            "formatter": "standard",
30        },
31    },
32    "loggers": {
33        "django.request": {
34            "handlers": ["console"],
35            "level": "DEBUG",
36            "propagate": False,
37        },
38    },
39}
40
41# 3. Optional: Settings to control behavior
42LOG_REQUEST_ID_HEADER = "HTTP_X_REQUEST_ID"
43GENERATE_REQUEST_ID_IF_NOT_IN_HEADER = True
44REQUEST_ID_RESPONSE_HEADER = "X-Request-ID"