1. 自动删除30天前的日志
find $PATH -mtime +天数 -name "*log*" -exec rm -rf {} \;
-mtime:最后修改时间
-ctime:创建时间
{} ; 为固定语法
2. 新建日志清理脚本
vi /usr/local/src/log-clear-30days-ago.sh
#!/bin/sh
PATH=/app/log
find $PATH -mtime +30 -name "*.log" -exec rm -rf {} \;
3. 添加计划任务
crontab -e
输入如下日志清理命令,保存,退出。
5 0 * * * /bin/sh /usr/local/src/log-clear-30days-ago.sh >/dev/null 2>&1
进阶:
挂载盘符+删除历史日志+压缩日志+rsync历史归档
#!bin/bash
## by hl @2020-03-04
LOCAL_IP=10.17.42.333
yestoday=`date -d last-day +%Y-%m-%d`
## NAS
## mount -t cifs -o user=test,pass=***,dom=cscjy //10.17.24.111/databak/ /log-collect
## windows
## mount -t cifs //10.17.0.333/smslog -o user=test,pass=c**8,file_mode=0777,dir_mode=0777,dom=\. /log-collect
## clear old logs
find /usr/local/app/logs/*log -mtime +60 -exec rm -f {} \;
find /usr/local/app/logs/*tar.gz -mtime +5 -exec rm -f {} \;
find /usr/local/wildfly-13.0.0.Final/standalone/log/ -mtime +5 -name "*log.*" -exec rm -rf {} \;
## gzip yestoday log and rsync to /log-collect
tar czf app_${yestoday}.tar.gz *${yestoday}*
m_status=`df -h|grep log-collect|wc -l`
if [ $m_status-eq 0 ] ;then
echo "日志归集目的盘符连接失败!";
curl -d "user=dx&pwd=bb4624304dd&mobile=152**5784&msg_content=<<<${LOCAL_IP}日志归集目的盘符连接失败!>>>${CTIME}" "http://your-msg-server/send-msg";
exit 1;
else
echo "日志归集ing";
rsync -auvt /usr/local/app/logs/*tar.gz /log-collect/${LOCAL_IP};
fi
exit 0
网友评论