温馨提示×

centos golang日志为何为空

小樊
39
2026-10-09 00:20:01
栏目: 编程语言

在 CentOS 上运行 Go 程序时“日志为空”,常见原因和排查思路如下(按出现频率排序):


1. 日志写到了 stdout / stderr,但你没看到

Go 程序默认:

  • fmt.Println → stdout
  • log.Println → stderr

常见场景

  • 用 nohup ./app & 但没重定向
  • 用 systemd 但没看 journalctl
  • 在 IDE 里运行但程序以服务方式启动

解决

# nohup 方式
nohup ./app > app.log 2>&1 &

# systemd
journalctl -u your-service -f

2. systemd 下日志没配置

如果你用 systemd 启动:

[Service]
ExecStart=/opt/app/app
# 没写 StandardOutput / StandardError

默认日志会进 journal,但:

  • 你没用 journalctl
  • 或日志级别被过滤

建议配置

StandardOutput=journal
StandardError=journal

然后:

journalctl -u your-service

3. 日志库没初始化 / 配置错误

如果你用了 log、zap、logrus 等:

示例错误

log.SetOutput(nil) // 日志直接没了

或:

logger, _ := zap.NewProduction()
// 但没调用 logger.Info(...)

检查

  • 是否调用了 logger.Info/Warn/Error
  • 是否有 log.SetOutput(file)
  • 文件权限是否可写

4. 日志文件存在但无内容(缓冲问题)

  • 程序崩了,没 flush
  • 使用了带 buffer 的 writer 但没 Sync()

zap 示例

defer logger.Sync()

logrus

log.SetOutput(os.Stdout)

5. SELinux 阻止写日志

CentOS 默认开启 SELinux:

getenforce

如果为 Enforcing,可能:

  • 不能写 /var/log/app
  • 不能写非标准目录

验证

ausearch -m avc -ts recent

临时验证

setenforce 0

6. 工作目录不对,日志写到了别的地方

log.SetOutput(os.Create("app.log"))

如果你用 systemd:

WorkingDirectory=/opt/app

否则日志可能在 / 或未知目录。


7. 程序根本没执行到日志代码

  • os.Exit() 提前退出
  • panic 在日志前
  • init() 中出错

排查

strace -f -e trace=write ./app

快速自查清单 ✅

  1. 你是怎样启动程序的?(nohup / systemd / docker)
  2. 日志是 stdout 还是文件?
  3. 文件是否存在?权限?
  4. journalctl 有没有内容?
  5. getenforce 是什么?

如果你愿意,可以贴:

  • 启动方式(systemd / shell)
  • 日志相关 Go 代码
  • CentOS 版本

我可以直接帮你定位到具体原因。

0 踩