Nginx日志切割
Nginx日志随着日期越来越大,需要对日志进行定期切割清理。
切割策略
每天凌晨0点,执行定时任务打包nginx日志并生成新的nginx日志文件。
备份脚本:
确定日志文件名称
#!/bin/bash
# cut nginx log of yesterday
source /etc/profile
log_path="/usr/local/nginx/logs/"
yesterday=$(date -d "yesterday" +"%Y%m%d")
mv ${log_path}error.log ${log_path}error.$yesterday.log
mv ${log_path}access.log ${log_path}access.$yesterday.log
/usr/local/nginx/sbin/nginx -s reload
cd $log_path
# 打包日志文件
tar -zcvf error.$yesterday.tar.gz error.$yesterday.log
tar -zcvf access.$yesterday.tar.gz access.$yesterday.log
# 删除打包的源文件
rm -rf error.$yesterday.log
rm -rf access.$yesterday.log
### 不确定日志文件名
```bash
#!/bin/bash
# cut nginx log of yesterday
source /etc/profile
log_path="/usr/local/nginx/logs"
yesterday=$(date -d "yesterday" +"%Y%m%d")
seven_day_ago=$(date -d "7 days ago" "+%Y-%m-%d")
for file in $log_path/*.log; do
mv "$file" "${file%.log}.${yesterday}.log"
done
/usr/local/nginx/sbin/nginx -s reload
for file in $log_path/*${yesterday}.log; do
tar -zcvPf "${file%.log}.tar.gz" "$file"
rm -rf "$file"
done
echo "remove ${log_path}/*.${seven_day_ago}.tar.gz"
#删除前边第7天的日志
rm -rf ${log_path}/*.${seven_day_ago}.tar.gz
## 删除策略
每天凌晨0点,定时删除历史超过7天的备份日志文件。
删除脚本:
```bash
#!/bin/bash
# del history nginx log
cd /usr/local/nginx/shell
find /usr/local/nginx/logs/ -mtime +7 -type f -name '*.tar.gz' | xargs rm -f
/usr/local/nginx/sbin/nginx -s reload
定时任务
Cron表达式
minute hour day-of-month month day-of-week command
利用crontab -e 添加要执行的定时任务