首页 > 其他分享 >django请求日志中间件

django请求日志中间件

时间:2023-01-11 17:45:51浏览次数:36  
标签:status 中间件 request django content method time 日志 response

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

标签:status,中间件,request,django,content,method,time,日志,response
From: https://www.cnblogs.com/lianhaifeng/p/17044492.html

相关文章

  • Django过滤器、自定义过滤器与自定义标签
    过滤器视图模板过滤器符号为| {{sex|default:"未知"}}--当sex的值为空时,取“未知”{{age|add:"5"}}--给age的值加5{{hobby|fi......
  • SqlServer日志清理
      USEABC--数据库名select*from sys.database_files--查看日志文件名USE[master]   GO   ALTERDATABASEABCSETRECOVERYSIMPLEWITHNO_WAIT--TechM......
  • Django条件查询When、Case
    目录Django条件查询When、Case1、model和数据准备2、When和Case操作新增字段返回3、条件搜索4、条件更新5、条件聚合Django条件查询When、Case这一篇笔记将介绍条件......
  • MSSQL中开启CDC导致事务日志空间被占满事件记录
    问题描述SQLServer中开启CDC之后,在某些情况下会导致事务日志空间被占满的现象为:在执行增删改语句(产生事务日志)的过程中提示,Thetransactionlogfordatabase'***'isfu......
  • 驱动日志Level精确打印
    如何精确控制驱动程序的log输出?一、设定Level等级enum{DRV_MSG_ERR=0x0001,DRV_MSG_WARN=0x0002,DRV_MSG_INFO......
  • (7)go-micro微服务zap日志配置
    目录一Zap日志介绍二Zap日志安装三Zap日志初始化四Zap日志重写方法五Zap日志使用六最后一Zap日志介绍Zap是在Go中实现超快、结构化、分级的日志记录。Zap......
  • Django序列化器的简单使用
    [Django序列化器的简单使用-SSgeek-博客园](https://www.cnblogs.com/ssgeek/p/13263810.html)注意:serializer 不是只能为数据库模型类定义,也可以为非数据库模型类的......
  • Linux截取某一段时间的日志
    问题:在服务器上,UAT环境logs日志有2G想要查看下载显然不合适,所以想要截取某一段时间的日志。因为不清楚日志的精确开始时间和结束时间,为避免截取的日志里没有对应的时间......
  • oracle 情理归档日志
    1.相关日志su-oracle//进入oracle账户sqlplus/assysdba//以操作系统权限认证的oraclesys管理员登陆archiveloglist//查看数据库的归档模式注意:输入arc......
  • nginx日志报错Uncaught exception 'SmartyException' with message 'unable to write
    问题:访问xxx.xxx.xxx域名时,返回500状态码,查看Nginx日志发现报错,Uncaughtexception'SmartyException'withmessage'unabletowritefFatalerror:Uncaughtexceptio......