栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux设置定时任务去清除日志文件,在磁盘使用率达到80%以上时

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux设置定时任务去清除日志文件,在磁盘使用率达到80%以上时

目录

1、背景:

2、需求:Linux系统设置定时任务,去清理掉日志文件

设计思路:

3、开发shell脚本:

4、配置cron定时任务配置


1、背景:

在项目上线之后,应用程序就会运行起来,应用程序运行的过程会产生大量的日志,这时候日志文件所占的空间就会非常的巨大,这样会导致空间使用率非常大,这样会有宕机或者是应用程序停止运行的风险存在的,这里时候我们就需要去清理掉日志文件了来释放空间,从而降低宕机或者程序停止运行的风险。但是清理文件的动作是一个重复的操作,同时也是要求实时性非常高,但是日常的工作想做到实时性处理,这个是有难度的,得不到100%的保证,这时候就需要一个定时任务来实现这个动作,从而提升运维工作的质量,减少人工运维的工作量,如下就是介绍设置定时任务来清理日志文件。


2、需求:Linux系统设置定时任务,去清理掉日志文件

条件一:每天在晚上凌晨12点去清理掉7天前的日志文件;

条件二:如果日志文件所在的磁盘的空间使用率到达了80%以上清理掉3天之前的日志文件;

条件三:清理日志文件需包含业务日志,启动日志、错误日志等;


设计思路:

1、首先在Linux上设置定时任务的,所以我们需要采用cron工具;

2、需求是包含了多个条件的,并且存在判断的条件,所以需要利用shell脚本来实现;

3、清理的日志文件是根据时间来判断的需要利用到find命令来实现;


3、开发shell脚本:

1、撰写shell脚本:

[root@tomcat ~]# cat del_log.sh 
#!/bin/bash
#author:jiang
#time: 2022/04/15
#mtime: 2022/04/15

#函数
#空间使用率不超过80的操作
find_1 () {
find /tomcat/logs/ -mtime +7 -name "server*error.log" -exec rm -f {} ;
find /tomcat/logs/ -mtime +7 -name "catalina.out.log" -exec rm -f {} ;
find /tomcat/logs/ -mtime +7 -name "access_log.*.txt" -exec rm -f {} ;
find /tomcat/bin/ -mtime +7 -name "server01.log.*" -exec rm -f {} ;
}
#空间使用率超过了80%的操作
find_2 () {
find /tomcat/logs/ -mtime +3 -name "server*error.log" -exec rm -f {} ;
find /tomcat/logs/ -mtime +3 -name "catalina.out.log" -exec rm -f {} ;
find /tomcat/logs/ -mtime +3 -name "access_log.*.txt" -exec rm -f {} ;
find /tomcat/bin/ -mtime +3 -name "server01.log.*" -exec rm -f {} ;
}

#获取磁盘的空间大小
use=`df -h / | head -2 | tail -1 | awk -F" " '{print $5}' | awk -F% '{print $1}'`
#进行数值的判断
if [ $use -gt 80 ]
then
#执行操作
    find_2    
else
    find_1
fi

2、测试校验shell脚本语法是否有问题

[root@tomcat ~]# bash -x del_log.sh 
++ head -2
++ tail -1
++ df -h /
++ awk '-F ' '{print $5}'
++ awk -F% '{print $1}'
+ use=81
+ '[' 81 -gt 80 ']'
+ find_2
+ find /tomcat/logs/ -mtime +3 -name 'server*error.log' -exec rm -f '{}' ';'
+ find /tomcat/logs/ -mtime +3 -name catalina.out.log -exec rm -f '{}' ';'
+ find /tomcat/logs/ -mtime +3 -name 'access_log.*.txt' -exec rm -f '{}' ';'
+ find /tomcat/bin/ -mtime +3 -name 'server01.log.*' -exec rm -f '{}' ';'

执行没有报错说明shell语法是没有问题的。


4、配置cron定时任务配置
[root@tomcat ~]# crontab -l
01 00 * * * /bin/sh /root/del_log.sh

 配置文件之后就完成了,就等到时间进行验证了,如果正常使用之前可以修改时间进行验证的,这里就不具体描述了。


总结:如上就是日常工作需要配置定时任务去自动清理掉日志文件的场景,希望可以帮助大家,脚本的设计思路可以借鉴的。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/831328.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号