在 CentOS 上排查 Go(Golang)程序慢日志 / 性能慢问题,通常分为几种场景。下面按「最常见 → 进阶」给你一套可操作方案。
Go 不会像 MySQL / Nginx 那样自动输出慢日志,慢通常来自:
所以需要 自己埋点或借助工具。
func SlowLogMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
cost := time.Since(start)
if cost > 500*time.Millisecond {
log.Printf("[SLOW] %s %s cost=%s", r.Method, r.URL.Path, cost)
}
})
}
使用:
http.Handle("/", SlowLogMiddleware(yourHandler))
日志示例:
[SLOW] GET /api/user cost=1.2s
# 开启
vi /etc/my.cnf
[mysqld]
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 0.5
systemctl restart mysqld
# 查看
tail -f /var/log/mysql/slow.log
db, _ := sql.Open("mysql", dsn)
db.SetConnMaxLifetime(time.Minute)
或在 ORM 中开启:
Logger: logger.Default.LogMode(logger.Info)import _ "net/http/pprof"
go func() {
http.ListenAndServe("0.0.0.0:6060", nil)
}()
# 查看接口耗时
go tool pprof http://localhost:6060/debug/pprof/profile
# 查看阻塞
go tool pprof http://localhost:6060/debug/pprof/block
go install github.com/uber/go-torch@latest
go-torch -u http://localhost:6060
GODEBUG=gctrace=1 ./your_app
示例:
gc 12 @3.2s 5%: 0.5+1.2+0.3 ms clock
如果 pause 很大,说明 GC 影响性能。
top
iostat -x 1
vmstat 1
ss -tanp
tcpdump -i eth0 port 8080
✅ 生产环境最佳实践
如果你愿意,可以告诉我:
我可以直接帮你写 针对性的慢日志方案。