答案:通过在Go服务中使用Prometheus客户端暴露指标,部署Prometheus抓取数据,并在Grafana中配置数据源和看板,可实现对Golang服务运行状态的可视化监控,关键步骤包括指标采集、时序存储与可视化展示。

想让Golang服务的运行状态一目了然,Grafana搭配合适的监控体系是最佳选择之一。核心思路是:在Go服务中采集指标,通过时序数据库存储,再用Grafana做可视化展示。下面一步步说明如何实现。
使用 prometheus/client_golang 是最常见的方式。先在项目中引入依赖:
go get github.com/prometheus/client_golang/prometheus go get github.com/prometheus/client_golang/prometheus/promhttp然后在服务中注册常用指标,比如请求计数、响应时间、Goroutine数量等:
示例代码:
立即学习“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", "status"}, )
// 请求时长直方图
httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Duration of HTTP requests in seconds",
Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0},
},
[]string{"method", "endpoint"},
))
func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration) }
func handler(w http.ResponseWriter, r http.Request) { start := time.Now() // 模拟业务处理 time.Sleep(100 time.Millisecond) httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path, "200").Inc() httpRequestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(time.Since(start).Seconds()) w.Write([]byte("Hello")) }
func main() { http.HandleFunc("/hello", handler) http.Handle("/metrics", promhttp.Handler()) http.ListenAndServe(":8080", nil) }
启动服务后,访问 :8080/metrics 就能看到Prometheus格式的指标输出。
Prometheus负责定时从Go服务拉取指标。配置 prometheus.yml:
scrape_configs: - job_name: 'go-service' static_configs: - targets: ['your-go-service-ip:8080']确保Prometheus能访问Go服务的 /metrics 接口。启动Prometheus后,访问其Web界面(默认9090端口),可用PromQL查询指标,如:
安装Grafana(可通过Docker、系统包或二进制方式),启动后访问3000端口。
步骤:
常用Panel配置示例:
sum(http_requests_total)
sum(rate(http_requests_total[1m]))
rate(http_request_duration_seconds_sum[5m]) / rate(http_request_duration_seconds_count[5m])
go_goroutines
可为不同接口、状态码设置变量(Variables),实现下拉筛选,提升看板灵活性。
除了基础指标,还可加入:
基本上就这些。搭建完成后,Grafana看板能实时反映Golang服务的健康状况,帮助快速定位性能瓶颈或异常。关键是指标要有业务意义,避免堆砌无用图表。
以上就是Golang服务监控看板 Grafana可视化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号