最近有个需要用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://<ip>:8080/metrics