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

如何为prometheus-flask-exporter的flask_http_request_exceptions_total添加path标签

问题原因

你当前的配置只给自定义的by_path_counter指标注册了path标签,prometheus-flask-exporter内置的flask_http_request_exceptions_total指标默认的统计逻辑在异常触发时,没有自动继承你给自定义指标配置的标签。而flask_http_request_duration_seconds_*类指标是在请求正常结束的after_request钩子中统计,会优先读取全局默认标签配置,所以可以正常携带path标签。

解决方案

方案1:注册全局默认标签

你可以直接给所有内置指标注册全局默认path标签,不需要只绑定到自定义指标:

metrics = PrometheusMetrics(app)
# 注册全局默认标签,所有内置指标都会自动携带
metrics.register_default(
    labels={
        'path': lambda: request.path
    }
)
# 原有自定义指标逻辑保留即可
metrics.register_default(
    metrics.counter(
        'by_path_counter', 'Request count by request paths',
        labels={'path': lambda: request.path}
    )
)

方案2:手动覆写异常指标统计逻辑

如果全局标签配置在异常场景下仍然不生效,可以通过Flask异常处理器手动统计带path标签的异常指标:

from flask import request

metrics = PrometheusMetrics(app)

# 预先注册带path标签的异常指标
exception_counter = metrics.counter(
    'flask_http_request_exceptions_total',
    'Total number of HTTP requests that resulted in an exception',
    labels=['path', 'method', 'exception']
)

# 全局异常处理器
@app.errorhandler(Exception)
def track_exception(e):
    exception_counter.labels(
        path=request.path,
        method=request.method,
        exception=type(e).__name__
    ).inc()
    # 抛出异常保留原有处理逻辑
    raise e

注意事项

如果你的路由包含动态参数(比如/user/<user_id>),直接使用request.path作为标签会导致指标基数过大,建议改用request.endpoint或者对路径做参数归一化处理后再作为标签值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:06:11