一尘不染

将请求记录到django-rest-framework

django

出于调试目的,我想使用Django的日志记录机制来记录每个传入的请求,当它们到达django-rest-framework的家门口时。

Djagno以以下方式(来自settings.py的“ LOGGING”部分)提供其请求的日志记录(仅“警告”日志级别和更高级别):

'django.request': {
        'handlers': ['mail_admins'],
        'level': 'ERROR',
        'propagate': False,
 },

我正在寻求实现以下目标(注意:日志级别为DEBUG):

'rest_framework.request': {
        'handlers': ['logfile'],
        'level': 'DEBUG',
        'propagate': False,
 },

有没有办法在不将记录器嵌入DRF的源代码的情况下做到这一点?
我可能不知道的DRF中是否存在某种“记录后端”选项?


阅读 571

收藏
2020-04-02

共1个答案

一尘不染

我做了一个泛型RequestLogMiddleware,可以使用将它连接到任何Django Viewdecorator_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
):
    ...
2020-04-02