温馨提示×

怎样查centos golang慢日志

小樊
38
2026-10-06 01:39:28
栏目: 编程语言

在 CentOS 上排查 Go(Golang)程序慢日志 / 性能慢问题,通常分为几种场景。下面按「最常见 → 进阶」给你一套可操作方案。


一、先明确:Go 本身没有“慢日志”

Go 不会像 MySQL / Nginx 那样自动输出慢日志,慢通常来自:

  • HTTP 接口响应慢
  • 数据库 / 外部调用慢
  • GC 停顿
  • 锁竞争
  • 协程阻塞

所以需要 自己埋点或借助工具。


二、最常用:HTTP 接口慢日志(推荐)

1️⃣ 手写中间件(最简单)

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

三、数据库慢日志(非常常见)

MySQL(CentOS)

# 开启
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

Go 层 SQL 慢日志

db, _ := sql.Open("mysql", dsn)
db.SetConnMaxLifetime(time.Minute)

或在 ORM 中开启:

  • GORM:Logger: logger.Default.LogMode(logger.Info)
  • sqlx:自己包一层

四、Go 官方性能分析(最专业)

1️⃣ 开启 pprof(强烈推荐)

import _ "net/http/pprof"

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

2️⃣ 本地分析

# 查看接口耗时
go tool pprof http://localhost:6060/debug/pprof/profile

# 查看阻塞
go tool pprof http://localhost:6060/debug/pprof/block

3️⃣ 火焰图(最直观)

go install github.com/uber/go-torch@latest
go-torch -u http://localhost:6060

五、GC 导致的“偶发慢”

查看 GC 日志

GODEBUG=gctrace=1 ./your_app

示例:

gc 12 @3.2s 5%: 0.5+1.2+0.3 ms clock

如果 pause 很大,说明 GC 影响性能。


六、系统级慢定位(CentOS)

CPU / IO

top
iostat -x 1
vmstat 1

网络慢

ss -tanp
tcpdump -i eth0 port 8080

七、推荐组合方案(实战)

✅ 生产环境最佳实践

  • HTTP 慢日志(>500ms)
  • pprof(按需开启)
  • 数据库慢日志
  • 日志接入 ELK / Loki

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

  • Go 版本
  • 是 Web 服务 / 后台任务 / 微服务?
  • 慢在哪一步(接口 / DB / CPU)

我可以直接帮你写 针对性的慢日志方案。

0 踩