1、创建存放日志文件夹
mkdir /data/nginx_logs/
2、创建分割日志脚本
vim /usr/local/nginx/sbin/cut_nginx_logs.sh
3、输入文件内容
保存日志目录为:/data/nginx_logs/
log_files_from
为 nginx.conf 配置的原始日志文件路径
log_files_to
为新存放的日志文件路径
#!/bin/bash
#function:cut nginx log files
log_files_from="/usr/local/nginx/logs/"
log_files_to="/data/nginx_logs/"
log_name="access"
backupEndTime=`date +%Y-%m-%d@%Hh%Mm%Ss`
file=${log_files_from}${log_name}.log
if [ -f "$file" ];then
mv ${log_files_from}${log_name}.log ${log_files_to}${log_name}_${backupEndTime}.log
#delete 30 days ago nginx log files
cd $log_files_torm
rm -rf `find . -name '*.log' -mtime +30`
#restart nginx
systemctl restart nginx
fi
4、赋予执行权限
chmod +x /usr/local/nginx/sbin/cut_nginx_logs.sh
5、使用 crontab 添加定时任务
打开定时任务
crontab -e
添加定时任务,这里每天凌晨0点执行一次。
00 00 * * * /bin/sh /usr/local/nginx/sbin/cut_nginx_logs.sh #添加定时任务
测试:/30 * /bin/sh /usr/local/nginx/sbin/cut_nginx_logs.sh
每半小时执行一次
重启 crontab 服务
systemctl restart crond
查看定时任务
crontab -l