第一种:日志本身就以日期保存,每天一个文件的,比如localhost.2020-04-24.log;这类日志只需要卡一个定时器,定期删除即可。
第二种:日志是日积月累在同一个文件中,比如catalina.out;这类文件的清理需要先"切割",再删除。以catalina.out为例,先将catalina.out备份成catalina.out-${date};再定期删除catalina.out-${date}
1- 删除文件
命令:find 对应目录 -mtime +天数 -name "文件名" -exec rm -rf {} \;
实例命令示例:find /opt/java/tomcat/logs/ -mtime +15 -name "localhost_access_log.*" -exec rm -rf {} \;
2- 计划任务
2-1- 创建shell:
新建执行文件:touch /opt/java/tomcat/logs/auto-del-15-days-ago-log.sh
分配运行权限:chmod +x /opt/java/tomcat/logs/auto-del-15-days-ago-log.sh
2-2- 编辑shell脚本
进入sh文件:vim /opt/java/tomcat/logs/auto-del-15-days-ago-log.sh
添加如下删除脚本(5种日志文件):
find /opt/java/tomcat/logs/ -mtime +15 -name "localhost_access_log.*" -exec rm -rf {} \;
find /opt/java/tomcat/logs/ -mtime +15 -name "localhost.*" -exec rm -rf {} \;
find /opt/java/tomcat/logs/ -mtime +15 -name "manager.*" -exec rm -rf {} \;
find /opt/java/tomcat/logs/ -mtime +15 -name "catalina.*" -exec rm -rf {} \;
find /opt/java/tomcat/logs/ -mtime +15 -name "host-manager.*" -exec rm -rf {} \;
保存并退出编辑(:wq)
2-3- 设置定时器
进入定时器文件:crontab –e
添加定时任务:1 1 * * * /opt/java/tomcat/logs/auto-del-15-days-ago-log.sh //每天凌晨1点1分执行(注意Llinux定时器的时间设置是从分开始,没有秒的)
保存退出(:wq)
#创建sh文件 touch /opt/java/tomcat/logs/clear-catalina-out-15-days.sh #编辑sh文件 vim /opt/java/tomcat/logs/clear-catalina-out-15-days.sh ##在sh文件中添加以下内容,并保存 #定义tomcat日志文件目录
log_path=/opt/java/tomcat/logs
#定义当前日期 d=`date +%Y-%m-%d`
#定义15天前的日期 d15=`date -d‘15 day ago‘ +%Y-%m-%d`
#跳转到tomcat日志文件夹,复制catalina.out到catalina.out.${d}.log cd ${log_path} && cp catalina.out ${log_path}/catalina.out.${d}.log
#清空cat文件alina.out echo > catalina.out
#删除15天前的catalina.out.${d15}.log rm -rf ${log_path}/catalina.out.${d15}.log #添加sh文件执行权限 chmod +x /opt/java/tomcat/logs/clear-catalina-out-15-days.sh #配置定时器 crontab -e ##添加以下内容,并保存(:wq) 1 1 * * * /opt/java/tomcat/logs/clear-catalina-out-15-days.sh #重新加载定时器 service crond reload
查看定时器运行日志
[root@izbp10ebr6tsvo83iahgzdz ~]# tail -f /var/log/cron ...... Apr 27 20:58:01 izbp10ebr6tsvo83iahgzdz CROND[26445]: (root) CMD (/opt/java/tomcat/logs/auto-del-15-days-ago-log.sh)
查看定时器运行状态
[root@izbp1aum9uyt0x56d3vepwz logs]# service crond status Redirecting to /bin/systemctl status crond.service ● crond.service - Command Scheduler Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2019-08-07 14:32:03 CST; 8 months 20 days ago Main PID: 2645 (crond) CGroup: /system.slice/crond.service └─2645 /usr/sbin/crond -n
END
Linux 定期切割Tomcat catalina.out和清理log日志
原文:https://www.cnblogs.com/wobuchifanqie/p/12790660.html