Golang如何集成Prometheus监控指标采集

Go应用集成Prometheus需引入client_golang库,定义并注册计数器、直方图等指标,通过http.Handle暴露/metrics端点,Prometheus配置scrape任务定时抓取,实现监控数据采集与可视化。

Go应用集成Prometheus监控,核心是暴露符合Prometheus格式的指标接口,并让Prometheus服务定期抓取。实现方式简单直接,主要依赖官方提供的客户端库。

引入Prometheus客户端库

使用官方prometheus/client_golang库来注册和暴露指标。通过go mod管理依赖:

go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp

确保项目中正确引入后,就可以定义和注册自定义或内置指标。

定义并注册监控指标

在代码中创建计数器、直方图、摘要等类型的指标。例如,记录HTTP请求次数和响应耗时:

counter := prometheus.NewCounter(
    prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "Total number of HTTP requests made.",
    })
histogram := prometheus.NewHistogram(
    prometheus.HistogramOpts{
        Name:    "http_request_duration_seconds",
        Help:    "Duration of HTTP requests in seconds.",
        Buckets: prometheus.DefBuckets,
    })

prometheus.MustRegister(counter) prometheus.MustRegister(histogram)

实际处理请求时更新指标值:

counter.Inc()
histogram.Observe(duration.Seconds())

暴露/metrics端点

Prometheus通过HTTP抓取指标数据,需在Go服务中开启一个路由返回指标内容。通常使用net/http启动一个单独的监听端口或复用主服务:

http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))

启动服务后访问 http://localhost:8080/metrics 可看到文本格式的指标输出,如:

# HELP http_requests_total Total number of HTTP requests made.
# TYPE http_requests_total counter
http_requests_total 42

配置Prometheus抓取任务

在prometheus.yml中添加job,指向你的Go服务地址:

scrape_configs:
  - job_name: 'go-service'
    static_configs:
      - targets: ['your-go-app-ip:8080']

Prometheus会定时从/metrics拉取数据,完成采集。重启Prometheus服务使配置生效后,在Prometheus UI中即可查询对应指标。

基本上就这些。只要暴露了标准格式的metrics接口,Prometheus就能自动识别并存储数据,后续可结合Grafana做可视化展示。关键是指标命名合理、标签设计清晰,避免高基数问题。