Golang自定义指标监控与Prometheus集成方法
时间:2025-12-03 10:07:34 315浏览 收藏
哈喽!今天心血来潮给大家带来了《Golang如何自定义指标监控与Prometheus集成》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
答案是使用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查询指标。

在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"},
))
在程序启动时注册这些指标:
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 来获取状态码:
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_total 或 http_request_duration_seconds 等指标。
基本上就这些。只要定义好指标、正确记录、暴露端点,Prometheus就能自动抓取你的Go服务中的自定义监控数据。
到这里,我们也就讲完了《Golang自定义指标监控与Prometheus集成方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
-
505 收藏
-
503 收藏
-
502 收藏
-
502 收藏
-
502 收藏
-
464 收藏
-
379 收藏
-
483 收藏
-
195 收藏
-
464 收藏
-
491 收藏
-
374 收藏
-
258 收藏
-
399 收藏
-
423 收藏
-
476 收藏
-
316 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习