温馨提示×

nohup日志如何加时间戳

小樊
44
2026-09-06 14:47:54
栏目: 编程语言

在使用 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 &

⚠️ 注意:这种方式只在启动时打一次时间,不适合持续输出。


四、程序内部加时间戳(最稳妥)

如果程序是你自己写的:

Python 示例

import logging
logging.basicConfig(
    filename='nohup.out',
    format='%(asctime)s %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)

Shell 脚本示例

echo "$(date '+%Y-%m-%d %H:%M:%S') something happened"

五、系统级方案(进阶)

  • systemd + journalctl(自带时间戳)
  • logrotate + rsyslog

推荐总结

场景 推荐方式
快速使用 ts
无 root 权限 awk + strftime
长期服务 程序内部日志
生产环境 systemd

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

  • 用的什么语言(Python / Java / Shell)
  • 是否在容器中
  • 是否必须写 nohup.out

我可以给你一个可直接用的命令模板

0