温馨提示×

centos nohup日志怎么保存

小樊
53
2026-08-04 09:41:48
栏目: 智能运维

CentOS 下使用 nohup 时,日志保存方式主要有以下几种,最常用的是 重定向输出


一、默认日志保存位置

nohup command &

默认情况下:

  • 标准输出(stdout)和标准错误(stderr)都会写入当前目录下的:
nohup.out

⚠️ 如果当前目录不可写,会写入:

$HOME/nohup.out

二、指定日志文件(推荐 ✅)

1️⃣ 同时保存 stdout 和 stderr

nohup command > app.log 2>&1 &

说明:

  • >:重定向标准输出
  • 2>&1:把错误输出也写入同一个文件
  • &:后台运行

✅ 最常用方式


2️⃣ 分别保存 stdout 和 stderr

nohup command > stdout.log 2> stderr.log &

3️⃣ 追加日志(而不是覆盖)

nohup command >> app.log 2>&1 &

三、示例

运行 Java 程序

nohup java -jar app.jar > app.log 2>&1 &

查看日志

tail -f app.log

四、查看后台任务

jobs

ps -ef | grep command

五、防止日志无限增长(进阶)

1️⃣ 使用 logrotate(生产环境推荐)

示例 /etc/logrotate.d/app

/opt/app/app.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
}

2️⃣ 使用 cronolog(按时间切分)

nohup command | cronolog /opt/logs/app-%Y%m%d.log &

六、总结(最常用)

推荐写法:

nohup command > app.log 2>&1 &

查看日志:

tail -f app.log

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

  • 是什么程序(Java / Python / Shell)
  • CentOS 版本(6 / 7 / 8)

我可以给你更精确的示例。

0