温馨提示×

怎样用centos查golang慢日志

小樊
33
2026-09-09 03:58:43
栏目: 编程语言

在 CentOS 上“查 Golang 慢日志”,要看你说的慢日志是什么类型,常见有下面几种情况。我按最常见场景给你讲。


一、Golang 自己的程序慢(函数/请求慢)

1️⃣ 用 pprof 查(最推荐)

Go 自带性能分析工具。

开启 pprof(Web 服务)

import _ "net/http/pprof"
import "net/http"

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

CentOS 上分析

# 查看 30 秒 CPU 占用
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

常用命令:

top
list 函数名
web

查“慢在哪里”

  • cpu → 哪段代码耗时
  • goroutine → 是否阻塞
  • block / mutex → 锁竞争

2️⃣ 自己写“慢日志”

比如请求超过 500ms 就记日志:

start := time.Now()
handler()
cost := time.Since(start)
if cost > 500*time.Millisecond {
    log.Printf("SLOW: %s cost=%s", r.URL.Path, cost)
}

日志位置看你程序配置,一般在:

/var/log/xxx.log

二、Golang HTTP 服务(如 Gin / Echo)

Gin 中间件示例

func SlowLog() gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Next()
        if time.Since(start) > 500*time.Millisecond {
            log.Printf("SLOW %s %s %s",
                c.Request.Method,
                c.Request.URL.Path,
                time.Since(start))
        }
    }
}

三、系统/进程级慢(CentOS 层面)

1️⃣ 看系统负载

top
htop
uptime

2️⃣ 看某个 Go 进程

ps -ef | grep go
strace -p 进程ID

3️⃣ 看 IO 是否慢

iostat -x 1

四、数据库慢(Go 调 MySQL 等)

如果是 Go 调 MySQL 慢:

  • 开 MySQL 慢查询日志
slow_query_log = 1
long_query_time = 1
cat /var/log/mysql/slow.log

五、总结(快速判断)

场景 方法
代码慢 pprof
接口慢 中间件记慢日志
系统慢 top / iostat
数据库慢 MySQL 慢日志

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

  • ✅ 你是 Web 服务还是脚本
  • ✅ 用的 框架(Gin / Beego / 原生)
  • ✅ 慢的是 请求 / SQL / 计算

我可以直接给你一套可复制的配置和代码

0