跳转至

可视化FastAPI监控ヾ(•ω•`)o

对于已经部署且依赖FastAPI的接口服务器,如何实现API调用、错误以及其它信息的监控呢?

找到了一个比较成熟且非常容易实现的开源方案,几乎零代码。

核心就三部份(外加FastAPI就是四个):

  1. Prometheus,有针对FastAPI的拓展包prometheus-fastapi-instrumentator
  2. 然后借助普罗米修斯抓取的标准格式的“mertics",对其进行可视化
  3. 可视化方案有很多,这里使用Grafana
%% 定义方向:TB=Top-Bottom
flowchart TB
    User([用户请求])

    subgraph FastAPI_App [FastAPI 应用]
        Endpoint[业务接口]
        Instrument[prometheus-fastapi-instrumentator]
        Metrics[/ <b>/metrics</b><br>Prometheus 格式指标 /]
    end

    Prometheus[(Prometheus <br> TSDB)]
    Grafana((Grafana<br>可视化))

    User -->|HTTP| Endpoint
    Endpoint --> Instrument
    Instrument -->|注册指标| Metrics
    Metrics -.->|pull| Prometheus
    Prometheus -.->|PromQL| Grafana

数据类型:https://prometheus.io/docs/concepts/metric_types/ python文档:https://prometheus.github.io/client_python/instrumenting/counter/

example:from prometheus_client import Gauge


自定义Prometheus Gauge指标current_online_users = Gauge(
    "current_online_users",
    "当前在线用户数",
    labelnames=("service",)
)
# 在需要的地方设置变量值

def update_online_users(count: int):
    current_online_users.labels(service="BunnyChenAPI").set(count)

# 示例:每次API调用时更新

@app.get("/online_users")
def get_online_users():
    user_count = 42  # 这里替换为你的实际逻辑
    update_online_users(user_count)
    return {"online_users": user_count}

评论