最近公司有个老项目,日志把磁盘打满了,导致业务出现问题,由于老项目中程序无法像log4j一样通过配置清除日志,所以准备写个清除日志的脚本,通过cron定时执行。
1、清除日志脚本
#!/bin/bash
echo "###################################################################"
echo "# read me "
echo "#" 1: exec this script must have root access
echo "#" 2: you can user 'sudo' to exec
echo "#" 3: if you want interrupt exec ,please enter 'CTRL+C'
echo "#"
echo "###################################################################"
#使用绿色字体输出
echo -e "\033[32m After 10 seconds start exec \033[0m"
echo -e "\n"
sleep 10
outpatch=/home/rm/historycleanlog
mkdir -p ${outpatch}
current_Time=$(date +%Y-%m-%d\ %H:%M:%S)
echo -e "\033[32m $current_Time \033[0m"
echo "=========================== $current_Time ========================" >> ${outpatch}/del_log.out
echo -e "\n"
echo -e "\033[32m start delete log \033[0m"
echo "=========================== start delete log ======================" >> ${outpatch}/del_log.out
echo -e "\n"
echo -e "\033[32m Deleting...... \033[0m"
echo -e "\n"
current_dir=$(cd "$(dirname "$0")";pwd)
echo "current dir : " $current_dir >> ${outpatch}/del_log.out
log_path=/usr/local/log
#模糊查询a.log.*并将查询到的文件删除, 将输出记录到del_log.out文件中
find ${log_path} -name "a.log.*" -exec rm -f {} \; >> ${outpatch}/del_log.out 2>&1
find ${log_path} -name "b.log.*" -exec rm -f {} \; >> ${outpatch}/del_log.out 2>&1
echo -e "\033[32m The log clear finish \033[0m"
echo "============================= The log clear finish =======================================" >> ${outpatch}/del_log.out 2>&1
echo -e "\n"
echo " the operations record to ${outpatch}/del_log.out file "
2、编写定时任务
新建一个文件auto-del-log.cron,将cron 任务写入
#每周三凌晨3点0分执行 clear-old-log.sh脚本
0 2 * * 3 /home/rm/clear-old-log.sh
cron命令 格式 * * * * * command;
第一个*代表分, 第二个*为小时,第三个*为自然天(几号),第四个*为月,第5个*为周,command为要执行的命令(可以是脚本,也可以是系统命令)
3、加入crontab定时
执行 "sudo crontab -l >> auto-del-log.cron",此操作会将系统已有定时拷贝,避免crontab 文件时覆盖原有定时任务。
执行 "sudo crontab auto-del-sdnc-log.cron";
通过 "sudo crontab -l" 可以看到加入的定时任务。
PS:重启系统 crontab定时任务会丢失吗?
答:不会