首先在Go应用中通过prometheus/client_golang暴露指标,再配置Prometheus抓取/metrics接口,最后在Grafana中添加Prometheus为数据源并创建或导入仪表盘实现可视化监控。

要在Golang中集成Grafana实现可视化监控,核心是先采集应用指标并暴露给Prometheus,再由Grafana连接Prometheus进行图形化展示。Grafana本身不直接接收数据,它依赖数据源(如Prometheus)来读取和展示监控信息。因此,关键步骤是:在Go服务中暴露监控指标,配置Prometheus抓取,最后在Grafana中导入仪表盘。
使用 prometheus/client_golang 库可以在Golang服务中暴露HTTP端点供Prometheus抓取。
安装依赖:
go get github.com/prometheus/client_golang/prometheus示例代码:暴露一个计数器和请求延迟直方图
立即学习“go语言免费学习笔记(深入)”;
package mainimport (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"method", "endpoint", "code"},
)
httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Duration of HTTP requests in seconds.",
Buckets: prometheus.DefBuckets,
},
[]string{"method", "endpoint"},
)
)
func init() {
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(httpRequestDuration)
}
func handler(w http.ResponseWriter, r http.Request) {
start := time.Now()
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path, "200").Inc()
time.Sleep(10 time.Millisecond) // 模拟处理时间
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello"))
httpRequestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(time.Since(start).Seconds())
}
func main() {
http.HandleFunc("/", handler)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
启动后,访问 :8080/metrics 可看到指标输出,Prometheus即可从此路径拉取数据。
编辑 prometheus.yml,添加你的Go服务为target:
scrape_configs:确保Prometheus能访问Go服务的 /metrics 接口。启动Prometheus后,在其Web界面(默认9090端口)可查询指标,如 http_requests_total。
启动Grafana(通常3000端口),登录后执行以下操作:
也可导入社区仪表盘模板,比如ID为 1860 的 “Go Metrics” 模板,快速查看Go运行时指标(GC、goroutines等)。
除了基本指标,还可收集:
若服务部署在Kubernetes,可通过ServiceMonitor(使用Prometheus Operator)自动发现目标。
基本上就这些。Golang负责暴露指标,Prometheus负责收集,Grafana负责展示。三者配合,即可实现完整的可视化监控链路。
以上就是如何在Golang中集成Grafana可视化监控的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号