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.stack.imgur.com/eedI7.png