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

Go语言(Golang)在构建高性能服务时被广泛使用,而监控是保障服务稳定运行的关键环节。将Golang应用与Grafana集成,可以实现指标的可视化与实时告警。最常见的方式是通过Prometheus采集Go应用的指标,再由Grafana展示。下面介绍如何实现这一集成。
1. 在Golang中暴露监控指标
要让Grafana可视化数据,首先需要让Go应用产生可采集的监控指标。使用 prometheus/client_golang 是最主流的方式。
示例代码:
package mainimport ( "net/http" "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"}, ) )
func init() { prometheus.MustRegister(httpRequestsTotal) }
func handler(w http.ResponseWriter, r *http.Request) { httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path, "200").Inc() w.Write([]byte("Hello from Go!")) }
func main() { http.Handle("/metrics", promhttp.Handler()) http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
这段代码注册了一个计数器,并在根路径处理请求时递增。/metrics 路径暴露Prometheus格式的指标。
立即学习“go语言免费学习笔记(深入)”;
2. 配置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”。
3. Grafana中添加Prometheus数据源
启动Grafana(默认端口3000),登录后进行以下操作:
- 进入“Configuration” → “Data Sources” → “Add data source”
- 选择“Prometheus”
- URL填写Prometheus服务地址,如 http://localhost:9090
- 点击“Save & Test”,确认连接成功
4. 创建可视化仪表盘
在Grafana中创建新Dashboard,添加Panel,使用PromQL查询Go应用的指标:
- 查询请求总量:rate(http_requests_total[5m])
- 按接口维度查看:sum by (endpoint) (rate(http_requests_total[5m]))
选择图表类型(如折线图、柱状图),调整时间范围,即可实现实时监控。
基本上就这些。Golang通过Prometheus暴露指标,Prometheus定期抓取,Grafana连接Prometheus作为数据源并展示图表,三者配合实现完整的监控可视化链路。这套方案轻量、高效,适合大多数Go服务场景。










