crontab
crontab -l
01 */2 * * * /usr/sbin/logrotate -v /opt/shell_app/appengine >/tmp/logrotate.log 2>&1
logrotate
$ cat /opt/shell_app/appengine
compress
daily
size 10M
missingok
rotate 7
/ebs_data/opt/typhoonae/var/log/http*.log
{
rotate 1
prerotate
/opt/shell_app/cut.sh ${1}.2.gz
endscript
postrotate
kill -USR1 $(/sbin/pidof nginx) > /dev/null 2>&1 || true
endscript
create 644 steve steve
}
/opt/proftpd/var/*.log
/opt/gltfs/*.log
/opt/redis/var/*.log
{
copytruncate
prerotate
/opt/shell_app/cut.sh ${1}.8.gz
endscript
}
shell cut.sh
#!/bin/sh
#usage:add this script to logrotate‘s prerotate/endscript
#${1} is the absolute path to the log file
#${1}.3.gz means which file to bak and 3 is rotate‘s count add 1
#e.g.
#prerotate
# /opt/shell_app/cut.sh ${1}.3.gz
#endscript
set -x
if [ -f $1 ]; then
filepath=${1}
filedir=$(dirname ${1})
filename=$(basename ${1})
else
exit 0
fi
c_date=$(date +%Y%m%d%H%M%S)
y_date=`date --date="1 days ago" +%Y%m%d`
w_date=`date --date="3 days ago" +%Y%m%d`
function clean_and_bak_log(){
if [[ -d ${filedir}/bak ]];then
echo "bak dir is exsited"
else
mkdir -p ${filedir}/bak
chmod a+w ${filedir}/bak
fi
#insert current time to filename
#${#filename}-3} means cut ‘.gz‘ from filename
#example cp /opt/shell_app/test.log.3.gz /opt/shell_app/bak/test.log.3.201703061814.gz
cp -p ${filedir}/${filename} ${filedir}/bak/${filename:0:${#filename}-3}.${c_date}.gz
#rm -f ${filedir}/bak/*${w_date}*.gz
find ${filedir}/bak/ -regextype posix-extended -regex ‘^.*[0-9]{14,14}\.gz$‘ -mtime +5 -print0 | xargs -0 /bin/rm -f
}
备注:若某天日志量较大,使用以上策略可能会对磁盘空间产生压力
参考链接:
gnu findutils
原文地址:http://blog.51cto.com/chaoyuezhangsan/2065003
时间: 2024-10-18 07:59:55