在使用 nohup 运行程序时,nohup 本身不会给日志加时间戳。常见做法是在程序外部或内部加时间戳。下面按使用场景给你几种常用方案。
ts 命令(推荐)如果你装了 moreutils:
nohup your_command | ts >> nohup.out 2>&1 &
ts 会给每一行前面加上时间戳Aug 20 14:32:01 starting...
Aug 20 14:32:05 done
安装(如未安装):
# Debian / Ubuntu
apt install moreutils
# CentOS / RHEL
yum install moreutils
awk 加时间戳(无需额外安装)nohup bash -c 'your_command 2>&1 | awk "{print strftime(\"%Y-%m-%d %H:%M:%S\"), \$0}"' >> nohup.out &
示例输出:
2026-01-15 10:23:45 log message
sed 加时间戳(不太推荐,复杂)nohup your_command 2>&1 | sed "s/^/$(date '+%F %T') /" >> nohup.out &
⚠️ 注意:这种方式只在启动时打一次时间,不适合持续输出。
如果程序是你自己写的:
import logging
logging.basicConfig(
filename='nohup.out',
format='%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
echo "$(date '+%Y-%m-%d %H:%M:%S') something happened"
systemd + journalctl(自带时间戳)logrotate + rsyslog| 场景 | 推荐方式 |
|---|---|
| 快速使用 | ts |
| 无 root 权限 | awk + strftime |
| 长期服务 | 程序内部日志 |
| 生产环境 | systemd |
如果你愿意,可以告诉我:
nohup.out我可以给你一个可直接用的命令模板。