Go 监控实战:用 Prometheus 自定义指标把服务状态暴露出来

test12026-10-2420 次阅读

监控不是上线后才想的事

一个只写业务逻辑的 Go 服务,出问题时你只能靠日志猜。Prometheus 的拉模型让监控变得简单:服务在 /metrics 暴露指标,采集器定时来拉,你就能看到 QPS、延迟、错误率的变化曲线。

注册三类核心指标

Counter 只增不减记录请求总数,Histogram 统计延迟分布,Gauge 反映瞬时值(如在线连接数)。

package metrics

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

var (
    ReqTotal = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "HTTP 请求总数",
        },
        []string{"method", "code"},
    )
    ReqDuration = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Name:    "http_request_duration_seconds",
            Help:    "请求耗时分布",
            Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1, 3},
        },
        []string{"method"},
    )
)

func init() {
    prometheus.MustRegister(ReqTotal, ReqDuration)
}

在 HTTP 中间件里埋点

用一个中间件统一记录每个请求的计数与耗时,业务代码完全无感知。

func Instrument(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        sw := &statusWriter{ResponseWriter: w, status: 200}
        next.ServeHTTP(sw, r)
        elapsed := time.Since(start).Seconds()
        ReqTotal.WithLabelValues(r.Method, strconv.Itoa(sw.status)).Inc()
        ReqDuration.WithLabelValues(r.Method).Observe(elapsed)
    })
}

暴露 /metrics 端点

挂上官方的 Handler,Prometheus 就能来抓取。

func main() {
    mux := http.NewServeMux()
    mux.Handle("/metrics", prometheus.Handler())
    mux.HandleFunc("/api/ping", ping)
    http.ListenAndServe(":8080", Instrument(mux))
}

配合 prometheus.yml 里加一个 job,几分钟内就能在 Grafana 画出请求量与 P99 延迟。指标先于告警,看得见才能管得住。

T

test1

文章作者

监控不是上线后才想的事 一个只写业务逻辑的 Go 服务,出问题时你只能靠日志猜。Prometheus 的拉模型让监控变...

分类
技术
发布时间
2026-10-24
字数
约 1588 字
阅读
20 次