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 抓取。
引入 Prometheus 客户端库
在 Go 项目中使用 Prometheus,第一步是引入官方客户端库:
go get github.com/prometheus/client_golang/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp
这两个包分别用于定义指标和提供 HTTP 处理器来暴露指标。
定义并注册监控指标
你可以根据需要创建计数器(Counter)、仪表(Gauge)、直方图(Histogram)等类型的指标。例如,统计请求次数和响应耗时:
立即学习“go语言免费学习笔记(深入)”;
Counter:只增不减,适合累计值,如请求数。
Gauge:可增可减,适合当前状态,如内存使用量。
Histogram:记录分布,如请求延迟。
示例代码:
package main
import (“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)}
在 HTTP 路由中记录指标
使用中间件的方式,在每个请求前后记录指标。以下是一个简单的日志+监控中间件:
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))
暴露 /metrics 接口供 Prometheus 抓取
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 counterhttp_requests_total{endpoint=”/hello”,method=”GET”} 5
HELP http_request_duration_seconds HTTP request latency in seconds.
TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{endpoint=”/hello”,method=”GET”,le=”0.1″} 3…
Prometheus 配置抓取任务
在 prometheus.yml 中添加你的 Go 应用为目标:
scrape_configs: – job_name: ‘go-app’ static_configs: – targets: [‘localhost:8080’]
确保 Prometheus 能访问你的应用地址。重启 Prometheus 后,可在 Web 界面查看抓取到的指标。
基本上就这些。Go 应用通过简单几行代码就能接入 Prometheus,配合 Grafana 可实现可视化监控。关键是定义好有意义的指标,并持续优化观测维度。
以上就是Golang如何使用Prometheus监控应用的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1414213.html
微信扫一扫
支付宝扫一扫