nginx日志切割

Nginx本身并不支持日志切割,那么就会造成日志非常的大,如果每天都手动的去截取日志,重命名这样就很不方便,所以我们编写一个脚本并建立一个定时任务来进行这些工作

(1)、 windows上nginx日志切割, 案例脚本nginxcut.bat内容:

@echo off
cd D:\nginx-1.16.1\
taskkill /F /IM nginx.exe > nul
rem date格式:
set today=%date:~0,4%-%date:~5,2%-%date:~8,2%
set dir="D:\nginx-1.16.1\logs\nginx日志切割"
rem access log
move "D:\nginx-1.16.1\logs\access.log" "%dir%\access-%today%.log"
move "D:\nginx-1.16.1\logs\error.log" "%dir%\error-%today%.log"
move "D:\nginx-1.16.1\logs\gateway.access.log" "%dir%\gateway\gateway.access-%today%.log"
move "D:\nginx-1.16.1\logs\gateway_error.log" "%dir%\gateway\gateway_error-%today%.log"
move "D:\nginx-1.16.1\logs\shangjia.access.log" "%dir%\shangjia\shangjia.access-%today%.log"
move "D:\nginx-1.16.1\logs\shangjia_error.log" "%dir%\shangjia\shangjia_error-%today%.log"
move "D:\nginx-1.16.1\logs\shangjia-test.access.log" "%dir%\shangjia-test\shangjia-test.access-%today%.log"
move "D:\nginx-1.16.1\logs\shangjia-test_error.log" "%dir%\shangjia-test\shangjia-test_error-%today%.log"
move "D:\nginx-1.16.1\logs\zong.access.log" "%dir%\zong\zong.access-%today%.log"
move "D:\nginx-1.16.1\logs\zong_error.log" "%dir%\zong\zong_error-%today%.log"
move "D:\nginx-1.16.1\logs\zong-test.access.log" "%dir%\zong-test\zong-test.access-%today%.log"
move "D:\nginx-1.16.1\logs\zong-test_error.access.log" "%dir%\zong-test\zong-test_error-%today%.log"
net start nginx
rem 删除30天前的备份:
forfiles /p "%dir%" /s /m "*.log" /d -30 /c "cmd /c if @isdir==TRUE (rmdir /q /s @path) else (del /f @path)"
forfiles /p "%dir%\gateway" /s /m "*.log" /d -30 /c "cmd /c if @isdir==TRUE (rmdir /q /s @path) else (del /f @path)"
forfiles /p "%dir%\shangjia" /s /m "*.log" /d -30 /c "cmd /c if @isdir==TRUE (rmdir /q /s @path) else (del /f @path)"
forfiles /p "%dir%\shangjia-test" /s /m "*.log" /d -30 /c "cmd /c if @isdir==TRUE (rmdir /q /s @path) else (del /f @path)"
forfiles /p "%dir%\zong" /s /m "*.log" /d -30 /c "cmd /c if @isdir==TRUE (rmdir /q /s @path) else (del /f @path)"
forfiles /p "%dir%\zong-test" /s /m "*.log" /d -30 /c "cmd /c if @isdir==TRUE (rmdir /q /s @path) else (del /f @path)"
pause

配合windows任务计划来完成对nginx日志的切割

(2)、 linux上nginx日志切割, 案例脚本nginxcut.sh内容:

#!/bin/bash
LOG_PATH=/usr/local/nginx/logs/oldlogs
CUR_LOG_PATH=/usr/local/nginx/logs
YESTERDAY=$(date +%F -d -1day)
logfile=(access.log error.log tms.access.log tms_error.log)
i=0
while [[ i -lt ${#logfile[@]} ]];
do
mv $CUR_LOG_PATH/${logfile[i]}  $LOG_PATH/${YESTERDAY}_${logfile[i]}
let i++
done
kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid)
find $LOG_PATH -name *.log -type f -mtime +30 -exec rm -rf {} \;

备注:该脚本应该加入到定时任务中,每天0点0分执行

crontab -e

0 0 * * * /bin/bash /home/nginxcut.sh &>/dev/null

相关新闻

联系我们

全国服务热线

400-033-9553

电子邮件:admin@example.com
工作时间:09:00-17:00 周一至周五

在线客服
关注微信
关注微信
分享本页
返回顶部