温馨提示×

怎么用centos查golang慢日志

小樊
42
2026-10-03 03:49:25
栏目: 编程语言

在 CentOS 上“查 Golang 慢日志”,通常分两种场景:

  1. 你自己的 Go 程序写了慢日志(如 HTTP 慢请求、SQL 慢查询)
  2. 想分析 Go 程序性能(CPU / 阻塞 / trace)来定位“慢”

下面按常见情况给你一套实用做法。


一、先确认:Go 程序有没有“慢日志”

1. 看程序是否自己打印了慢日志

# 查看进程
ps -ef | grep your_go_app

# 查看程序日志文件
ls -l /var/log/your_go_app/
tail -f /var/log/your_go_app/access.log

常见慢日志关键字:

  • slow
  • timeout
  • cost=
  • elapsed=
  • took=

例如:

grep -i slow /var/log/your_go_app/*.log

二、如果是 Web 服务(HTTP 慢请求)

1. 用 access 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

三、Go 程序自身加“慢日志”(推荐)

1. HTTP 中间件记录慢请求

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

四、用 pprof 查“为什么慢”(非常关键)

1. 开启 pprof

import _ "net/http/pprof"

go func() {
    http.ListenAndServe("0.0.0.0:6060", nil)
}()

2. CentOS 上采集

# 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

五、系统级排查(Go 程序卡)

1. 看 CPU / 内存

top -p $(pidof your_go_app)

2. 看系统调用慢不慢

strace -p $(pidof your_go_app) -c

3. 看网络慢不慢

ss -tnp | grep your_go_app

六、如果是数据库慢(Go + MySQL)

MySQL 慢日志

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

七、用 systemd 查 Go 服务日志

journalctl -u your_go_service -f

总结一句话

CentOS 查 Golang 慢日志 = 看应用日志 + Nginx 日志 + pprof + 系统资源

如果你愿意,可以告诉我:

  • Go 是 web / 微服务 / 脚本?
  • 是否用 Gin / Beego / gRPC?
  • 慢在哪(接口 / DB / CPU)?

我可以直接给你精准命令或代码。

0 踩