GolangPrometheus指标收集教程详解
时间:2025-11-01 09:51:27 156浏览 收藏
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Golang Prometheus监控指标收集教程》,聊聊,希望可以帮助到正在努力赚钱的你。
首先引入Prometheus客户端库,定义并注册计数器和直方图指标,通过HTTP Handler记录请求量和耗时,暴露/metrics接口供Prometheus抓取,最后在配置文件中添加目标地址实现监控。

在Go语言中使用Prometheus进行监控指标收集非常常见,尤其适合微服务和高并发场景。下面是一个简单的Golang程序示例,展示如何暴露HTTP接口供Prometheus抓取自定义指标。
1. 引入依赖
使用官方Prometheus客户端库来创建和暴露指标:
go get github.com/prometheus/client_golang/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp2. 定义并注册监控指标
可以在程序中定义计数器、直方图、仪表盘等常用指标。以下是一个包含计数器和直方图的示例:
代码示例:
package mainimport (
"net/http"
"math/rand"
"time"
"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"},
)
requestDuration = prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: prometheus.DefBuckets,
},
)
)
func init() {
// 注册指标到默认的Registry
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(requestDuration)
}
// 模拟处理请求的Handler
func handler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()
// 模拟一些处理延迟
time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, Prometheus!"))
// 记录请求耗时
requestDuration.Observe(time.Since(start).Seconds())
}
func main() {
http.HandleFunc("/hello", handler)
// 暴露/metrics端点供Prometheus抓取
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
3. 配置Prometheus抓取目标
启动上面的Go程序后,访问 http://localhost:8080/metrics 可看到类似以下输出:
# HELP http_requests_total Total number of HTTP requests.# TYPE http_requests_total counter
http_requests_total{endpoint="/hello",method="GET"} 3
# HELP http_request_duration_seconds HTTP request duration in seconds.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_sum 0.423
http_request_duration_seconds_count 3
编辑Prometheus配置文件(prometheus.yml)添加Job:
scrape_configs:- job_name: 'go-app'
static_configs:
- targets: ['localhost:8080']
重启Prometheus后,在Web UI中即可查询 http_requests_total 和 http_request_duration_seconds 等指标。
4. 常用指标类型说明
- Counter(计数器):只增不减,适合记录请求数、错误数等
- Gauge(仪表盘):可增可减,适合内存使用、在线用户数等
- Histogram(直方图):记录样本分布,如请求延迟分桶统计
- Summary(摘要):类似直方图,但支持计算分位数
基本上就这些。只要在程序中正确注册指标并暴露/metrics接口,Prometheus就能自动抓取数据。实际项目中建议结合中间件统一收集HTTP指标,避免重复埋点。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《GolangPrometheus指标收集教程详解》文章吧,也可关注golang学习网公众号了解相关技术文章。
-
860 收藏
-
843 收藏
-
826 收藏
-
809 收藏
-
792 收藏
-
Golang · Go教程 | 2天前 | 并发 · 闭包 · for range · 迁移 · Go教程 · Go 1.22 · Goroutine 闭包 循环变量 Go教程 Go 1.22 for range113 收藏
-
331 收藏
-
Golang · Go教程 | 2天前 | 单元测试 · 错误处理 · Go教程 · errors.Join · errors.Is · errors.Is Go错误处理 Go教程 errors.Join 多错误返回 批量校验352 收藏
-
Golang · Go教程 | 2天前 | Context · 超时控制 · Go教程 · http.Client · Transport · Go context 请求超时 Transport http.Client Client.Timeout ResponseHeaderTimeout218 收藏
-
Golang · Go教程 | 2天前 | 文件下载 · Go教程 · 审计日志 · 接口安全 · 路径穿越 · Go 文件下载 审计日志 HTTP接口 filepath.Clean 安全下载 路径穿越362 收藏
-
273 收藏
-
Golang · Go教程 | 2天前 | CI/CD · gitHub actions · Go教程 · 自托管 Runner · 持续集成 · Go 持续集成 CI Go test GitHub Actions self-hosted runner 自托管 runner340 收藏
-
124 收藏
-
Golang · Go教程 | 2天前 | HTTP · 文件下载 · Go教程 · Range请求 · ServeContent · 断点续传 Content-Range Go教程 HTTP Range ServeContent 206 Partial Content 视频拖动250 收藏
-
Golang · Go教程 | 3天前 | csv · Go教程 · 后端架构 · 流式响应 · 大文件导出 · 大文件下载 FLUSH CSV导出 Go教程 流式写出 csv.Writer rows.Next251 收藏
-
Golang · Go教程 | 3天前 | HTTP服务 · Go教程 · 后端开发 · 超时配置 · 服务稳定性 · net/http WriteTimeout HTTP超时 Go教程 ReadHeaderTimeout IdleTimeout140 收藏
-
Golang · Go教程 | 3天前 | 错误处理 · Context · 并发控制 · Go教程 · 并发控制 Go教程 context取消 context.WithCancelCause context.Cause342 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习