我有一项cron作业,每天将其日志文件复制到我的主文件夹中.
每天,它都会覆盖目标文件夹中的现有文件,这是预期的.我想保留以前日期的日志,以便下次将文件复制到目标文件夹时,可以保留以前日期的文件.
我怎么做?
解决方法:
管理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