在 CentOS 上“查 Golang 慢日志”,通常分两种场景:
下面按常见情况给你一套实用做法。
# 查看进程
ps -ef | grep your_go_app
# 查看程序日志文件
ls -l /var/log/your_go_app/
tail -f /var/log/your_go_app/access.log
常见慢日志关键字:
slowtimeoutcost=elapsed=took=例如:
grep -i slow /var/log/your_go_app/*.log
如果你用了 Nginx + Go:
tail -f /var/log/nginx/access.log
Nginx 默认有 $request_time:
log_format main '$remote_addr - $request_time $upstream_response_time $request';
查响应时间 > 1s 的请求:
awk '$NF>1' /var/log/nginx/access.log
func SlowLog(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 > time.Second {
log.Printf("SLOW %s %s cost=%s", r.Method, r.URL.Path, cost)
}
})
}
然后:
journalctl -u your_go_service | grep SLOW
import _ "net/http/pprof"
go func() {
http.ListenAndServe("0.0.0.0:6060", nil)
}()
# CPU
go tool pprof http://localhost:6060/debug/pprof/profile
# 阻塞
go tool pprof http://localhost:6060/debug/pprof/block
# traces
go tool pprof http://localhost:6060/debug/pprof/trace?seconds=10
top -p $(pidof your_go_app)
strace -p $(pidof your_go_app) -c
ss -tnp | grep your_go_app
vim /etc/my.cnf
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
mysqldumpslow -s t /var/log/mysql/slow.log
journalctl -u your_go_service -f
CentOS 查 Golang 慢日志 = 看应用日志 + Nginx 日志 + pprof + 系统资源
如果你愿意,可以告诉我:
我可以直接给你精准命令或代码。