tomcat&nginx日志定时清理
工作中tomcat和nginx下的日志,默认是不会进行日志轮换的,在线上环境运行久了,就会变得巨大,占用磁盘,严重时把磁盘占满,还会影响系统或程序的服务运行,因此需要进行定时定期清理,比如每天0点采用脚本方式进行日志的切割并备份清理,以下记录下tomcat和nginx的我使用的日志清理方式
1.脚本准备
Tomcat的清理脚本,只保留7天的日志,7天前的日志都清除。内容如下:
cat > /opt/scripts/tomcat_log_cut.sh << EOF
#!/bin/sh
#指定tomcat的日志目录
logPath="/opt/apache-tomcat-8.5.51/logs/"
cd $logPath
d=`date -d'1 day ago' +%Y-%m-%d`
d7=`date -d'7 day ago' +%Y-%m-%d`
#复制原来的日志文志,写到昨天的日期文件中
cp catalina.out catalina.out.${d}
#清空日志文件
cat /dev/null > catalina.out
#查找目录下七天前的日志文件进行删除
find $logPath -mtime +7 -type f -name catalina.out.\* | xargs rm -rf
find $logPath -mtime +7 -type f -name catalina.\*.log | xargs rm -rf
find $logPath -mtime +7 -type f -name manager.\*.log | xargs rm -rf
find $logPath -mtime +7 -type f -name localhost_access_log.\*.txt | xargs rm -rf
find $logPath -mtime +7 -type f -name localhost.\*.log | xargs rm -rf
find $logPath -mtime +7 -type f -name host-manager.\*.log | xargs rm -rf
EOF
Nginx的清理脚本,只保留7天的日志,7天前的日志都清除。内容如下:
cat > /opt/scripts/nginx_log_cut.sh << EOF
#!/bin/sh
#指定nginx的日志目录
logPath="/usr/local/nginx/logs/"
cd $logPath
d=`date -d'1 day ago' +%Y-%m-%d`
d7=`date -d'7 day ago' +%Y-%m-%d`
#复制原来的日志文志,写到昨天的日期文件中
cp access.log access.log.${d}
cp error.log error.log.${d}
#清空日志文件
cat /dev/null > access.log
cat /dev/null > error.log
#查找目录下七天前的日志文件进行删除
find $logPath -mtime +7 -type f -name access.log.\* | xargs rm -rf
find $logPath -mtime +7 -type f -name error.log.\* | xargs rm -rf
EOF
2.配置linux的crontab定时任务
脚本准备好后,通过linux的crontab任务配置定时执行,比如每天的0点
在命令行下输入crontab -e回车,然后加入以下脚本
0 0 * * * /bin/sh /opt/scripts/tomcat_log_cut.sh >/dev/null 2>&
0 0 * * * /bin/sh /opt/scripts/nginx_log_cut.sh >/dev/null 2>&
最后按shift+冒号,然后输入wq!保存定时任务即可
注:0 0 * * *表示每天的0点0分执行。