How would you implement a custom middleware to log the time taken for every request, and what methods like process_view or process_response would you hook into?
Last updated
Record
time.monotonic()before callingget_response()and compute the delta after it returns. Then log it or add anX-Request-Durationheader in the response phase.process_viewis optional: it runs after URL resolution with the view function, so use it to capture which view is being timed.Register the class in
MIDDLEWAREnear the top so the timing covers the full middleware stack.
- https://micropyramid.com/blog/understanding-middleware-functionality-in-django2/
- https://docs.djangoproject.com/en/6.1/topics/http/middleware/
- https://levelup.gitconnected.com/django-middleware-explained-with-5-production-ready-examples-c2e630c33038
- https://dev.to/alansomathew/how-django-works-internally-the-complete-request-response-cycle-io8