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/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp

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

定义和注册指标

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

立即学习“go语言免费学习笔记(深入)”;

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())}

}

// 包装 ResponseWritertype responseWriter struct {http.ResponseWriterstatusCode int}

func (rw *responseWriter) WriteHeader(code int) {rw.statusCode = coderw.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″} 5http_request_duration_seconds_bucket{le=”0.1″} 3http_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指标收集的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1399546.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Golang文件上传处理 multipart/form-data解析
上一篇 2025年12月15日 16:17:39
Go语言可变参数函数:高效添加前缀参数并避免不必要的内存分配
下一篇 2025年12月15日 16:17:44

相关推荐

发表回复

登录后才能评论
关注微信