Issue with Custom Django Middleware Not Executing

Hi everyone,

I’m encountering an issue with a custom middleware I’ve implemented in my Django project. The middleware is supposed to log every request made to the application, but it doesn’t seem to be executing. Here’s the relevant part of my code:

middleware.py

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

    def __call__(self, request):
        self.log_request(request)
        response = self.get_response(request)
        return response

    def log_request(self, request):
        with open('request_log.txt', 'a') as f:
            f.write(f"Method: {request.method}, Path: {request.path}\n")

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'myapp.middleware.LogRequestMiddleware',  # My custom middleware
]

Despite this, the log_request method is never called, and nothing gets logged in request_log.txt. I’ve double-checked that the middleware is listed correctly in settings.py and that the application name is correct.

Could anyone point out what might be going wrong or provide any tips on debugging custom middleware in Django?

Thanks in advance!

Hello there!
The best ways to check if your middleware is running is by:

  • Adding some print statements on your middleware and checking them on your terminal that you had “runserver” running;
  • Running your code with some debugger and adding a breakpoint in any line.

Another thing, is that this is not the best way to log information to a file. You can configure django to do this for you.