一个nginx切割日志的脚本,自动删除7天前日志
#!/bin/bash LOGS_PATH=/home/wwwlogs YESTERDAY=$(date -d "yesterday" +%Y-%m-%d) #按天切割日志 mv ${LOGS_PATH}/access.log ${LOGS_PATH}/access_${YESTERDAY}.log #向 Nginx 主进程发送 USR1 信号,重新打开日志文件,否则会继续往mv后的文件写内容,导致切割失败. kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'` #压缩 gzip -9 ${LOGS_PATH}/access_${YESTERDAY}.log #删除7天前的日志 cd ${LOGS_PATH} find . -mtime +7 -name "*20[1-9][3-9]*" | xargs rm -f exit 0
|-------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/bin/bash LOGS_PATH=/home/wwwlogs YESTERDAY=$(date -d "yesterday" +%Y-%m-%d) #按天切割日志 mv ${LOGS_PATH}/access.log ${LOGS_PATH}/access_${YESTERDAY}.log #向 Nginx 主进程发送 USR1 信号,重新打开日志文件,否则会继续往mv后的文件写内容,导致切割失败. kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'` #压缩 gzip -9 ${LOGS_PATH}/access_${YESTERDAY}.log #删除7天前的日志 cd ${LOGS_PATH} find . -mtime +7 -name "*20[1-9][3-9]*" | xargs rm -f exit 0 |
可以通过grep、awk找到nginx master也可以直接kill -USR1 pid
kill -USR1 `ps aux | grep "nginx: master process" | grep -v grep | awk '{print $2}'`
|---|-------------------------------------------------------------------------------------------| | 1 | kill -USR1 `ps aux | grep "nginx: master process" | grep -v grep | awk '{print $2}'` |
或
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
|---|----------------------------------------------------| | 1 | kill -USR1 `cat /usr/local/nginx/logs/nginx.pid` |