管理由cron作业创建的日志文件 [英] Managing log files created by cron jobs

查看:61
本文介绍了管理由cron作业创建的日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个cron作业,每天将其日志文件复制到我的主文件夹中.

I have a cron job that copies its log file daily to my home folder.

每天,它都会覆盖目标文件夹中的现有文件,这是预期的.我想保留以前日期的日志,以便下次将文件复制到目标文件夹时,可以保留以前日期的文件.

Everyday it overrides the existing file in the destination folder, which is expected. I want to preserve the log from previous dates so that next time it copies the file to destination folder, it preserves the files from previous dates.

我该怎么做?

推荐答案

管理cron日志的最佳方法是在每个作业周围都有一个包装.包装程序至少可以执行以下操作:

The best way to manage cron logs is to have a wrapper around each job. The wrapper could do these things, at the minimum:

  • 初始化环境
  • 将stdout和stderr重定向到日志
  • 执行任务
  • 执行检查以查看作业是否成功
  • 必要时发送通知
  • 清理日志

这是cron包装的基本版本:

Here is a bare bones version of a cron wrapper:

#!/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命令行如下所示:

Your cron command line would look like:

/path/to/cron_wrapper command ...

一旦完成,我们可以执行另一个名为cron_log_cleaner的作业,该作业可以删除较旧的日志.最后,从cron包装器本身调用日志清理器并不是一个坏主意.

Once this is in place, we can have another job called cron_log_cleaner which can remove older logs. It's not a bad idea to call the log cleaner from the cron wrapper itself, at the end.

一个例子:

# 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作业后,日志中将包含以下内容:

The log would contain this after running the wrapped cron job:

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

这篇关于管理由cron作业创建的日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆