centos 定时清理log
2019-05-07 本文已影响0人
小草_fdba
添加定时任务
echo "0 0 * * * sh /****/clear_log.sh" >> /var/spool/cron/root
clear_log.sh
#!/bin/bash
cd /var/log/cloudsec/
mv webServer.log webServer`date -d yesterday +%Y%m%d`.log;
filenames=$(ls)
prefix=webServer
dateLen=8
prefixLen=${#prefix}
for filename in ${filenames[@]}
do
file_date=${filename:$prefixLen:$dateLen}
regFileDate=`echo ${file_date} | grep '^[0-9][0-9]*$'`
if [ ${filename:18:4} ] && [ ${filename:18:4} != '.log' ] && [ "$regFileDate" = "$file_date" ] && [ `date -d ${file_date} +%s` -lt `date -d -180day +%s` ];
then
echo $file_date
rm -f $filename
fi
done
这样写会发现log没有继续在webServer.log里写,而是在webServer.date.log里写,原因查看文件描述符
换用logrotate切割log
脚本如下
cd /etc/logrotate.d
touch web_log
echo "/**.log
{
rotate 90
daily
dateyesterday
copytruncate
}" >> /etc/logrotate.d/web_log
echo "# /etc/anacrontab: configuration file for anacron
# See anacron(8) and anacrontab(5) for details.
SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=0
# the jobs will be started during the following hours only
START_HOURS_RANGE=0-22
#period in days delay in minutes job-identifier command
1 0 cron.daily nice run-parts /etc/cron.daily
7 25 cron.weekly nice run-parts /etc/cron.weekly
@monthly 45 cron.monthly nice run-parts /etc/cron.monthly
" > /etc/anacrontab
echo "0 0 * * * logrotate -vf /etc/logrotate.d/web_log" >> /var/spool/cron/root