首先通过prometheus/client_golang在Go应用中暴露指标,接着配置Prometheus抓取目标,最后在Grafana中添加Prometheus数据源并创建仪表盘展示监控数据,实现完整可观测性链路。

Go语言(Golang)在构建高性能服务时被广泛使用,而监控是保障服务稳定运行的关键环节。将Golang应用与Grafana集成,可以实现指标的可视化与实时告警。最常见的方式是通过Prometheus采集Go应用的指标,再由Grafana展示。下面介绍如何实现这一集成。
要让Grafana可视化数据,首先需要让Go应用产生可采集的监控指标。使用 prometheus/client_golang 是最主流的方式。
示例代码:
package main
<p>import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)</p><p>var (
// 定义一个计数器,记录请求次数
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "endpoint", "code"},
)
)</p><p>func init() {
prometheus.MustRegister(httpRequestsTotal)
}</p><p>func handler(w http.ResponseWriter, r *http.Request) {
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path, "200").Inc()
w.Write([]byte("Hello from Go!"))
}</p><p>func main() {
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}</p>这段代码注册了一个计数器,并在根路径处理请求时递增。/metrics 路径暴露Prometheus格式的指标。
立即学习“go语言免费学习笔记(深入)”;
Prometheus需要知道从哪里拉取指标。修改prometheus.yml配置文件:
scrape_configs:
- job_name: 'go-app'
static_configs:
- targets: ['localhost:8080']
确保Prometheus能访问Go应用的8080端口。启动Prometheus后,访问其Web界面(默认9090端口),在“Status” → “Targets”中确认目标状态为“UP”。
启动Grafana(默认端口3000),登录后进行以下操作:
在Grafana中创建新Dashboard,添加Panel,使用PromQL查询Go应用的指标:
选择图表类型(如折线图、柱状图),调整时间范围,即可实现实时监控。
基本上就这些。Golang通过Prometheus暴露指标,Prometheus定期抓取,Grafana连接Prometheus作为数据源并展示图表,三者配合实现完整的监控可视化链路。这套方案轻量、高效,适合大多数Go服务场景。
以上就是Golang与Grafana可视化监控集成的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号