Logging Requests in Middleware

A snippet for logging incoming requests with custom middleware.


# middleware.py

import logging

logger = logging.getLogger(__name__)

class LoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        logger.info(f"Request Method: {request.method}, Path: {request.path}")
        response = self.get_response(request)
        return response
  

# settings.py

MIDDLEWARE = [
    # ...
    'your_app.middleware.LoggingMiddleware',
]

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}
  
Explanation:
  • This middleware logs every request's HTTP method (GET, POST, etc.) and its path (URL).
  • Logging happens before the response is generated, making it great for debugging traffic and issues.
  • Django's LOGGING settings let you configure how and where logs are written (console, files, services).
  • You can expand this to include IPs, headers, or user information for detailed request tracking.
  • Category Middleware
  • Total Views 296
  • Last Modified 17 March, 2026
  • Tags #middleware #logging #requests #response
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.