管理 cron 日志的最佳方法是对每个作业进行包装。包装器至少可以做这些事情:
- 初始化环境
- 将 stdout 和 stderr 重定向到日志
- 运行作业
- 检查作业是否成功
- 必要时发送通知
- 清理日志
这是 cron 包装器的基本版本:
#!/bin/bash
log_dir=/tmp/cron_logs/$(date +'%Y%m%d')
mkdir -p "$log_dir" || { echo "Can't create log directory '$log_dir'"; exit 1; }
#
# we write to the same log each time
# this can be enhanced as per needs: one log per execution, one log per job per execution etc.
#
log_file=$log_dir/cron.log
#
# hitherto, both stdout and stderr end up in the log file
#
exec 2>&1 1>>"$log_file"
#
# Run the environment setup that is shared across all jobs.
# This can set up things like PATH etc.
#
# Note: it is not a good practice to source in .profile or .bashrc here
#
source /path/to/setup_env.sh
#
# run the job
#
echo "$(date): starting cron, command=[$*]"
"$@"
echo "$(date): cron ended, exit code is $?"
您的 cron 命令行如下所示:
/path/to/cron_wrapper command ...
一旦完成,我们可以有另一个名为cron_log_cleaner 的作业,它可以删除旧日志。最后从 cron 包装器本身调用日志清理器不是一个坏主意。
一个例子:
# run the cron job from command line
cron_wrapper 'echo step 1; sleep 5; echo step 2; sleep 10'
# inspect the log
cat /tmp/cron_logs/20170120/cron.log
运行打包的 cron 作业后,日志将包含以下内容:
Fri Jan 20 04:35:10 UTC 2017: starting cron, command=[echo step 1; sleep 5; echo step 2; sleep 10]
step 1
step 2
Fri Jan 20 04:35:25 UTC 2017: cron ended, exit code is 0