普罗米修斯集成aiohttp框架。
hr-prometheus的Python项目详细描述
HR普罗米修斯
为aiohttp项目集成普罗米修斯。
HR Prometheus增加了对向prometheus提供aiohttp应用程序度量的支持。它是作为aiohttp中间件实现的。
目前,默认情况下,它通过/metrics端点导出以下度量:
- 请求延迟:每个请求所用的时间(秒)。
- 导出的标签:方法(http方法),路径
- 请求计数:收到的请求数。
- 导出的标签:方法(http方法)、路径、状态(http状态)
- 请求进行中:进行中的请求。
- 导出的标签:方法(http方法),路径
可以通过向中间件传递自定义的RequestMonitor
来修改默认请求行为。你可以在advanced section中找到怎么做。
安装
pip install hr-prometheus
用法
简单地说,您只需执行以下操作即可从aiohttp web应用程序测量和导出普罗米修斯度量:
fromaiohttpimportwebfromhr_prometheusimporthrprometheus_middleware,hrprometheus_viewapp=web.Application()app.router.add_get("/metrics",hrprometheus_view)app.middlewares.append(hrprometheus_middleware())
高级使用
自定义监视器
要修改默认行为,只需创建一个继承自BaseRequestMonitor
的新监视器,并将类传递给中间件。
这个类提供两个公共方法。update_init_metrics
和update_end_metrics
。
这些方法分别在请求的开始和结束执行。只需在每个点上添加所需的度量。
下面是从默认监视器中获取的示例。
fromaiohttpimportwebfromhr_prometheusimporthrprometheus_middleware,hrprometheus_viewfromhr_prometheus.monitorsimportBaseRequestMonitorclassRequestMonitor(BaseRequestMonitor):REQUEST_COUNT=Counter("request_count","Number of requests received",["method","path","status"])REQUEST_LATENCY=Histogram("request_latency","Elapsed time per request",["method","path"])REQUEST_IN_PROGRESS=Gauge("requests_in_progress","Requests in progress",["method","path"])defupdate_init_metrics(self):self.REQUEST_IN_PROGRESS.labels(*self.request_description).inc()defupdate_end_metrics(self):resp_time=time.time()-self.init_timeself.REQUEST_COUNT.labels(*self.request_description,self.response_status).inc()self.REQUEST_LATENCY.labels(*self.request_description).observe(resp_time)self.REQUEST_IN_PROGRESS.labels(*self.request_description).dec()app=web.Application()app.router.add_get("/metrics",hrprometheus_view)app.middlewares.append(hrprometheus_middleware(RequestMonitor))
分组动态路由
在aiohttp中,可以通过参数化路由路径(例如/v1/resource/{resource_id}
)来定义动态路由。如果您对在相同度量下对给定参数的不同值进行分组感兴趣,可以通过为到请求监视器的命名路由指定固定参数来进行分组(您可以通过使用中间件方便地这样做)。
下面是一个api从矩阵返回相邻单元格的示例
fromaiohttpimportwebfromhr_prometheusimporthrprometheus_middlewarefrommy_project.viewsimportget_cell_neighbour_viewmiddleware=hrprometheus_middleware(fixed_routes_parameter={"get_cell_neighbour":["cell_id"]})app=web.Application(middlewares=[middleware])app.add_route("GET","/cell_neighbour/{cell_id}/direction/{direction}",get_cell_neighbour_view,name="get_cell_neighbour")
这样,路径为/cell_neighbour/1948/direction/north
和/cell_neighbour/874/direction/north
的请求都被折叠成"/cell_neighbour/{cell_id}/direction/north"
当您对路径参数有很多可能的值,并且只对整体监视感兴趣时,这一点特别有用,从而避免了度量命名空间的污染。