pythondjangologgingdjango-rest-frameworkhttp-status-code-400

How to log more detail of 400 responses in Django Rest Framework?


I've got an endpoint built with Django Rest Framework, to which someone is posting data. Since this morning he's getting a lot of 400 responses. In my Kibana logging I can only confirm that he indeed receives a lot of 400 responses. I need to debug this, but I don't have a lot of info. So I want to log more detail about the 400 responses. So I thought of doing the following in my viewset

def create(self, request, *args, **kwargs):
    try:
        response = super().create(request, *args, **kwargs)
        return response
    except exceptions.ValidationError as e:
        logger.error(f"{e} in message: {request.data}")
        return Response(e, status=status.HTTP_400_BAD_REQUEST)

This seems to work, but it doesn't really feel like the most logical way of doing it. Is there a more pythonic way of logging 400 responses?


Solution

  • I would check the response.status value, which will be an integer and then I log response.data which will be a dict like object.

    Also, Logstash is very fond of JSON like items, this may more suitable in your case.

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        if response.status == 400:
            logger.error(response.data)
            
        return response