django请求日志中间件

import logging
import time

from django.http import FileResponse
from django.utils.deprecation import MiddlewareMixin

access_logger = logging.getLogger("access")

class LogMiddle(MiddlewareMixin):
    # 日志处理中间件
    def process_request(self, request):
        # 存放请求过来时的时间
        request.init_time = time.time()
        request.body.decode("utf-8")
        return None

    def process_response(self, request, response):
        # 耗时
        time_cost = time.time() - request.init_time
        # 请求路径
        path = request.path
        # 请求方式
        method = request.method
        # 请求参数
        if method == "GET":
            query = request.GET
            parm = query.urlencode()
        else:
            parm = request.body.decode("utf-8")
        # 响应状态码
        if isinstance(response, FileResponse):
            return response
        status_code = response.status_code
        response_content = response.content.decode("utf-8")
        if len(response_content) > 500:
            response_content = response_content[:500] + "..."

        message = f"\r\nurl:{path},\r\n method:{method},\r\n parm:{parm},\r\n time_cost:{round(time_cost, 2)},\r\n status_code:{status_code},\r\n response_content:{response_content}\r\n"
        access_logger.info(message)
        return response

posted @ 2023-01-11 17:37  公众号海哥python  阅读(153)  评论(0编辑  收藏  举报