Go集成Prometheus需暴露/metrics端点并配置Prometheus抓取,用client_golang注册Counter、Gauge、Histogram等指标,再通过rule_files定义告警规则交由Alertmanager通知。
在 Go 语言中集成 Prometheus 主要分两步:暴露指标供 Prometheus 抓取,以及通过 Alertmanager 配合规则实现报警。核心是用 prometheus/client_golang 库注册和收集指标,再配置 Prometheus Server 定期拉取,最后定义告警规则触发通知。
最常用的方式是启动一个 HTTP 服务,将指标以文本格式暴露在 /metrics 路径下:
github.com/prometheus/client_golang/prometheus/promhttp
http.Handle("/metrics", promhttp.Handler()) 暴露端点:2112)对 Prometheus Server 可访问示例代码片段:
http.Handle("/metrics", promhttp.Handler())
go http.ListenAndServe(":2112", nil)根据监控目标选择合适指标类型:
http_requests_total{method="POST",code="200"})注册后,在

.Inc()、.Observe(duration.Seconds()) 等方法更新值。
在 Prometheus 的 prometheus.yml 中添加 job:
scrape_configs:
- job_name: 'my-go-service'
static_configs:
- targets: ['your-go-app-host:2112']重启 Prometheus 后,可在 Web UI 的 Status > Targets 查看是否健康,Graph 页面输入指标名查询数据。
告警不在 Go 程序中实现,而是由 Prometheus Server 加载规则文件,并将触发的告警转发给 Alertmanager:
alert.rules.yml,例如当 5 分钟内错误率 > 1% 时告警prometheus.yml 中通过 rule_files: 加载规则alerting.alertmanagers 关联一条简单规则示例:
- alert: HighErrorRate
expr: rate(http_requests_total{code=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.01
for: 2m
labels:
severity: warning
annotations:
summary: "High HTTP error rate"
来电咨询