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

Golang如何使用Prometheus抓取自定义指标

P粉602998670
发布: 2025-10-18 08:27:01
原创
248人浏览过
答案是使用Prometheus Go客户端库定义并注册自定义指标,通过HTTP中间件记录请求数据,暴露/metrics端点供Prometheus抓取。具体步骤为:1. 引入prometheus/client_golang依赖,定义计数器http_requests_total和直方图request_duration_seconds;2. 在init函数中注册指标;3. 编写中间件更新指标,利用包装的ResponseWriter捕获状态码;4. 使用promhttp.Handler()暴露/metrics路径;5. 配置prometheus.yml的scrape_configs添加目标地址,即可在UI查询指标。

golang如何使用prometheus抓取自定义指标

在Go应用中集成Prometheus来抓取自定义指标,核心是使用官方客户端库 prometheus/client_golang。你需要定义指标、注册到处理器,并暴露一个HTTP端点供Prometheus抓取。

1. 引入依赖并初始化指标

先安装Prometheus Go客户端:

go get github.com/prometheus/client_golang/prometheusgo get 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"}, )
requestDuration = 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, 2.0},
    },
    []string{"endpoint"},
)
登录后复制

)

在程序启动时注册这些指标:

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

func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(requestDuration) }

2. 在代码中更新指标

在处理请求的地方记录数据。例如,在HTTP中间件中:

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.ServeHTTP(rw, r)

    duration := time.Since(start).Seconds()
    endpoint := r.URL.Path

    httpRequestsTotal.WithLabelValues(r.Method, endpoint, fmt.Sprintf("%d", rw.statusCode)).Inc()
    requestDuration.WithLabelValues(endpoint).Observe(duration)
}
登录后复制

}

确保实现自定义的 responseWriter 来获取状态码

标小兔AI写标书
标小兔AI写标书

一款专业的标书AI代写平台,提供专业AI标书代写服务,安全、稳定、速度快,可满足各类招投标需求,标小兔,写标书,快如兔。

标小兔AI写标书 40
查看详情 标小兔AI写标书
type responseWriter struct { http.ResponseWriter statusCode int }

func (rw *responseWriter) WriteHeader(code int) { rw.statusCode = code rw.ResponseWriter.WriteHeader(code) }

3. 暴露/metrics端点

使用 promhttp 处理器暴露指标:

func main() { http.Handle("/metrics", promhttp.Handler())
// 示例接口
http.HandleFunc("/api/users", metricsMiddleware(func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "user list")
}))

log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
登录后复制

}

Prometheus就可以通过 http://your-service:8080/metrics 抓取数据了。

4. 配置Prometheus抓取

prometheus.yml 中添加你的目标:

scrape_configs: - job_name: 'go-service' static_configs: - targets: ['localhost:8080']

重启Prometheus后,就能在Prometheus UI中查询如 http_requests_totalhttp_request_duration_seconds 等指标。

基本上就这些。只要定义好指标、正确记录、暴露端点,Prometheus就能自动抓取你的Go服务中的自定义监控数据。

以上就是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号