Nginx Log Rotation using bash shell script

By | January 17, 2015

In this Post we will see how to configure Nginx Log Rotation using bash shell script.

I highly suggest everyone to achieve log rotation with logrotate service which is up and running in any minimal installation of Linux. In case if some errors are encountered with logrotate, then this route can come in handy. The official nginx site has a simple log rotation document. Based on it I wrote a simple shell script to get the log rotataion done. This script is not very pleasing to look at (given my near zero experience in scripting). But none the less, does a wonderful job.

My nginx logs go the directory “/var/log/nginx” by the names “access.log” and “error.log“. I have created a directory “/var/log/nginx/archive“. In simple words what this script does is, it makes a copy of the above mentioned access and error logs, attaches a timestamp to it, gzips and puts it in the “/var/log/nginx/archive“. After that it deletes, the timestamp attached log files.

Lets create the bash shell script:

[email protected]:~# mkdir /script
[email protected]:~# vi /script/nginx_log_rotate.sh
### Archiving Nginx access log ###
#!/bin/bash
logfile=/var/log/nginx/access.log
if [ ! -f $logfile ]; then
 echo "log file not found $logfile"
 exit 1
fi
timestamp=`date +%Y%m%d`
newlogfile=$logfile.$timestamp
mv $logfile $newlogfile
kill -USR1 `cat /var/run/nginx.pid` ##nginx will re-open its logs in response to the USR1 signal.##
sleep 1
gzip -f -9 $newlogfile
mv /var/log/nginx/access.*.gz /var/log/nginx/archive
rm -rf $newlogfile
### Archiving Nginx error log ###
#!/bin/bash
logfile=/var/log/nginx/error.log
if [ ! -f $logfile ]; then
 echo "log file not found $logfile"
 exit 1
fi
timestamp=`date +%Y%m%d`
newlogfile=$logfile.$timestamp
mv $logfile $newlogfile
kill -USR1 `cat /var/run/nginx.pid` ##nginx will re-open its logs in response to the USR1 signal.##
gzip -f -9 $newlogfile
mv /var/log/nginx/error.*.gz /var/log/nginx/archive
rm -rf $newlogfile
exit

Lets Set Up the Cronjob for log rotation:

[email protected]:~# crontab -e

## Rotate logs daily at 8 am (Assign your own time)
00 08 * * * sh /script/nginx_log_rotate.sh
## Delete the zipped log archives once a week (Set this as per your requirement)
55 07 * * 1 rm -rf /var/log/nginx/archive/*

So this is how we can set up Nginx Log Rotation using bash shell script.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.