How to log request and response for 4XX Http status in Django Rest Framework?

坚强是说给别人听的谎言 提交于 2019-12-13 03:20:27

问题


The default behaviour of DRF is to throw exception for 5XX, but return valid response with error details for 4XX. I want to log request and response of any API call which fails with 4XX.

Currently the log only shows Bad Request : /path/api/

Answer: Custom exception work fine.


回答1:


You can define your own custom exception handler and access your request such as:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    response = exception_handler(exc)
    if response is not None:
        response.data['status_code'] = response.status_code
        response.data['request'] = context['request']

    return response

And show your custom handler in settings.py such as:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}


来源:https://stackoverflow.com/questions/57589907/how-to-log-request-and-response-for-4xx-http-status-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!