温馨提示×

debian golang日志报错怎么查

小樊
43
2026-09-01 05:17:12
栏目: 编程语言

在 Debian 上运行 Go(Golang)程序时遇到“日志报错”,一般可以按下面几个方向来定位、查看和分析


一、先确认“报错”来自哪里

1. 程序自身日志

Go 程序常见的日志来源:

  • log.Println / log.Fatal
  • 第三方日志库(zap、logrus、slog)
  • 自己写到文件的日志

查看方式:

# 如果程序在前台运行
./yourapp

# 如果日志写到文件
tail -f /var/log/yourapp.log

2. systemd 服务(最常见)

如果 Go 程序是通过 systemd 启动的:

# 查看服务状态
systemctl status yourapp.service

# 查看实时日志
journalctl -u yourapp.service -f

# 查看最近 100 行
journalctl -u yourapp.service -n 100

3. 标准错误(stderr)

Go 的 panic、未捕获错误通常输出到 stderr:

# 运行并保存错误
./yourapp 2> error.log
cat error.log

二、常见 Go 报错类型 & 排查方法

1. panic(程序崩溃)

典型日志:

panic: runtime error: invalid memory address
goroutine 1 [running]:

排查:

  • goroutine 堆栈
  • 定位到具体 .go 文件和行号
  • 是否空指针、数组越界、并发写 map

2. 端口被占用

listen tcp :8080: bind: address already in use
# 查看端口占用
ss -ltnp | grep 8080
# 或
lsof -i:8080

3. 权限问题(Debian 常见)

permission denied

常见原因:

  • 非 root 绑定 80/443
  • 日志目录无写权限
ls -l /var/log/yourapp
id yourappuser

4. 依赖 / 环境错误

exec: "gcc": executable file not found

Debian 上常缺依赖:

sudo apt update
sudo apt install -y build-essential

三、开启更详细的日志

1. 设置环境变量

GODEBUG=http2debug=2 ./yourapp
GOTRACEBACK=all ./yourapp

2. 使用 slog(Go 1.21+)

logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
    Level: slog.LevelDebug,
}))

四、快速排查 checklist

✅ 程序怎么启动的(前台 / systemd / docker)
✅ 报错是 panic 还是普通 error
✅ 日志里是否有文件路径和行号
✅ 是否是权限 / 端口 / 依赖问题
✅ 是否能本地复现


五、如果你愿意,我可以更具体地帮你

你可以直接贴:

  • 报错日志内容
  • 启动方式(systemd / 脚本 / docker)
  • Debian 版本(cat /etc/os-release
  • Go 版本(go version

我可以帮你逐行分析报错原因

0