答案是通过引入Prometheus client_golang库,在Go项目中定义、注册并更新自定义指标,再通过HTTP暴露/metrics端点供Prometheus抓取。具体步骤包括:1. 安装client_golang库;2. 使用Counter、Gauge等类型定义业务指标;3. 在init函数中注册指标;4. 于业务逻辑中更新指标值;5. 通过promhttp.Handler()暴露metrics接口;6. 配置Prometheus目标抓取该端点,最终实现监控数据采集与查询。

在Go项目中接入Prometheus自定义指标采集,核心是使用官方提供的 client_golang 库暴露业务相关的监控数据。整个过程包括定义指标、注册、更新数值,并通过HTTP服务暴露给Prometheus抓取。
安装Go的Prometheus客户端:
go get github.com/prometheus/client_golang/prometheus这两个包分别用于定义指标和提供HTTP处理器来暴露指标。
Prometheus支持多种指标类型:Counter(计数器)、Gauge(当前值)、Histogram(直方图)、Summary(摘要)。根据业务场景选择合适类型。
立即学习“go语言免费学习笔记(深入)”;
例如,定义一个请求计数器和一个处理耗时的直方图:
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests made.",
},
[]string{"method", "endpoint", "status"},
)
requestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request latency in seconds.",
Buckets: prometheus.DefBuckets,
},
[]string{"method", "endpoint"},
)
)
定义后的指标需要注册到默认的Registry中,才能被暴露出来:
func init() {
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(requestDuration)
}
也可以创建自定义Registry,但通常使用默认即可。
在处理HTTP请求的地方记录数据:
func handler(w http.ResponseWriter, r http.Request) {
start := time.Now()
// 模拟业务逻辑
time.Sleep(100 time.Millisecond)
// 更新计数器
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path, "200").Inc()
// 更新耗时
requestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(time.Since(start).Seconds())
w.Write([]byte("OK"))
}
启动一个HTTP服务,将指标通过 /metrics 接口暴露:
func main() {
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", handler)
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
启动后访问 http://localhost:8080/metrics 可看到类似如下内容:
# HELP http_requests_total Total number of HTTP requests made.在Prometheus配置文件中添加目标:
scrape_configs:重启Prometheus后,在Web UI中就能查询自定义指标。
基本上就这些。关键在于合理设计指标名称和标签,避免 cardinality 过高,同时确保性能开销可控。
以上就是Golang如何实现Prometheus自定义指标采集的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号