Log requests and responses ¶
file main/middleware.py
import logging from django.utils.deprecation import MiddlewareMixin from django.conf import settings logging.basicConfig(level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s") def to_string(value): text = str(value) nmax = settings.LOG_REQUEST_DETAIL_MAX_LENGTH if nmax > 0 and len(text) > nmax: text = text[:nmax] + "......" return text def user_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None) if x_forwarded_for: remote_address = x_forwarded_for.split(',')[0].strip() else: remote_address = request.META.get('REMOTE_ADDR', None) return remote_address class LoggingMiddleware(MiddlewareMixin): """ Log requests and responses Adapted from: https://scripting4ever.wordpress.com/2020/07/27/how-to-log-the-request-and-response-via-django-middleware/ """ def process_request(self, request): if settings.LOG_REQUEST_DETAILS: logging.info("=" * 80) logging.info( "Request Method: " + to_string(request.META.get("REQUEST_METHOD", "???")) ) logging.info("URL requested: " + to_string(request.path)) logging.info("Request Body Contents: " + to_string(request.body)) logging.info("Request Headers: " + to_string(request.headers)) logging.info( "Content Length: " + to_string(request.META.get("CONTENT_LENGTH", "???")) ) logging.info( #"Client IP Address: " + to_string(request.META.get("REMOTE_ADDR", "???")) "Client IP Address: " + to_string(user_ip_address(request)) ) logging.info( "Host Name of Client: " + to_string(request.META.get("REMOTE_HOST", "???")) ) logging.info( "Host Name or Server: " + to_string(request.META.get("SERVER_NAME", "???")) ) logging.info( "Port of the Server: " + to_string(request.META.get("SERVER_PORT", "???")) ) logging.info("-" * 80) return None def process_response(self, request, response): if settings.LOG_REQUEST_DETAILS: logging.info("Response Content: " + to_string(response.content)) logging.info("Response Code: " + to_string(response.status_code)) logging.info("Response Headers: " + to_string(response.headers)) logging.info("=" * 80) return response
then, in settings.py:
MIDDLEWARE = [ ... 'main.middleware.LoggingMiddleware', ] ... LOG_REQUEST_DETAILS = True LOG_REQUEST_DETAIL_MAX_LENGTH = 200
Adapted from: