31 lines
889 B
Python
31 lines
889 B
Python
|
|
import logging
|
||
|
|
import time
|
||
|
|
|
||
|
|
logger = logging.getLogger("django.request")
|
||
|
|
|
||
|
|
|
||
|
|
class RequestLoggingMiddleware:
|
||
|
|
"""
|
||
|
|
Captures incoming HTTP requests, client IPs, response status codes,
|
||
|
|
and end-to-end processing durations to log to requests.log and console.
|
||
|
|
"""
|
||
|
|
|
||
|
|
def __init__(self, get_response):
|
||
|
|
self.get_response = get_response
|
||
|
|
|
||
|
|
def __call__(self, request):
|
||
|
|
start_time = time.time()
|
||
|
|
response = self.get_response(request)
|
||
|
|
duration_ms = (time.time() - start_time) * 1000
|
||
|
|
|
||
|
|
ip = (
|
||
|
|
request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")[0].strip()
|
||
|
|
or request.META.get("REMOTE_ADDR", "unknown")
|
||
|
|
)
|
||
|
|
|
||
|
|
logger.info(
|
||
|
|
f"IP: {ip} | {request.method} {request.get_full_path()} | "
|
||
|
|
f"Status: {response.status_code} | Duration: {duration_ms:.2f}ms"
|
||
|
|
)
|
||
|
|
return response
|