2

In my app, there is this API named 'UserChangeWorkScheduleViewSet' where its uri is 'host/api/v1/workSchedule' I have been trying to make a custom logging filter that would send me an error log whenever a user causes 400 status code. Below is the UserChangeWorkScheduleViewSet in 'workschedule.py':

class UserChangeWorkScheduleViewSet(viewsets.ModelViewSet):
    queryset = UserChangeWorkSchedule.objects.all()
    serializer_class = UserChangeWorkScheduleSerializer
    permission_classes = (IsAuthenticated,)

    def create(self, request, *args, **kwargs):
        UserChangeWorkSchedule.objects.filter(user=request.user.id).update(status=0)

        is_many = isinstance(request.data, list)
        if not is_many:
            request.data['user'] = request.user.id
            return super().create(request)
        else:
            for data in request.data:
                data['user'] = request.user.id

            serializer = self.get_serializer(data=request.data, many=True)
            if serializer.is_valid(raise_exception=True):
                self.perform_create(serializer)
                headers = self.get_success_headers(serializer.data)
                return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
            else:
                print('UserChangeWorkScheduleViewSet', request.user.id, serializer.errors)
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Here is my customlog.py:

import logging

class UserChangeWorkScheduleViewSet400(logging.Filter):

    def filter(self, record):
        record.levelname == 400
        record.filename == "workschedule.py"
        return True

And here is the logging in the settings

from api import customlog

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },
        'only_400_from_workschedule': {
            '()': customlog.UserChangeWorkScheduleViewSet400
        },
    },
    'formatters': {
        'simple_trace': {
            'format': '%(asctime)s %(levelname)s %(filename)s %(funcName)s %(message)s',
        }
    },
    'handlers': {
        'telegram': {
            'class': 'telegram_handler.TelegramHandler',
            'token': '1489551033:AAHbIvspcVR5zcslrbrJ9qNK2yZ1at0yIMA',
            'chat_id': '-429967971',
            'formatter': 'simple_trace',
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['telegram'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

I intentionally sent a bad request to raise 400 and the 400 shows up like so: [![enter image description here][1]][1]

However, I still do not receive the Telegram log. The Telegram log is working fine for other errors such as 500 though.

IMPORTANT: This logger must log other 500 error along with the 400 error from workschedule.py. If the setting only logs the workschedule.py's 400, the logging would not be useful. [1]: https://i.sstatic.net/eedI7.png

2 Answers 2

0

Have you tried authentication_classes?

https://www.django-rest-framework.org/api-guide/views/#authentication_classes

Sign up to request clarification or add additional context in comments.

Comments

0

You are not attaching your custom filter to telegram handler.

replace handler section of your config dictionary with below

'handlers': {
    'telegram': {
        'class': 'telegram_handler.TelegramHandler',
        "filters": ["only_400_from_workschedule"], # <--------------
        'token': '1489551033:AAHbIvspcVR5zcslrbrJ9qNK2yZ1at0yIMA',
        'chat_id': '-429967971',
        'formatter': 'simple_trace',
    }
},

Note:

Your custom filter is not doing any filtering, it is simply returning True. And by default record.levelname is string such as "INFO", "DEBUG" etc.

Probably what you want to do is something like below:

def filter(self, record):
    return record.filename == "workschedule.py" and "400" in record.message

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.