Go服务集成Prometheus监控需暴露/metrics端点,用官方客户端注册Counter、Gauge、Histogram等指标,中间件统一埋点记录请求量与耗时,Prometheus通过配置static_configs抓取数据。

在 Go 服务中集成 Prometheus 监控,核心是暴露符合 Prometheus 格式的指标端点,并用官方客户端库自动注册和更新指标。不需要手动拼接文本格式,也不需要自己实现 HTTP handler —— promhttp 和 prometheus 客户端已封装好标准流程。
引入 Prometheus 客户端并初始化指标
使用官方库 github.com/prometheus/client_golang/prometheus 注册常用指标类型(Counter、Gauge、Histogram、Summary):
- Counter 适合累计值,如请求总数、错误总数
- Gauge 适合可增可减的瞬时值,如当前活跃连接数、内存使用量
- Histogram 推荐用于耗时、大小类分布统计(如 HTTP 响应时间),会自动分桶并提供 _sum/_count/_bucket 指标
示例:注册一个请求计数器和响应延迟直方图
goimport (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "status_code"},
)
httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration in seconds",
Buckets: prometheus.DefBuckets, // 或自定义 [0.01, 0.025, 0.05, ...]
},
[]string{"method", "path"},
)
)
func init() {
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(httpRequestDuration)
}
在 HTTP 处理逻辑中记录指标
在实际 handler 中调用 Inc()、Observe() 等方法更新指标值。建议配合中间件统一埋点,避免每个 handler 重复写:
立即学习“go语言免费学习笔记(深入)”;
- 用
httpRequestsTotal.WithLabelValues(r.Method, strconv.Itoa(status)).Inc()记录一次请求 - 用
httpRequestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(latency.Seconds())记录耗时 - 注意 label 值应可控(如路径避免带 ID,可用正则归一化),防止高基数导致 Prometheus 内存暴涨
暴露 /metrics 端点
只需一行代码挂载标准 handler:
http.Handle("/metrics", promhttp.Handler())启动服务后访问 http://localhost:8080/metrics 即可看到纯文本格式指标(如 http_requests_total{method="GET",status_code="200"} 42)。Prometheus server 抓取该地址即可采集数据。
配置 Prometheus 抓取目标
在 Prometheus 的 prometheus.yml 中添加 job:
scrape_configs:
- job_name: 'my-go-service'
static_configs:
- targets: ['localhost:8080']重启 Prometheus 后,在 Web UI 的 Status > Targets 页面确认目标为 UP 状态,再通过 Graph 查询如 rate(http_requests_total[5m]) 验证数据是否正常上报。
基本上就这些。不复杂但容易忽略的是 label 设计和 Histogram 的 bucket 设置 —— 这两点直接影响监控可用性和资源开销。










