登录
首页 >  Golang >  Go教程

Golang监控:Prometheus指标收集教程

时间:2025-09-06 18:23:15 105浏览 收藏

想要对 Golang 服务进行有效监控?本文详细介绍了如何使用 Prometheus 官方客户端库 `prometheus/client_golang` 实现指标收集,并将其暴露为 Prometheus 可抓取的 HTTP 端点 `/metrics`。文章将引导你一步步完成指标的定义与注册,例如计数器和直方图,并通过中间件在 HTTP 处理过程中记录请求量、请求耗时等关键数据。通过示例代码,你将学会如何集成这些监控指标,并通过 Prometheus 定期拉取数据,最终配合 Grafana 实现可视化监控,从而全面掌握 Golang 服务的运行状态。掌握 Golang 服务监控,从 Prometheus 指标收集开始!

首先引入prometheus/client_golang库,然后定义并注册计数器和直方图指标,接着通过中间件在HTTP处理中记录请求量和耗时,最后暴露/metrics端点供Prometheus抓取,实现监控数据采集。

Golang服务监控实现 Prometheus指标收集

要在Golang服务中实现Prometheus指标收集,核心是使用官方提供的客户端库 prometheus/client_golang,并暴露符合Prometheus格式的HTTP端点。下面介绍如何一步步集成监控指标并让Prometheus抓取。

引入Prometheus客户端库

安装官方Golang客户端:

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

这个库提供了指标定义、注册和HTTP处理的支持。

定义和注册指标

在服务中创建常用的指标类型,比如计数器、直方图、仪表盘等。以下是一个简单示例:

package main

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"}, )

// 定义一个请求耗时直方图 var httpRequestDuration = prometheus.NewHistogram( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "HTTP request latency in seconds.", Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0}, }, )

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

在HTTP处理中记录指标

在实际的请求处理中更新指标。例如,使用中间件记录请求次数和耗时:

import "time"

func metricsMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now()

    // 包装 ResponseWriter 以捕获状态码
    rw := &responseWriter{ResponseWriter: w, statusCode: 200}
    next(rw, r)

    method := r.Method
    endpoint := r.URL.Path
    status := rw.statusCode

    httpRequestsTotal.WithLabelValues(method, endpoint, http.StatusText(status)).Inc()
    httpRequestDuration.Observe(time.Since(start).Seconds())
}

}

// 包装 ResponseWriter type responseWriter struct { http.ResponseWriter statusCode int }

func (rw *responseWriter) WriteHeader(code int) { rw.statusCode = code rw.ResponseWriter.WriteHeader(code) }

暴露/metrics端点

启动一个HTTP服务,暴露Prometheus可抓取的/metrics路径:

func main() { // 注册 metrics 接口 http.Handle("/metrics", promhttp.Handler())
// 示例业务接口
http.HandleFunc("/hello", metricsMiddleware(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, World!"))
}))

// 启动服务
http.ListenAndServe(":8080", nil)

}

启动后访问 http://localhost:8080/metrics 可看到类似以下输出:

http_requests_total{method="GET",endpoint="/hello",status="200"} 5 http_request_duration_seconds_bucket{le="0.1"} 3 http_request_duration_seconds_bucket{le="0.3"} 5 ...

Prometheus配置示例如下:

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

基本上就这些。只要服务暴露了/metrics,Prometheus就能定期拉取数据,配合Grafana可实现可视化监控。

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

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