Timing Request Duration
A snippet showing how to measure request time using middleware.
# middleware.py
import time
import logging
logger = logging.getLogger(__name__)
class TimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start_time = time.perf_counter()
response = self.get_response(request)
duration = (time.perf_counter() - start_time) * 1000 # ms
logger.info(f"{request.method} {request.path} took {duration:.2f}ms")
response['X-Request-Duration-ms'] = f"{duration:.2f}"
return response
# settings.py
MIDDLEWARE = [
# ...
'your_app.middleware.TimingMiddleware',
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
# Example curl test
$ curl -i http://localhost:8000/
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
X-Request-Duration-ms: 12.34
...
Explanation:
- This middleware measures how long each request takes to process from start to finish.
-
Duration is logged to the console (via Django's logging) and also sent back in the response header
X-Request-Duration-ms. - Helps spot slow endpoints and monitor performance without extra tooling.
- You can extend this to send metrics to tools like Prometheus, Datadog, or InfluxDB.
- Category Middleware
- Total Views 524
- Last Modified 08 March, 2026
- Tags #middleware #performance #logging #timing
Previous snippet
Add Custom Headers in Response
Next snippet