Go应用集成Prometheus需引入client_golang库,定义并注册计数器、直方图等指标,通过http.Handle暴露/metrics端点,Prometheus配置scrape任务定时抓取,实现监控数据采集与可视化。

Go应用集成Prometheus监控,核心是暴露符合Prometheus格式的指标接口,并让Prometheus服务定期抓取。实现方式简单直接,主要依赖官方提供的客户端库。
使用官方prometheus/client_golang库来注册和暴露指标。通过go mod管理依赖:
go get github.com/prometheus/client_golang/prometheus确保项目中正确引入后,就可以定义和注册自定义或内置指标。
在代码中创建计数器、直方图、摘要等类型的指标。例如,记录HTTP请求次数和响应耗时:
立即学习“go语言免费学习笔记(深入)”;
counter := prometheus.NewCounter(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests made.",
})
histogram := prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Duration of HTTP requests in seconds.",
Buckets: prometheus.DefBuckets,
})
<p>prometheus.MustRegister(counter)
prometheus.MustRegister(histogram)</p>实际处理请求时更新指标值:
counter.Inc() histogram.Observe(duration.Seconds())
Prometheus通过HTTP抓取指标数据,需在Go服务中开启一个路由返回指标内容。通常使用net/http启动一个单独的监听端口或复用主服务:
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
启动服务后访问 http://localhost:8080/metrics 可看到文本格式的指标输出,如:
# HELP http_requests_total Total number of HTTP requests made.在prometheus.yml中添加job,指向你的Go服务地址:
scrape_configs:
- job_name: 'go-service'
static_configs:
- targets: ['your-go-app-ip:8080']
Prometheus会定时从/metrics拉取数据,完成采集。重启Prometheus服务使配置生效后,在Prometheus UI中即可查询对应指标。
基本上就这些。只要暴露了标准格式的metrics接口,Prometheus就能自动识别并存储数据,后续可结合Grafana做可视化展示。关键是指标命名合理、标签设计清晰,避免高基数问题。
以上就是Golang如何集成Prometheus监控指标采集的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号