目标:
日志不丢失
空间可回收
应用无感知(无需触发应用重载日志)
方案:
logrotate滚动日志
shell、python脚本
split大文件切分处理
但不管哪种处理方式,在不触发应用重载日志的情况下(很多应用也不支持或不方便重载日志),基本都会先用copy/split对文件进行备份或切分处理,然后利用truncate/>对日志文件进行截断清空操作,而在这两步操作之间,在日志持续写入的情况下,就存在日志丢失的可能。
优化处理:
1、确保应用采用的是追加(>>)方式写入日志,否则清空日志文件后继续写入,原存储空间将得不到释放;
2、利用tail -f 将日志文件刷到增量日志文件A;
3、利用copy/split备份原日志文件到文件B;
4、利用cat /dev/null >xxx.log,截断清空日志文件;
5、kill掉tail进程,中止增量日志文件A的写入;
6、结合A+B,确保了日志文件的无丢失滚动备份;
logrotate使用注意:
1、系统默认使用cron执行logrotate,加载默认配置文件/etc/logrotate.conf,默认情况下每周转储,保留4份历史日志
2、手动执行logrotate配置文件不会加载配置文件/etc/logrotate.conf,默认转储大于1M的日志,且不保留历史日志
3、手动强制执行logrotate配置文件不会加载配置文件/etc/logrotate.conf,默认转储所有日志,且不保留历史日志
shell脚本参考:
nohup ./logger.sh 1>>test.log 2>&1 &
tail -f test.log >>tt-add.log &
cp test.log tt.log && cat /dev/null >test.log ; (或使用logrotate)
kill -9 `ps -ef |grep test.log|grep -v grep |awk '{print $2}' `
相对完善的脚本:
#!/bin/bash
# 当/home/ooxx/java/serverlog/*.log大于500M时
# 自动将其截断清空,并备份之前的日志
#1G=1024*1024*1024字节
Logpath=/home/ooxx/java/serverlog
oper_date=$(date "+%Y%m%d%H")
bakdir=$(date "+%Y%m%d%H%M%S")
cd $Logpath
for Logname in `ls *.log`
do
if [ `ls -l $Logpath/$Logname|awk '{print $5}'` -gt $((1024*1024*512)) ]
then
mkdir $Logpath/logbak/$bakdir
tail -f $Logname >${Logname}-add &
cp $Logname ${Logname}-${oper_date} && echo "" >$Logname &
sleep 10
ps -ef |grep $Logname|grep -v grep |awk '{print $2}'|xargs kill -9
cat ${Logname}-${oper_date} ${Logname}-add |awk '!x[$0]++' > ${Logname}_${bakdir} && tar -czf ${Logname}_${bakdir}.tar.gz ${Logname}_${bakdir}
mv *.tar.gz $Logpath/logbak/$bakdir
rm -f ${Logname}-add ${Logname}-${oper_date} ${Logname}_${bakdir}
fi
done
http://www.cnblogs.com/sailrancho/p/4784763.html
https://blog.youkuaiyun.com/u010039418/article/details/81045632
https://blog.youkuaiyun.com/u010181136/article/details/56008787