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


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 .


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


establish file

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/ >> /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.

Please bring the original link to reprint ,thank
Similar articles