必须用fiberprometheus.New注册中间件且/metrics走独立HTTP服务,因promhttp.Handler()不兼容Fiber上下文、未接入路由树,且业务压力会导致指标采集不可靠;正确做法是用fiberprometheus自动埋点并另起端口暴露metrics。

必须用 fiberprometheus.New 注册中间件,且 /metrics 必须走独立 HTTP 服务暴露,不能和业务端口混用。
为什么 app.Use(prometheus.Handler()) 会失效
这是最常踩的坑:直接把 Prometheus 官方 promhttp.Handler() 当作 Fiber 中间件挂载,结果 /metrics 返回 404 或空响应。原因有三:
- Fiber 的
app.Use()是前缀匹配中间件,而promhttp.Handler()是标准http.Handler,不兼容 Fiber 的fiber.Ctx上下文 - 它不会自动注册到 Fiber 的路由树,
app.Get("/metrics", ...)也得手动写,但又没法直接传promhttp.Handler() - 更关键的是:指标采集需持续稳定暴露,一旦业务请求压垮主线程(比如 GC 尖峰、慢 SQL),
/metrics可能超时或卡死,导致 Prometheus 抓取失败——这违背了监控“自身必须高可用”的原则
正确做法:用 fiberprometheus + 独立 metrics 服务
社区维护的 github.com/gofiber/fiber/v2/middleware/prometheus(即 fiberprometheus)是专为 Fiber 设计的封装,它做了两件事:一是把指标注册进 Prometheus 全局 registry,二是提供可直接启动的 http.Server 实例。
实操要点:
立即学习“go语言免费学习笔记(深入)”;
- 初始化时调用
fiberprometheus.New("myapp"),返回一个中间件实例,传给app.Use()即可自动记录请求路径、方法、状态码、耗时 - 调用
prom.Registerer().Gather()并用promhttp.HandlerFor(...)包装,但别挂到app上——而是另起一个http.Server监听:9091这类专用端口 - 务必在
app.Listen()之前启动 metrics 服务,否则可能因端口被占失败 - 示例关键片段:
prom := fiberprometheus.New("user-api")
app.Use(prom.Middleware) // 自动埋点
// 启动独立 metrics 服务
go func() {
metricsApp := http.NewServeMux()
metricsApp.Handle("/metrics", prom.Handler())
log.Fatal(http.ListenAndServe(":9091", metricsApp))
}()
fiberprometheus 默认指标有哪些?怎么改 bucket
默认暴露三个核心指标:
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
-
http_request_duration_seconds_bucket{method="GET",path="/users",status_code="200"}:直方图,含预设 latency buckets(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10 秒) -
http_requests_total{method="POST",path="/login",status_code="401"}:Counter,按方法+路径+状态码聚合 -
http_request_size_bytes_count{...}和http_response_size_bytes_count{...}:请求/响应体大小统计(默认关闭,需显式启用)
修改 bucket 要在初始化时传参:
prom := fiberprometheus.New("myapp",
fiberprometheus.WithDurationBuckets([]float64{0.01, 0.05, 0.1, 0.3, 0.8, 2}), // 替换默认值
fiberprometheus.WithResponseSize(true), // 开启响应体大小统计
)
注意:WithDurationBuckets 必须在 New() 时设置,后续无法修改;bucket 数量建议控制在 10 个以内,过多会显著增加内存占用和 Prometheus 存储压力。
高基数陷阱:路径标签怎么分组才不崩
默认情况下,fiberprometheus 把完整路径(如 /users/123/profile)作为 path 标签值,这会导致指标维度爆炸——每个用户 ID 都生成新时间序列,Prometheus 很快 OOM。
解决方式只有两个,且必须二选一:
- 用
WithSubroutes按前缀归并:fiberprometheus.WithSubroutes("/users/:id", "/users/:id/profile"),所有匹配路径统一标为/users/:id/profile - 手动注册自定义路由分组,在
app.Group()上挂中间件:api := app.Group("/api"); api.Use(prom.Middleware),再让所有子路由都走api.Get("/users", ...),这样指标里path标签就变成/api/users,避免带参路径污染
千万别用正则路由(/users/*)来“兜底”,它不仅性能差 3–5 倍,还会让 fiberprometheus 无法识别路径结构,导致分组失效。


















