Django middleware for request logging and timing

13030
0

Custom middleware lets me inspect or modify every request and response. I implement both __init__ (called once at startup) and __call__ (for each request). By storing start time in the request, I can measure total processing time including view and template rendering. I log requests to a structured logger with contextual data like user, path, and duration. Middleware order matters—I place this early in MIDDLEWARE to capture total time. For production, I sample or filter to avoid log spam on high-traffic endpoints.