栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

django 中间件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

django 中间件

最近有个需要用prometheus对django服务的接口进行监控的任务,由于接口比较多,写装饰器比较麻烦,因此,研究了中间件的用法

1. 编写monitor.middleware

编写一个middleware.py文件,内容如下:

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.views import View
from prometheus_client import CollectorRegistry, Counter, generate_latest, Gauge
import time

# 注册采集器
LABELS = ['req_status', 'req_method', 'req_url']  # 标签定义

REGISTRY = CollectorRegistry()


class ExporterView(View):
    """
    exporter主页面
    """
    def get(self, request, *args, **kwargs):
        return HttpResponse(generate_latest(REGISTRY), status=200, content_type="application/json")


class MonitorMiddleware(MiddlewareMixin):
    """
    监控指标埋点
    该类主要是采集http性能相关的指标
    """
    def __init__(self, get_response=None, t=None):
        super().__init__(get_response)
        self.start = t
        self.g_requests_total = Counter('requests_total',
                                        'url request total num',
                                        LABELS,
                                        registry=REGISTRY
                                        )
        self.g_response_time_seconds = Gauge('avg_response_time_seconds',
                                             'Seconds of prediction cost in total',
                                             LABELS,
                                             registry=REGISTRY
                                             )

    def process_request(self, request):
        self.start = time.time()

    def process_response(self, request, response):
        method = request.method
        status = response.status_code
        url = request.path
        avg_rt = time.time() - self.start
        self.g_requests_total.labels(status, method, url).inc()  # 统计请求次数
        self.g_response_time_seconds.labels(status, method, url).set(avg_rt)
        return response

然后,在setting.py中配置该中间件

MIDDLEWARE = [
    '....',  # 其它默认的中间件
    'monitor.middleware.MonitorMiddleware',   # 自定义的监控中间件
]

将django工程打包成docker镜像后,启动django工程(本项目使用8080端口),可以在该url下看到监控日志http://:8080/metrics

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/743848.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号