Go 应用监控:从 A 到 Z 的指标与告警
在现代软件开发中,监控不是奢侈品,而是必需品。对于常用于高负载微服务和基础设施项目的 Go (Golang) 应用,配置得当的监控可以及时发现问题、优化性能并确保稳定运行。本文将从头开始讲解如何配置 Go 应用监控:从收集基本指标到配置告警和在 Grafana 中进行可视化。
为什么监控对 Go 应用很重要?
Go 是一种内置并发支持的编译型语言。Go 应用通常运行在关键系统中:从 API 网关到数据库。没有监控,您将面临以下风险:
- 遗漏内存或 goroutine 泄漏
- 未能发现性能退化
- 因未处理的错误而丢失数据
- 因资源不足而导致停机
正确的监控可以为您提供应用健康状况的完整视图:从 CPU 和内存使用情况到响应时间和错误率。
Go 监控的主要指标
在介绍工具之前,我们先确定哪些指标对 Go 应用至关重要:
系统指标
- CPU usage — 处理器负载
- Memory usage — 内存消耗(包括堆和栈)
- Goroutines count — 活跃 goroutine 数量
- GC stats — 垃圾回收器统计信息(时间、周期数)
- Open file descriptors — 打开的文件描述符数量
业务指标
- Request latency — 响应时间(p50、p95、p99)
- Request rate — 每秒请求数
- Error rate — 错误百分比
- Database connection pool — 连接池状态
Go 监控工具
Go 应用监控的标准技术栈包括:
- Prometheus — 指标收集和存储系统
- Grafana — 可视化和仪表板
- Alertmanager — 告警管理
- Go 客户端库 — 用于导出指标
在 Go 中配置 Prometheus 指标收集
让我们从实践开始。为了从 Go 应用导出指标,我们将使用官方库 prometheus/client_golang。
步骤 1:安装依赖
go get github.com/prometheus/client_golang/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp步骤 2:带指标的基本 HTTP 服务器
package main
import ( "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", "status"}, )
httpRequestDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "Histogram of HTTP request durations", Buckets: prometheus.DefBuckets, }, []string{"method", "endpoint"}, ))
func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration)}
func main() { http.Handle("/metrics", promhttp.Handler()) http.HandleFunc("/api/users", func(w http.ResponseWrit