首先引入Prometheus客户端库,然后定义并注册请求计数器和响应时间直方图等指标,接着通过promhttp暴露/metrics接口,再在中间件中记录请求数和耗时,最后配置Prometheus抓取目标实现监控。

在Go语言开发的微服务或Web应用中,集成Prometheus监控是实现可观测性的常见做法。通过暴露指标接口并交由Prometheus抓取,可以实时掌握服务的运行状态,比如请求量、响应时间、错误率等。下面介绍如何在Golang项目中快速接入Prometheus。
1. 引入Prometheus客户端库
要在Go项目中使用Prometheus,需要引入官方提供的客户端库。该库支持定义和暴露各种类型的监控指标。
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
其中,prometheus 包用于定义指标,promhttp 提供了用于暴露指标的HTTP处理器。
2. 定义并注册监控指标
常见的指标类型包括计数器(Counter)、仪表盘(Gauge)、直方图(Histogram)和摘要(Summary)。根据实际需求选择合适的类型。
立即学习“go语言免费学习笔记(深入)”;
例如,定义一个请求计数器和响应时间直方图:
var ( httpRequestsTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests.", }, []string{"method", "endpoint", "code"}, )httpResponseTime = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_response_time_seconds", Help: "Histogram of response time for HTTP requests.", Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0}, }, []string{"method", "endpoint"},)
)
注册这些指标到默认的注册中心:
func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpResponseTime)}
3. 在HTTP服务中暴露指标接口
使用 promhttp 将指标通过HTTP端点暴露出来,通常挂载在 /metrics 路径。
示例:使用标准 net/http 启动一个监控端口:
import ( "net/http" "github.com/prometheus/client_golang/prometheus/promhttp")func startMetricsServer() {http.Handle("/metrics", promhttp.Handler())http.ListenAndServe(":9091", nil)}
也可以将该Handler集成进现有服务,比如 Gin 或 Echo 框架中:
r := gin.New()r.GET("/metrics", gin.WrapH(promhttp.Handler()))
4. 在业务逻辑中更新指标
在处理请求时记录相关数据。例如,在中间件中统计请求数和耗时:
func metricsMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now() next.ServeHTTP(w, r) // 假设能获取状态码(需包装ResponseWriter) httpRequestsTotal.WithLabelValues( r.Method, r.URL.Path, "200", // 实际应动态获取 ).Inc() httpResponseTime.WithLabelValues( r.Method, r.URL.Path, ).Observe(time.Since(start).Seconds())}
}
注意:要准确获取状态码,建议封装 http.ResponseWriter 实现 WriteHeader 方法拦截。
配置Prometheus抓取目标时,只需在 prometheus.yml 中添加:
scrape_configs: - job_name: 'my-go-service' static_configs: - targets: ['your-service-ip:9091']
启动Prometheus后,访问其Web界面即可看到采集到的指标。
基本上就这些。只要定义好关键指标,暴露/metrics接口,并让Prometheus定期抓取,就能完成基础监控接入。后续可结合Grafana做可视化展示,提升排查效率。
以上就是Golang如何使用Prometheus监控服务_Golang Prometheus监控操作指南的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1426193.html
微信扫一扫
支付宝扫一扫