在 CentOS 上“定位 Golang 慢日志”,通常分几种场景。下面按最常见需求给你一套实用思路和命令。
例如 Gin / Echo / net/http 接口响应慢
✅ 解决方案:在代码里加慢请求日志(中间件)
func SlowLogMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
cost := time.Since(start)
if cost > 200*time.Millisecond {
log.Printf("[SLOW] %s %s cost=%s", c.Request.Method, c.Request.URL.Path, cost)
}
}
}
CentOS 上运行:
./your_app 2>&1 | tee app.log
grep SLOW app.log
Golang 本身不记录慢 SQL,需要:
vim /etc/my.cnf
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 0.5
重启:
systemctl restart mysqld
查看:
less /var/log/mysql/slow.log
用 pprof(最专业)
import _ "net/http/pprof"
go func() {
http.ListenAndServe("0.0.0.0:6060", nil)
}()
go tool pprof http://localhost:6060/debug/pprof/profile
分析:
top
web
CentOS 常用排查命令:
top
htop
iotop
netstat -antp | grep ESTABLISHED
df -h
dmesg | tail
✅ Web 服务
✅ 数据库
✅ Go 程序
我可以直接给你可复制的慢日志方案。