将请求记录到Django rest fram

2024-06-26 19:52:57 发布

您现在位置:Python中文网/ 问答频道 /正文

出于调试的目的,我想使用Django的日志记录机制,在每个传入请求“到达”Django rest框架的门口时对其进行日志记录。

Djagno以以下方式(从settings.py中的logging部分)提供对其请求的日志记录(仅“warning”日志级别及更高级别):

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

我希望实现这样的功能(注意:日志级别是DEBUG):

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

有没有一种方法可以在不将记录器嵌入DRF源代码的情况下完成这项工作?
DRF中是否有某种我不知道的“日志后端”选项?


Tags: djangodebug目的框架restfalserequesthandlers
3条回答

我做了一个泛型RequestLogMiddleware,可以用decorator_from_middleware连接到任何Django View

请求日志/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

请求日志/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
):
    ...

我发现,最好、最灵活的方法是通过decorator添加日志记录。我只是将decorator添加到每个要记录请求的函数(post、get)中,而不是将其作为overal view类的一部分。更多地控制记录的内容。这些修饰符接受传入的请求对象(arg[1]),然后将请求对象的部分记录到文件中。

请参见https://github.com/slogan621/tscharts/commit/39ed479b04b7077f128774d3a203a86d6f68f03e了解执行此操作所需的模板(commit显示了将日志记录线程化到现有文件日志记录方案所需的settings.py更改,以及decorator和示例用法)。

重写^{}方法以添加日志记录。

Dispatch methods

The following methods are called directly by the view's .dispatch() method. These perform any actions that need to occur before or after calling the handler methods such as .get(), .post(), put(), patch() and .delete().

.initial(self, request, *args, **kwargs)
Performs any actions that need to occur before the handler method gets called. This method is used to enforce permissions and throttling, and perform content negotiation.

相关问题 更多 >