Go应用通过Prometheus客户端暴露指标,Prometheus抓取后由Grafana展示。首先在Go服务中引入prometheus/client_golang,注册Counter、Gauge、Histogram等指标并启用/metrics接口;接着配置Prometheus的scrape_configs定时拉取目标实例指标;最后在Grafana中添加Prometheus数据源,使用PromQL查询如rate(http_requests_total[5m])或histogram_quantile(0.95, rate(request_duration_seconds_bucket[5m])),创建请求量、延迟等监控面板。还可导入模板ID 1860快速搭建仪表盘。完整链路为:Go暴露metrics → Prometheus采集存储 → Grafana可视化分析。

Go语言开发的服务如果需要做性能监控或业务指标观测,Grafana 是一个非常强大的可视化工具。它本身不采集数据,而是展示来自数据源(如 Prometheus、InfluxDB 等)的指标。要实现 Golang 应用的 Grafana 可视化监控,核心在于:暴露监控指标、选择合适的数据存储,并在 Grafana 中配置面板展示。
使用 Prometheus 客户端库是目前最主流的方式。通过 prometheus/client_golang 包,你可以轻松地在 Go 服务中注册并暴露 metrics。
安装依赖:
go get github.com/prometheus/client_golang/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp在 HTTP 服务中添加 metrics 接口:
立即学习“go语言免费学习笔记(深入)”;
func main() { // 注册默认的 metrics 收集器 http.Handle("/metrics", promhttp.Handler())// 示例:自定义一个计数器  
httpRequestsTotal := prometheus.NewCounter(  
    prometheus.CounterOpts{  
        Name: "http_requests_total",  
        Help: "Total number of HTTP requests",  
    },  
)  
prometheus.MustRegister(httpRequestsTotal)  
// 模拟请求计数  
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {  
    httpRequestsTotal.Inc()  
    w.Write([]byte("Hello World"))  
})  
http.ListenAndServe(":8080", nil)  }
启动服务后访问 http://localhost:8080/metrics,可以看到类似如下输出:
# HELP http_requests_total Total number of HTTP requests # TYPE http_requests_total counter http_requests_total 5Prometheus 负责定时从你的 Go 服务拉取 metrics 数据。你需要在 prometheus.yml 中配置 job:
确保 Prometheus 能访问到你的 Go 服务地址。启动 Prometheus 后,进入其 Web 界面(默认 9090 端口),在 “Status > Targets” 中确认目标状态为 UP,表示抓取正常。
安装并启动 Grafana(可通过 Docker 或系统包管理器安装),登录后(默认账号密码 admin/admin)进行以下操作:
rate(http_requests_total[5m]) 查看每秒请求数你还可以导入现成的模板,比如 Grafana 官方提供的 ID 为 1860 的 “Prometheus Stats” 面板,快速查看 Prometheus 自身及目标服务的基础指标。
除了计数器(Counter),你还可以使用:
例如监控请求耗时:
histogram := prometheus.NewHistogram(prometheus.HistogramOpts{ Name: "request_duration_seconds", Help: "HTTP request duration in seconds", Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0}, }) prometheus.MustRegister(histogram)// 在 handler 中记录 timer := prometheus.NewTimer(histogram) defer timer.ObserveDuration()
在 Grafana 中使用 PromQL:histogram_quantile(0.95, rate(request_duration_seconds_bucket[5m])) 展示 P95 延迟。
基本上就这些。整个链路是:Go 应用暴露 metrics → Prometheus 抓取存储 → Grafana 查询展示。这套方案稳定、灵活,适合大多数 Go 微服务监控场景。关键是把指标设计好,后续可视化就很自然了。
以上就是Golang如何使用Grafana可视化监控数据_Golang Grafana监控可视化实践详解的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号