在 Debian 上“查 Golang 慢日志”通常分两种情况,我分别说明,你可以按需选择。
Go 本身没有像 MySQL 那样的慢日志机制,慢日志一般是:
func LoggingMiddleware(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 took %s", r.Method, r.URL.Path, cost)
}
})
}
启动服务:
go run main.go >> /var/log/myapp.log 2>&1
查看慢日志:
grep SLOW /var/log/myapp.log
Go 里常用 database/sql + mysql 驱动:
db.SetConnMaxLifetime(time.Minute)
db.SetMaxOpenConns(10)
但真正的慢日志在 MySQL 端:
sudo vi /etc/mysql/my.cnf
[mysqld]
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
重启:
sudo systemctl restart mysql
查看:
sudo less /var/log/mysql/slow.log
top
htop
iotop
找 go 或你的程序名
import _ "net/http/pprof"
go func() {
http.ListenAndServe("127.0.0.1:6060", nil)
}()
go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30
(pprof) top
(pprof) web
sudo strace -f -tt -T -p <pid>
可看到哪个 read/write/network 调用慢
| 场景 | 方法 |
|---|---|
| HTTP 慢 | 中间件记日志 |
| DB 慢 | MySQL slow log |
| 程序卡 | pprof |
| 系统级慢 | top / strace |
如果你能具体说一下:
我可以直接给你一份可用的 Debian + Go 慢日志方案。