Python Web Integration Prometheus

This article shares how Python integrates Prometheus.

main content:

  • FastApi/Starlette integrates Prometheus
  • General method to integrate Prometheus

FastApi/Starlette integrates Prometheus

For web applications developed using FastApi, if you want to add monitoring indicators, the mainstream solution is to connect to Prometheus.

When looking for a solution, I found out that Starlette has a middleware, Starlette Prometheus .

FastApi inherits from Starlette and can use its middleware directly.

The usage instructions described in the official documentation of this middleware are based on the Starlette application as an example. Here is a brief description of how to use FastApi.

1. Installation

pip install starlette-prometheus

2. Add middleware

from fastapi import FastAPI
from starlette_prometheus import metrics, PrometheusMiddleware
​
app = FastAPI()
​
app.add_middleware(PrometheusMiddleware, filter_unhandled_paths=True)  # filter_unhandled_paths=True将过滤掉不属于starlette应用的path
app.add_route('/metrics', metrics)  # 设置metrics path
# app.add_route('/prometheus/metrics', metrics)  # 设置metrics path

3. Configure Prometheus

After exposing the prometheus metrics path, configure it in the prometheus.yml file.
Assuming that the application address is localhost:8000, the configuration example is as follows:

scrape_configs:
  - job_name: "fastapi"
    # metrics_path: "/prometheus/metrics"  # 设置metrics path,默认为 /metrics
    static_configs:
      - targets: ["localhost:8000"]

General method to integrate Prometheus

When using the Starlette Prometheus middleware, it is found that the underlying layer uses the Prometheus Python Client . This library is the Python Client officially provided by Prometheus. It is a general solution for Python to integrate Prometheus. However, this library only collects general system indicator data by default. If you want to collect application requests, responses and other indicators, you need to develop it yourself. If there is no Available third-party libraries can only use this library to develop indicators.

See Prometheus Python Client for usage details .

The general indicators are as follows:
insert image description here

Guess you like

Origin blog.csdn.net/xwd127429/article/details/120767996