Logging requests to django-rest-framework

后端 未结 8 661
迷失自我
迷失自我 2020-12-02 12:31

For debugging purposes, I would like to use Django\'s logging mechanism to log each and every incoming request when it \"arrives\" at django-rest-framework\'s doorstep.

相关标签:
8条回答
  • 2020-12-02 13:11

    A few years later and Rhumbix has come out with this library, has anyone tried it?

    https://github.com/Rhumbix/django-request-logging

    MIDDLEWARE = (
    ...,
    'request_logging.middleware.LoggingMiddleware',
    ...,
    )
    

    And configure logging in your app:

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            'django.request': {
                'handlers': ['console'],
                'level': 'DEBUG',  # change debug level as appropiate
                'propagate': False,
            },
        },
    }
    
    0 讨论(0)
  • 2020-12-02 13:12

    I made a generic RequestLogMiddleware that can be hooked into any Django View using decorator_from_middleware.

    request_log/middleware.py

    import socket
    import time
    
    
    class RequestLogMiddleware(object):
        def process_request(self, request):
            request.start_time = time.time()
    
        def process_response(self, request, response):
    
            if response['content-type'] == 'application/json':
                if getattr(response, 'streaming', False):
                    response_body = '<<<Streaming>>>'
                else:
                    response_body = response.content
            else:
                response_body = '<<<Not JSON>>>'
    
            log_data = {
                'user': request.user.pk,
    
                'remote_address': request.META['REMOTE_ADDR'],
                'server_hostname': socket.gethostname(),
    
                'request_method': request.method,
                'request_path': request.get_full_path(),
                'request_body': request.body,
    
                'response_status': response.status_code,
                'response_body': response_body,
    
                'run_time': time.time() - request.start_time,
            }
    
            # save log_data in some way
    
            return response
    

    request_log/mixins.py

    from django.utils.decorators import decorator_from_middleware
    
    from .middleware import RequestLogMiddleware
    
    
    class RequestLogViewMixin(object):
        """
        Adds RequestLogMiddleware to any Django View by overriding as_view.
        """
    
        @classmethod
        def as_view(cls, *args, **kwargs):
            view = super(RequestLogViewMixin, cls).as_view(*args, **kwargs)
            view = decorator_from_middleware(RequestLogMiddleware)(view)
            return view
    

    my_django_rest_api/views.py

    from rest_framework import generics
    
    from ...request_log.mixins import RequestLogViewMixin
    
    class SomeListView(
        RequestLogViewMixin,
        generics.ListAPIView
    ):
        ...
    
    0 讨论(0)
提交回复
热议问题