以下这个脚本实施的核心是:
每天凌晨将日志文件压缩并移动到相应的年份月份目录下,然后重新生成日志文件,同时记录日志
#!/bin/bash
logs_path="/home/wwwlog/" #日志存放位置
year=`date +%Y` #年份
month=`date +%m` #月份
day=`date +%Y%m%d` #日期
time=`date +%Y%m%d-%H:%M:%S` #时间
weblog="www.pcstars.com_access" #web访问日志
CutNginxLog="/home/sysadmin/zhaoyj/CutNginx.Log" #分割nginx日志的记录
if [ $day -eq 1 ];then #判断是不是月初1号,如果条件成立则创建目录/home/wwwlog/年/月
mkdir -p ${logs_path}$year/$month/
fi
cd $logs_path #进入当前目录
tar jcf access_$day.log.tar.bz2 access.log #压缩日志文件
echo -n > access.log #清空文件,重新开始记录日志
DuAccess=`du -sh access_$day.log.tar.bz2 |awk '{print $1}'` #统计tar的大小,以便记录日志
mv access_$day.log.tar.bz2 ${logs_path}$year/$month/ #将日志文件移动到相应的目录下
echo "access_$day.log.tar.bz2 : $DuAccess $time" >> $CutNginxLog #记录日志
tar jcf ${weblog}_$day.tar.bz2 $weblog.log
echo -n > $weblog.log
DuPcstars=`du -sh ${weblog}_$day.tar.bz2 |awk '{print $1}'`
mv ${weblog}_$day.tar.bz2 ${logs_path}$year/$month/
echo "${weblog}_$day.tar.bz2 : $DuPcstars $time" >> $CutNginxLog
DuPcstars=`du -sh ${weblog}_$day.tar.bz2 |awk '{print $1}'`
mv ${weblog}_$day.tar.bz2 ${logs_path}$year/$month/
echo "${weblog}_$day.tar.bz2 : $DuPcstars $time" >> $CutNginxLog
echo "" >> $CutNginxLog
echo "" >> $CutNginxLog