Nginx log files are recorded by day and cleaned up periodically
First level code VIP 2021-06-04 10:16:45

problem

nginx The log is recorded in a file by default access.log in , The log file will be very large after a long time , Even the disk is full .

Solution

Use the following methods , take access.log One file a day , And then clean it up 15 Days ago .

Method

establish clearNginxLog.sh file

#!/bin/bash
LOG_PATH="/data/nginx/log/"
save_days=1
YESTERDAY=$(date -d "yesterday" +%Y%m%d)
echo "———————————————–"
echo " The elapsed time :[$(date +"%Y-%m-%d %H:%M:%S")]"
# Delete files before the specified date
echo " Delete [$save_days] Log files days ago "
#find $LOG_PATH -mtime +$save_days -exec rm -rf {} \;
find $LOG_PATH -mtime +$save_days -type f -name \*.log | xargs rm -f
# Loop file rename
echo " Loop file rename "
#for f in $LOG_PATH*.log; do cp $f ${f%.html}.php; done
for var in $LOG_PATH*.log; do mv "$var" "${var%.log}_$YESTERDAY.log"; done
# towards nginx The main process sends USR1 The signal , Reopen the log file , Otherwise, they will continue to go mv After the file to write data . The reason lies in :linux In the system , The kernel looks for files based on file descriptors . If not, log cutting fails .
echo " towards nginx Sending signal "
kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`
echo " Clean up complete "
echo "———————————————–"

Upload the file to the server ,
And then in crontab Add task
crontab -e
Every day 0 Point to perform
0 0 * * * /data/nginx/conf/clearNginxLog.sh >> /var/log/clearNginx.log 2>&1

:q! sign out
:wq Save and exit

And then restart crontab service
root@castle:~# /etc/init.d/cron restart
[ ok ] Restarting cron (via systemctl): cron.service.
root@castle:~#

Please bring the original link to reprint ,thank
Similar articles

2021-08-09

2021-08-09