首页 > 后端开发 > Golang > 正文

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

P粉602998670
发布: 2025-11-06 16:52:02
原创
705人浏览过
首先在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:

集简云
集简云

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

集简云 22
查看详情 集简云
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负责展示。三者配合,即可实现完整的可视化监控链路。

以上就是如何在Golang中集成Grafana可视化监控的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号