首先集成Prometheus客户端库,定义请求量、响应时间等指标并暴露/metrics接口;接着配置Prometheus抓取目标,确保状态为UP;最后通过Grafana添加数据源并导入或创建Dashboard展示QPS和延迟等关键指标。

在Golang服务开发中,系统可观测性至关重要。Prometheus 和 Grafana 是目前最流行的开源监控与可视化组合。通过集成 Prometheus 客户端库,可以轻松暴露指标数据,再由 Grafana 展示成直观图表。下面介绍如何在 Golang 项目中实践 Prometheus + Grafana 监控。
Prometheus 提供了官方的 Go 客户端库 prometheus/client_golang,用于在应用中定义和暴露指标。
安装依赖:
go get github.com/prometheus/client_golang/prometheus go get github.com/prometheus/client_golang/prometheus/promhttp在代码中注册常用指标类型,如计数器(Counter)、直方图(Histogram)、仪表(Gauge)等。
立即学习“go语言免费学习笔记(深入)”;
以一个 HTTP 服务为例,统计请求次数、响应时间等常见指标。
示例代码:
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.NewHistogram(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request latency in seconds.",
Buckets: prometheus.DefBuckets,
},
))
func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration) }
func handler(w http.ResponseWriter, r *http.Request) { start := time.Now()
// 模拟业务逻辑
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, Prometheus!"))
// 记录指标
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path, "200").Inc()
httpRequestDuration.Observe(time.Since(start).Seconds())}
启动一个 /metrics 接口供 Prometheus 抓取:
func main() { http.HandleFunc("/", handler) http.Handle("/metrics", promhttp.Handler()) // 暴露指标 http.ListenAndServe(":8080", nil) }修改 prometheus.yml 配置文件,添加你的 Go 应用为监控目标。
scrape_configs: - job_name: 'go-app' static_configs: - targets: ['your-go-app-host:8080']启动 Prometheus 服务后,访问其 Web 界面(默认 9090 端口),在 “Targets” 中确认状态为 UP,表示抓取正常。
启动 Grafana(通常使用 Docker):
docker run -d -p 3000:3000 --name=grafana grafana/grafana-enterprise登录 Grafana(默认账号/密码:admin/admin),添加 Prometheus 为数据源,地址填入 Prometheus 服务地址(如 http://host:9090)。
导入或创建 Dashboard:
基本上就这些。只要在 Golang 中正确暴露指标,Prometheus 抓取,Grafana 展示,整套链路就能跑通。关键是指标设计要合理,比如按 endpoint、method、status 分维度,才能支持有效分析。不复杂但容易忽略细节,比如 histogram buckets 设置、label 维度过载等。保持简洁清晰最重要。
以上就是如何在Golang中使用Prometheus+Grafana监控_Golang Prometheus Grafana监控实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号