首页 > 后端开发 > Golang > 正文

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

P粉602998670
发布: 2025-08-22 08:03:01
原创
476人浏览过
首先引入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处理的支持。

定义和注册指标

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

立即学习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处理中记录指标

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

标贝科技
标贝科技

标贝科技-专业AI语音服务的人工智能开放平台

标贝科技 14
查看详情 标贝科技
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指标收集的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号