首先集成prometheus/client_golang库,定义并注册指标如直方图记录HTTP请求延迟;接着在Golang应用中暴露/metrics接口供Prometheus抓取;然后配置Prometheus的scrape_configs以目标地址获取指标;最后在Grafana中添加Prometheus数据源并导入4475模板实现可视化。需注意网络可达性、高基数问题及生产环境安全防护。

Golang 应用中要实现指标可视化,通常需要先采集运行时数据(如请求延迟、QPS、内存使用等),然后将这些指标暴露给 Prometheus 抓取,最后通过 Grafana 展示。整个流程不复杂,核心在于正确集成指标收集与暴露机制。
Golang 中最常用的指标库是 prometheus/client_golang。你需要在项目中引入它,并定义要收集的指标类型,比如计数器(Counter)、直方图(Histogram)、仪表(Gauge)等。
- 安装依赖:go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/http
注册一个 handler,把 prometheus 的默认收集器暴露出来:
立即学习“go语言免费学习笔记(深入)”;
http.Handle("/metrics", promhttp.Handler())
- 定义并使用自定义指标,例如记录 HTTP 请求耗时:创建一个直方图:
var httpDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request latency in seconds",
},
[]string{"path", "method", "status"},
)
启动时注册到全局收集器:
prometheus.MustRegister(httpDuration)
在中间件中观测请求耗时:
func InstrumentHandler(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
duration := time.Since(start).Seconds()
httpDuration.WithLabelValues(r.URL.Path, r.Method, strconv.Itoa(status)).Observe(duration)
}
}
Prometheus 需要知道你的应用地址和 /metrics 路径。编辑 prometheus.yml,加入 job 配置:
scrape_configs:
- job_name: 'go-app'
static_configs:
- targets: ['localhost:8080'] # 替换为你的应用地址
重启 Prometheus 后,在 Web 界面(http://localhost:9090)查询你的指标,比如 http_request_duration_seconds,确认数据已抓取。
启动 Grafana 并登录后,先添加 Prometheus 为数据源:
- 进入 Configuration > Data Sources > Add data source- 选择 Prometheus
- 填写 URL(通常是 http://localhost:9090)
- 保存测试通过
- 创建新 Dashboard 或导入现成模板:推荐使用社区编号为 4475 的 "Go Metrics" 模板:
- 点击 + Import
- 输入 4475
- 选择你刚配置的 Prometheus 数据源
这个模板会自动展示 GC 次数、goroutines 数量、内存分配、HTTP 延迟等关键指标。
确保你的应用暴露的 /metrics 接口可被 Prometheus 访问,防火墙或网络策略可能阻止抓取。
避免创建过多 label 组合,否则会导致“高基数”问题,影响 Prometheus 性能。
生产环境中建议加 basic auth 或路径保护,防止 /metrics 被公开访问。
如果应用是分布式的,每个实例都要暴露 metrics,Prometheus 会分别抓取,Grafana 自动聚合展示。
基本上就这些。只要指标正确暴露,Prometheus 正常抓取,Grafana 就能画出清晰的图表。调试时先查 /metrics 输出,再看 Prometheus 是否有数据,最后在 Grafana 查表达式是否匹配。流程通了之后,加新指标也很简单。
以上就是Golang如何使用Grafana可视化指标的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号