Go应用通过prometheus/client_golang库集成Prometheus监控,首先引入包并定义Counter、Gauge、Histogram指标,如请求总数和响应延迟;接着在init函数中注册指标,使用中间件记录HTTP请求的method和endpoint维度数据;然后通过http.Handle("/metrics", promhttp.Handler())暴露指标接口;最后在Prometheus配置中添加目标地址,实现定时抓取,结合Grafana可完成可视化监控。

Prometheus 是云原生生态中最流行的监控系统之一,Golang 应用可以很方便地集成 Prometheus 来暴露指标数据。实现方式主要是通过 prometheus/client_golang 官方库,在应用中定义并暴露 HTTP 接口供 Prometheus 抓取。
在 Go 项目中使用 Prometheus,第一步是引入官方客户端库:
go get github.com/prometheus/client_golang/prometheus go get github.com/prometheus/client_golang/prometheus/promhttp这两个包分别用于定义指标和提供 HTTP 处理器来暴露指标。
你可以根据需要创建计数器(Counter)、仪表(Gauge)、直方图(Histogram)等类型的指标。例如,统计请求次数和响应耗时:
立即学习“go语言免费学习笔记(深入)”;
Counter:只增不减,适合累计值,如请求数。
Gauge:可增可减,适合当前状态,如内存使用量。
Histogram:记录分布,如请求延迟。
示例代码:
package mainimport ( "net/http" "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"}, )
httpRequestDuration = prometheus.NewHistogramVec(
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},
},
[]string{"method", "endpoint"},
))
func init() { // 注册指标到默认的注册表 prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration) }
使用中间件的方式,在每个请求前后记录指标。以下是一个简单的日志+监控中间件:
func monitor(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now() // 执行实际处理逻辑
next.ServeHTTP(w, r)
// 请求结束后记录指标
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()
httpRequestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(time.Since(start).Seconds())
}}
func helloHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) }
将 handler 包装进中间件:
http.HandleFunc("/hello", monitor(helloHandler))Prometheus 通过定期抓取目标的 /metrics 接口获取指标数据。你需要添加一个路由来暴露这些指标:
http.Handle("/metrics", promhttp.Handler())启动服务:
func main() { http.ListenAndServe(":8080", nil) }运行程序后,访问 https://www.php.cn/link/c219b83bdbd3fc9bf4fa8526d4368ea1 可看到类似以下内容:
# HELP http_requests_total Total number of HTTP requests. # TYPE http_requests_total counter http_requests_total{endpoint="/hello",method="GET"} 5http_request_duration_seconds_bucket{endpoint="/hello",method="GET",le="0.1"} 3 ...
在 prometheus.yml 中添加你的 Go 应用为目标:
scrape_configs: - job_name: 'go-app' static_configs: - targets: ['localhost:8080']确保 Prometheus 能访问你的应用地址。重启 Prometheus 后,可在 Web 界面查看抓取到的指标。
基本上就这些。Go 应用通过简单几行代码就能接入 Prometheus,配合 Grafana 可实现可视化监控。关键是定义好有意义的指标,并持续优化观测维度。
以上就是Golang如何使用Prometheus监控应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号