Revel 如何自动暴露 `http_request_duration_seconds`?

解读

在国内一线/二线互联网公司的 Go 后端面试中,“能不能在框架层零侵入地暴露 Prometheus 指标” 是高频考点。
Revel 作为全栈 MVC 框架,没有官方 Prometheus 插件,但提供了 Filter 链(拦截器)+ 模块热插拔 机制,正好可以在请求入口和返回出口埋点,自动记录 http_request_duration_seconds。
面试官真正想听的是:

  1. 你熟悉 Revel 的 Filter 执行顺序 与 Controller 上下文;
  2. 你知道 Prometheus HistogramVec 四要素:namespace、subsystem、name、label;
  3. 你能把 业务代码与指标代码彻底解耦,做到“加包即可暴露”。

知识点

  1. Revel Filter 链:app.Init() 阶段通过 revel.Filters 数组注入自定义 Filter,所有请求都会顺序执行。
  2. revel.Controller:每次请求都会生成新的 *Controller 实例,内部字段 Controller.StartTime 已经记录了请求开始时间,精度为 time.Time,可直接复用。
  3. Prometheus HistogramVec:
    • 必须注册到 默认 Registerer;
    • 常用 label:method、status、endpoint(Revel 的 c.Action 即 ControllerName.MethodName)。
  4. 模块初始化钩子:Revel 支持 app.Init() 阶段执行任意代码,保证指标只注册一次,避免重复 panic。
  5. 暴露端口:Revel 本身监听业务端口,指标路由需额外监听 :9090/metrics,使用 github.com/prometheus/client_golang/prometheus/promhttp 即可,无需改动业务路由树。

答案

步骤一:创建指标包 metrics/metrics.go

package metrics

import (
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promauto"
    "github.com/revel/revel"
)

var (
    HttpDuration = promauto.NewHistogramVec(
        prometheus.HistogramOpts{
            Namespace: "revel",
            Subsystem: "http",
            Name:      "request_duration_seconds",
            Help:      "Duration of HTTP requests in seconds.",
            Buckets:   prometheus.DefBuckets,
        },
        []string{"method", "status", "endpoint"},
    )
)

func Init() {
    // 注册 Filter 到 Revel 全局链
    revel.Filters = append([]revel.Filter{PrometheusFilter}, revel.Filters...)
}

func PrometheusFilter(c *revel.Controller, fc []revel.Filter) {
    // StartTime 由框架在路由匹配后自动赋值
    start := c.StartTime
    fc[0](c, fc[1:])
    duration := time.Since(start).Seconds()
    status := strconv.Itoa(c.Response.Status)
    HttpDuration.WithLabelValues(c.Request.Method, status, c.Action).Observe(duration)
}

步骤二:在 app/init.go 中引入并初始化

import "your_project/app/metrics"

func init() {
    revel.OnAppStart(metrics.Init)
}

步骤三:新增 metrics 端口监听 在 app/init.go 追加:

import "github.com/prometheus/client_golang/prometheus/promhttp"

func init() {
    revel.OnAppStart(func() {
        go func() {
            http.Handle("/metrics", promhttp.Handler())
            _ = http.ListenAndServe(":9090", nil)
        }()
    })
}

效果:
服务启动后,无需修改任何 Controller,访问 http://localhost:9090/metrics 即可看到
revel_http_request_duration_seconds_bucket{method="GET",status="200",endpoint="App.Index",le="0.005"} 42
等全套 Prometheus 指标,完全零侵入、可热重载。

拓展思考

  1. 高并发场景下如何避免 metrics 成为瓶颈?
    答:

    • 使用 prometheus.HistogramVec 的 const label 把静态维度提前固化,减少每次 WithLabelValues 的 map 查询;
    • 若 QPS > 10w,把 Histogram 换成 Summary,或开启 exemplar 追踪采样,降低服务端 CPU。
  2. Revel 热编译重启后指标会清零,如何保证 SLA 监控连续?
    答:

    • Pushgateway 模式:在 revel.OnAppStop 钩子中把当前指标主动 push 到 Pushgateway,重启后再拉回;
    • 或者 sidecar 容器 独立跑 prometheus-node-exporter,业务容器只负责暴露,重启不影响时间序列。
  3. 国内金融级项目要求“双录”与审计,如何扩展?
    答:

    • 在 PrometheusFilter 中同时记录 trace-id(从 c.Request.Header.Get("X-Trace-Id") 取),把 trace-id 作为 exemplar 写入 Histogram;
    • 再配 Loki + Grafana,实现 “指标+日志+链路”三位一体,满足央行《金融科技指标上报规范》。

掌握以上思路,即可在面试中把 “Revel 如何自动暴露 http_request_duration_seconds” 讲成 “云原生可观测性最佳实践”,直接拉开与其他候选人的差距。