直接调用 iris.Prometheus() 即可启用,须在路由注册前调用以注册 /metrics 路由并暴露运行时指标;它不支持自定义路径,且与 InterSystems IRIS 无关;自定义指标需引入 prometheus/client_golang 并复用 Iris 的 HTTP server。

iris.Prometheus() 中间件怎么启用
直接调用 iris.Prometheus() 就能注册 Prometheus 指标收集器,但必须在路由注册前挂载,否则指标不会被采集。它本质是注册一个 /metrics 路由并自动暴露基础运行时指标(如 HTTP 请求计数、延迟直方图、Go 内存统计)。
常见错误是把它放在 app.Use(...) 之后,或写在某个子路由组里 —— 这会导致 /metrics 不可达,Prometheus 抓取返回 404。
- 正确位置:紧接
app := iris.New()后,且早于所有app.Get/Post/Handle调用 - 它默认监听
GET /metrics,不支持自定义路径(想改就得自己重写 handler) - 不需要额外 import Prometheus 客户端库,Iris 内置封装了
promhttp的逻辑
HTTP 请求指标为什么没看到 iris_interop_avg_* 这类命名
你看到的 iris_interop_avg_processing_time 等指标来自 InterSystems IRIS(医疗/企业级数据库平台),和 Go 的 Iris Web 框架完全无关 —— 这是名称撞车导致的典型混淆。Go 的 Iris 框架暴露的指标全是标准 Prometheus 命名风格,比如:
http_requests_total{method="GET",status="200",path="/api/users"}http_request_duration_seconds_bucket{le="0.1",method="POST",path="/login"}-
go_goroutines、process_resident_memory_bytes
如果你在文档或监控面板里搜 iris_interop_*,那目标系统一定是 InterSystems IRIS,不是 Go 的 Iris。强行在 Go 项目里查这些指标,只会一无所获。
怎么加自定义业务指标(比如订单量、失败率)
Iris 的 iris.Prometheus() 不提供注册自定义指标的接口,得绕过它,直接用官方 prometheus/client_golang 库。
关键点:必须复用 Iris 启动的 HTTP server 实例,不能另起一个端口;同时要确保 metrics handler 和 Iris 的路由共存。
- 先
import "github.com/prometheus/client_golang/prometheus" - 定义指标:
orders_total = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "orders_total", Help: "Total orders processed"}, []string{"status"}) - 在
app.ConfigureHost()里把orders_total注册到全局 registry:prometheus.MustRegister(orders_total) - 在 handler 里打点:
orders_total.WithLabelValues("success").Inc() - 最后用
app.Any("/metrics", iris.FromStd(promhttp.Handler()))暴露(注意是Any,不是Get,避免 method 不匹配)
为什么 Prometheus 抓不到指标,但 curl /metrics 能看到
大概率是抓取配置里的 scrape_timeout 太短,或服务启用了 HTTPS 但配置写了 http://。Iris 默认不强制 HTTPS,但如果你加了 TLS 配置(比如 app.Run(iris.TLS(...))),而 Prometheus 的 job 还是用 http 协议去抓,就会超时或拒绝连接。
另一个隐蔽问题是:Iris 的 iris.Prometheus() 在启用后会自动设置 Content-Type: text/plain; version=0.0.4;charset=utf-8,某些旧版 Prometheus(text/plain; version=0.0.4,得自己写 handler 替换。
最稳妥的做法:不用 iris.Prometheus(),全程手管 promhttp,控制 header、路径、registry 和生命周期。复杂度略升,但可控性拉满。


















