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

查看:20
本文介绍了管理由 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天全站免登陆