用 go-zero 内置 Prometheus 指标接入 Grafana,5 分钟打通微服务监控链路
【免费下载链接】go-zeroA cloud-native Go microservices framework with cli tool for productivity.项目地址: https://gitcode.com/GitHub_Trending/go/go-zero
需要观测 go-zero 服务的接口延迟和错误率时,不必额外引入埋点库:框架自带 Prometheus 兼容的指标出口和 RPC 采集拦截器,配合 Grafana,启动后 5 分钟内就能得到一块可查询的监控看板。
整体方案一览
服务启动 → 9101 端口暴露 /metrics → Prometheus 抓取 → Grafana 画图,全程只用框架内置能力。
配置与接入
开启指标出口
在你的服务配置文件中加一段 Prometheus 配置,指标端口即随服务自动启动。
Prometheus: Host: 0.0.0.0 # 监听地址,留空则不启用 Port: 9101 # 默认 9101 Path: /metrics # 默认 /metricsServiceConf.SetUp执行时会自动调用 core/prometheus/agent.go 的 StartAgent 拉起独立 HTTP 端口(见 core/service/serviceconf.go),无需手写 main 逻辑。
挂载采集拦截器
zrpc 服务只需打开一个开关,RPC 调用统计就会自动挂上。
Middlewares: Prometheus: truezrpc/server.go 检测到该开关后会注册UnaryPrometheusInterceptor,对每个方法记录耗时与状态码,业务代码零改动;指标定义见 zrpc/internal/serverinterceptors/prometheusinterceptor.go。
确认指标可读
启动后直接请求出口,是最快的验证方式。
curl -s http://localhost:9101/metrics | grep rpc_server能打印出rpc_server_requests_*开头的两个指标族,说明出口与拦截器都已就位。
看效果
# HELP rpc_server_requests_duration_ms rpc server requests duration(ms). # TYPE rpc_server_requests_duration_ms histogram rpc_server_requests_duration_ms_bucket{method="/user.UserService/GetUser",le="5"} 34 rpc_server_requests_duration_ms_bucket{method="/user.UserService/GetUser",le="50"} 56 rpc_server_requests_code_total{code="0",method="/user.UserService/GetUser"} 120这意味着:GetUser 的绝大多数请求落在 50ms 桶内,错误码 0(成功)占绝对多数。把它接进 Prometheus 后,Grafana 里直接按 method 维度画 P95 延迟和错误率曲线即可。
进阶:把链路串起来
如果你需要进一步定位问题,有两个可选方向:
- 持续剖析:配置里加 Profiling 段并指定 ServerAddr 指向 Pyroscope 实例,internal/profiling/profiling.go 会在 CPU 负载超过阈值(默认 70%)时自动采集 CPU、goroutine、内存数据并上传,无需重启服务;
- 分布式追踪:
ServiceConf.Telemetry字段支持按 OpenTelemetry 协议上报 span,配合采集后端可从监控指标下钻到具体调用链。
两者都是配置驱动,不开启时对服务无任何影响。
踩坑与调优
- 采集间隔:scrape_interval 降到 5s 以内能看更细的波动,但时间序列数量翻倍,先评估 Prometheus 存储量;
- 桶分布:默认直方图桶覆盖 1~5000ms,如果你的接口 SLA 在几十毫秒内,可参照 core/metric/histogram.go 自定义更密的桶,让 P95 落在有意义的区间;
- 配置字段:较新版本中
ServiceConf.Prometheus标注了 Deprecated 并提示改用 DevServer 段,升级后请确认当前版本里指标出口的实际开启方式,避免升级后看板断流。
后续可探索
- 基于
rpc_server_requests_code_total写告警规则,把错误率与 P95 延迟推送到值班渠道; - 引入 eBPF 在内核层采集性能数据,不依赖进程内埋点;
- 对接 OpenTelemetry 全链路标准,统一 trace、metric、log 三种观测数据。
【免费下载链接】go-zeroA cloud-native Go microservices framework with cli tool for productivity.项目地址: https://gitcode.com/GitHub_Trending/go/go-zero
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考