Go微服务通过prometheus/client_golang暴露metrics,Prometheus配置抓取任务采集数据,Grafana接入Prometheus数据源并用PromQL构建看板,实现监控闭环。

Go语言编写的微服务要实现可观测性,集成Prometheus和Grafana是最常见且高效的方式。Prometheus负责采集和存储指标数据,Grafana用于可视化展示。整个过程不复杂,关键在于正确暴露指标、配置抓取,并构建合适的看板。
暴露Go服务的监控指标
要在Go微服务中启用监控,第一步是暴露符合Prometheus格式的HTTP端点。使用官方的prometheus/client_golang库可以轻松实现。
示例代码:
import (
"net/http"
"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", "endpoint", "status"},
)
)
func init() {
prometheus.MustRegister(httpRequestsTotal)
}
func main() {
// 注册Prometheus handler
http.Handle("/metrics", promhttp.Handler())
// 示例业务handler
http.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
httpRequestsTotal.WithLabelValues(r.Method, "/api/users", "200").Inc()
w.Write([]byte("Hello"))
})
http.ListenAndServe(":8080", nil)}
立即学习“go语言免费学习笔记(深入)”;
这样,访问http://localhost:8080/metrics就能看到标准的指标输出,Prometheus可直接抓取。
Prometheus配置抓取任务
启动Prometheus后,需在prometheus.yml中配置目标服务的抓取地址。
配置示例:
scrape_configs:
- job_name: 'go-microservice'
static_configs:
- targets: ['host.docker.internal:8080'] # 若在Docker中运行,使用此地址访问宿主机
启动Prometheus服务后,打开Web界面(默认9090端口),在Targets页面确认服务状态为“UP”,表示抓取正常。
Grafana接入Prometheus并展示指标
启动Grafana后,进入Web界面(默认3000端口),先添加Prometheus为数据源:
- 进入 Configuration > Data Sources > Add data source
- 选择 Prometheus
- URL填写 Prometheus 服务地址,如 http://localhost:9090
- 保存并测试连接
接着创建仪表盘,添加Panel,使用PromQL查询指标:
- 查询总请求数:rate(http_requests_total[5m])
- 按接口维度查看:sum by(endpoint) (rate(http_requests_total[5m]))
可设置图表类型、时间范围、刷新频率,形成直观的监控看板。
常用指标建议
除了自定义业务指标,建议集成以下通用监控:
- Go运行时指标:使用prometheus.NewGoCollector()收集GC、goroutine数等
- HTTP请求延迟:用Histogram记录响应时间分布
- 错误率监控:基于状态码统计失败请求占比
这些指标有助于快速定位性能瓶颈或异常行为。
基本上就这些。Go服务暴露metrics,Prometheus定时抓取,Grafana做可视化,三者配合即可完成基础监控闭环。后续可结合Alertmanager实现告警,进一步提升系统稳定性。










