在 CentOS 下,使用 nohup 运行程序时,日志设置主要通过 重定向 来完成。nohup 本身并不提供复杂的日志配置选项,而是依靠 Shell 重定向 来控制日志输出位置。
下面按常见场景详细说明。
nohup command &
默认行为:
nohup.outnohup.out$HOME/nohup.outnohup command > app.log 2>&1 &
解释:
>:重定向标准输出2>&1:将标准错误合并到标准输出app.log:自定义日志文件✅ 生产环境最推荐
nohup command > stdout.log 2> stderr.log &
stdout.log:正常日志stderr.log:错误日志适合需要分别排查错误的情况。
nohup command > /dev/null 2>&1 &
或
nohup command &> /dev/null &
✅ 适用于不需要日志的脚本或服务
nohup command >> app.log 2>&1 &
>>:追加写入nohup java -jar app.jar > app.log 2>&1 &
nohup python3 main.py > run.log 2>&1 &
nohup ./start.sh > start.log 2>&1 &
ps -ef | grep command
或
jobs
tail -f app.log
nohup.out 或 app.log 不会自动轮转,可能写满磁盘。
✅ 方案 1:使用 logrotate(推荐)
vim /etc/logrotate.d/app
示例:
/opt/app/app.log {
daily
rotate 7
compress
missingok
notifempty
copytruncate
}
✅ 方案 2:定时清空
echo > app.log
✅ 方案 3:直接丢弃日志
nohup command > /dev/null 2>&1 &
如果是 长期运行的服务,更推荐使用 systemd:
systemctl start yourapp
journalctl -u yourapp -f
systemd 自带日志管理,比 nohup 更稳定。
| 需求 | 命令 |
|---|---|
| 默认日志 | nohup cmd & |
| 指定日志 | nohup cmd > app.log 2>&1 & |
| 追加日志 | nohup cmd >> app.log 2>&1 & |
| 不记录日志 | nohup cmd > /dev/null 2>&1 & |
| 查看日志 | tail -f app.log |
如果你愿意,我可以 根据你的具体程序(Java / Python / Shell)或 CentOS 版本,给你一套更合适的启动 + 日志方案。