在 Debian 系统下监控 Go 程序性能,通常可以从 操作系统层面、Go 运行时层面 和 应用层面 三个维度来做。下面给你一套比较实用、常用的方案。
top / htop查看 CPU、内存、负载:
top
htop
关注:
perf(Linux 性能分析神器)适合分析 CPU 热点:
sudo apt install linux-perf
perf top -p <pid>
或采样:
perf record -p <pid>
perf report
✅ 适合定位 Go 程序 CPU 占用高 的问题
strace / lsof分析系统调用和 IO:
strace -p <pid>
lsof -p <pid>
pprof(官方标准方案 ✅)HTTP 服务(最常见):
import (
_ "net/http/pprof"
"net/http"
)
func main() {
go func() {
http.ListenAndServe("0.0.0.0:6060", nil)
}()
}
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
常用命令:
top
list 函数名
web
✅ 定位:
go tool pprof http://localhost:6060/debug/pprof/heap
关注:
alloc_space(累计分配)inuse_space(当前占用)curl http://localhost:6060/debug/pprof/goroutine?debug=2
重点看:
runtime/metrics(Go 1.16+ 推荐)比 runtime.MemStats 更底层、更完整:
import "runtime/metrics"
var sample = make([]metrics.Sample, len(metrics.All()))
metrics.Read(sample)
可监控:
✅ 适合做 长期监控 & 告警
go get github.com/prometheus/client_golang/prometheus
暴露指标:
http.Handle("/metrics", promhttp.Handler())
可监控:
例如:
GODEBUG=gctrace=1GODEBUG=gctrace=1 ./myapp
输出示例:
gc 12 @3.456s 0%: 0.12+0.45+0.03 ms
关注:
GODEBUG=schedtrace=1000 ./myapp
Debian + Docker 常见坑:
go version
✅ pprof + top + gctrace
✅ pprof(按需)
✅ Prometheus + Grafana
✅ runtime/metrics
| 问题 | 工具 |
|---|---|
| CPU 高 | pprof profile / perf |
| 内存涨 | pprof heap |
| goroutine 泄漏 | pprof goroutine |
| GC 频繁 | gctrace |
| 请求慢 | trace / 自定义 metrics |
| 系统瓶颈 | top / strace / perf |
如果你愿意,可以告诉我:
我可以给你更精确的监控和排查方案。