如何在Golang中集成Grafana可视化监控

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

如何在Golang中集成Grafana可视化监控

要在Golang中集成Grafana实现可视化监控,核心是先采集应用指标并暴露给Prometheus,再由Grafana连接Prometheus进行图形化展示。Grafana本身不直接接收数据,它依赖数据源(如Prometheus)来读取和展示监控信息。因此,关键步骤是:在Go服务中暴露监控指标,配置Prometheus抓取,最后在Grafana中导入仪表盘。

1. 在Go应用中暴露监控指标

使用 prometheus/client_golang 库可以在Golang服务中暴露http端点供Prometheus抓取。

安装依赖:

go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp

示例代码:暴露一个计数器和请求延迟直方图

立即学习go语言免费学习笔记(深入)”;

package main

import (
  “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即可从此路径拉取数据。

2. 配置Prometheus抓取Go服务

编辑 prometheus.yml,添加你的Go服务为target:

如何在Golang中集成Grafana可视化监控

集简云

软件集成平台,快速建立企业自动化与智能化

如何在Golang中集成Grafana可视化监控 22

查看详情 如何在Golang中集成Grafana可视化监控

scrape_configs:
  – job_name: ‘go-service’
    static_configs:
      – targets: [‘localhost:8080’]

确保Prometheus能访问Go服务的 /metrics 接口。启动Prometheus后,在其Web界面(默认9090端口)可查询指标,如 http_requests_total

3. Grafana连接Prometheus并创建仪表盘

启动Grafana(通常3000端口),登录后执行以下操作:

  • 进入 Configuration > Data Sources,添加 Prometheus
  • URL 填写 Prometheus 的地址(如 http://localhost:9090)
  • 点击 “Save & Test” 确保连接成功
  • 进入 Create > Dashboard,新建面板
  • 选择 Prometheus 数据源,输入 PromQL 查询,例如:
    rate(http_requests_total[5m])

    histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
  • 设置图表类型(如折线图、柱状图),调整时间范围和刷新频率

也可导入社区仪表盘模板,比如ID为 1860 的 “Go Metrics” 模板,快速查看Go运行时指标(GC、goroutines等)。

4. 可选:自动上报或高级指标

除了基本指标,还可收集:

  • Goroutine 数量:prometheus.NewGaugeFunc 包装 runtime.NumGoroutine()
  • 内存使用:使用 runtime.ReadMemStats 并注册自定义Gauge
  • 业务指标:如订单数、缓存命中率等,用Counter或Gauge记录

若服务部署在kubernetes,可通过ServiceMonitor(使用Prometheus operator)自动发现目标。

基本上就这些。Golang负责暴露指标,Prometheus负责收集,Grafana负责展示。三者配合,即可实现完整的可视化监控链路。

上一篇
下一篇
text=ZqhQzanResources