You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于端点为prometheus_fastapi_instrumentator添加自定义标签?

给FastAPI Prometheus指标添加自定义标签

完全可以实现,通过prometheus_fastapi_instrumentator的扩展能力,就能给http_requests_total指标添加基于端点的自定义标签。以下是两种可行的实现方式:

方法一:复用默认指标,添加自定义Enricher

这种方式无需重新定义指标,只需在默认的http_requests_total收集逻辑中注入标签判断逻辑,简洁高效:

from prometheus_fastapi_instrumentator import Instrumentator
from prometheus_fastapi_instrumentator.metrics import http_requests_total

def add_endpoint_label(enrich, data):
    # 根据handler路径判断标签值
    if data.handler.startswith("/orders/electronic/"):
        enrich(label="electronic")
    elif data.handler.startswith("/orders/"):
        enrich(label="order")
    else:
        enrich(label="other")  # 非目标路径设置默认标签

# 初始化Instrumentator,替换默认指标并添加自定义enricher
instrumentator = Instrumentator().add(
    http_requests_total(enrich=add_endpoint_label)
)
instrumentator.instrument(app).expose(app, include_in_schema=False)

方法二:完全自定义指标收集逻辑

如果需要更灵活的控制,可以重新定义http_requests_total指标,手动处理标签和计数:

from prometheus_fastapi_instrumentator import Instrumentator
from prometheus_client import Counter

def custom_request_counter():
    # 定义包含额外label的Counter指标
    counter = Counter(
        "http_requests_total",
        "Total HTTP requests.",
        ["method", "status", "handler", "label"]
    )

    def instrumentation(request, response):
        # 获取当前请求的handler路径
        handler = request.scope.get("route").path if request.scope.get("route") else "unknown"
        # 确定label值
        if handler.startswith("/orders/electronic/"):
            label_val = "electronic"
        elif handler.startswith("/orders/"):
            label_val = "order"
        else:
            label_val = "other"
        # 生成状态码前缀(如2xx、4xx)
        status_prefix = str(response.status_code)[0] + "xx"
        
        # 更新指标计数
        counter.labels(
            method=request.method,
            status=status_prefix,
            handler=handler,
            label=label_val
        ).inc()

    return instrumentation

# 注册自定义指标并启动监控
instrumentator = Instrumentator().add(custom_request_counter())
instrumentator.instrument(app).expose(app, include_in_schema=False)

效果验证

启动服务后,访问/metrics端点,就能看到带自定义label标签的指标:

http_requests_total{handler="/orders/{order_id}",label="order",method="GET",status="2xx"} 99.0
http_requests_total{handler="/orders/electronic/{order_id}/items/",label="electronic",method="GET",status="4xx"} 5.0

内容的提问来源于stack exchange,提问作者wltz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 21:42:47