登录
首页 >  Golang >  Go教程

GolangPrometheus监控指标教程详解

时间:2025-12-01 16:27:38 108浏览 收藏

想要在Go应用中实现高效的Prometheus监控吗?本文为你提供一份详细的Golang Prometheus监控指标收集教程。首先,我们将介绍如何引入Prometheus官方客户端库,定义并注册计数器和直方图等关键指标,这些指标能够帮助你追踪HTTP请求量和请求耗时等关键信息。接着,我们将演示如何通过HTTP Handler暴露`/metrics`接口,以便Prometheus能够抓取这些指标数据。最后,我们将讲解如何在Prometheus配置文件中添加目标地址,实现对Go应用的全面监控。通过本教程,你将能够轻松掌握Golang应用Prometheus监控的最佳实践,为你的微服务和高并发应用保驾护航。

首先引入Prometheus客户端库,定义并注册计数器和直方图指标,通过HTTP Handler记录请求量和耗时,暴露/metrics接口供Prometheus抓取,最后在配置文件中添加目标地址实现监控。

Golang Prometheus监控指标收集示例

在Go语言中使用Prometheus进行监控指标收集非常常见,尤其适合微服务和高并发场景。下面是一个简单的Golang程序示例,展示如何暴露HTTP接口供Prometheus抓取自定义指标。

1. 引入依赖

使用官方Prometheus客户端库来创建和暴露指标:

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

2. 定义并注册监控指标

可以在程序中定义计数器、直方图、仪表盘等常用指标。以下是一个包含计数器和直方图的示例:

代码示例:

package main

import (
  "net/http"
  "math/rand"
  "time"
  "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"},
  )

  requestDuration = prometheus.NewHistogram(
    prometheus.HistogramOpts{
      Name: "http_request_duration_seconds",
      Help: "HTTP request duration in seconds.",
      Buckets: prometheus.DefBuckets,
    },
  )
)

func init() {
  // 注册指标到默认的Registry
  prometheus.MustRegister(httpRequestsTotal)
  prometheus.MustRegister(requestDuration)
}

// 模拟处理请求的Handler
func handler(w http.ResponseWriter, r *http.Request) {
  start := time.Now()
  httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()

  // 模拟一些处理延迟
  time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)

  w.WriteHeader(http.StatusOK)
  w.Write([]byte("Hello, Prometheus!"))

  // 记录请求耗时
  requestDuration.Observe(time.Since(start).Seconds())
}

func main() {
  http.HandleFunc("/hello", handler)

  // 暴露/metrics端点供Prometheus抓取
  http.Handle("/metrics", promhttp.Handler())

  http.ListenAndServe(":8080", nil)
}

3. 配置Prometheus抓取目标

启动上面的Go程序后,访问 http://localhost:8080/metrics 可看到类似以下输出:

# HELP http_requests_total Total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{endpoint="/hello",method="GET"} 3

# HELP http_request_duration_seconds HTTP request duration in seconds.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_sum 0.423
http_request_duration_seconds_count 3

编辑Prometheus配置文件(prometheus.yml)添加Job:

scrape_configs:
  - job_name: 'go-app'
    static_configs:
      - targets: ['localhost:8080']

重启Prometheus后,在Web UI中即可查询 http_requests_totalhttp_request_duration_seconds 等指标。

4. 常用指标类型说明

  • Counter(计数器):只增不减,适合记录请求数、错误数等
  • Gauge(仪表盘):可增可减,适合内存使用、在线用户数等
  • Histogram(直方图):记录样本分布,如请求延迟分桶统计
  • Summary(摘要):类似直方图,但支持计算分位数

基本上就这些。只要在程序中正确注册指标并暴露/metrics接口,Prometheus就能自动抓取数据。实际项目中建议结合中间件统一收集HTTP指标,避免重复埋点。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《GolangPrometheus监控指标教程详解》文章吧,也可关注golang学习网公众号了解相关技术文章。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>