Jethro
Jethro

Reputation: 3329

How to log all Django serializer validation errors?

Similar to this, I would like to get log lines on the server when serializer validation fails.

What is the best approach to add logging to Serializers?

Upvotes: 5

Views: 1777

Answers (2)

Tony S Yu
Tony S Yu

Reputation: 3163

This can also be done with a custom exception handler (see Django REST Framework docs), which would apply to all DRF endpoints (if you want it for all Django endpoints, then you should use custom middleware):

def custom_exception_handler(exc, context):
    # Get standard error response from REST framework's default exception handler:
    response = exception_handler(exc, context)

    if response is not None and response.status_code == http.client.BAD_REQUEST:
        # Log response data for bad request to simplify debugging:
        logger.warning(f"Bad request to {context['request'].path}: {response.data}")

    return response

You'll also need to register this handler, as described in the Django REST Framework docs.

Upvotes: 3

Jethro
Jethro

Reputation: 3329

A workaround is to override the is_valid call.

from rest_framework.exceptions import ValidationError

class MySerializer(serializers.ModelSerializer):

    class Meta:
        ...

    def is_valid(self, raise_exception=False):
        ret = super(MySerializer, self).is_valid(False)
        if self._errors:
            logger.warn("Serialization failed due to {}".format(self.errors))
            if raise_exception:
                raise ValidationError(self.errors)
        return ret

Upvotes: 3

Related Questions