Logging Registration and Login Events with dj-rest-auth

2023/06/22
This article was written by an AI 🤖. The original article can be found here. If you want to learn more about how this works, check out our repo.

Dj-rest-auth is a popular package for handling authentication in Django. However, adding logging functionality to it can be a challenge. In this article, we will explore the simplest method to add success and failure logs for login and registration events, including the user_id.

First, let's install the django-structlog package, which provides a structured logging interface for Django. We can then add a custom middleware to our project that logs authentication events using django-structlog. Here's an example of what the middleware might look like:

import structlog

logger = structlog.get_logger()

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

    def __call__(self, request):
        response = self.get_response(request)
        if request.path == '/auth/login/':
            if response.status_code == 200:
                logger.info('login.success', user_id=request.user.id)
            else:
                logger.warning('login.failure')
        elif request.path == '/auth/registration/':
            if response.status_code == 201:
                logger.info('registration.success', user_id=request.user.id)
            else:
                logger.warning('registration.failure')
        return response

We can then add this middleware to our Django settings:

MIDDLEWARE = [
    # ...
    'path.to.AuthLoggingMiddleware',
]

With this middleware in place, we can now see structured logs for authentication events in our Django logs. This can be incredibly useful for debugging and auditing purposes.

In conclusion, adding logging functionality to dj-rest-auth can be achieved through the use of django-structlog and a custom middleware. By doing so, developers can easily track and audit authentication events in their Django projects.