Monday, February 22, 2016

Easily rotate Nginx logs using rename, truncate, then restart

The scripts below is probably one of the simplest way to keep a few days worth of logs (up to you) and still keep all logs organized enough without loosing track.


What the scripts below do:

1. change directory to /log/nginx  (this is where I keep my Nginx logs - yours may be different)
2. move (rename) a log file ie: access.log to access_YYYYMMDD.log
3. create a new log file (using touch) with zero bytes.
4. change permission of new log file to 777 (allow everything).
5. restart nginx process so that it will use newly created log files.

-----------------------------------------------

cd /log/nginx

mv access.log access_`date +"%Y%m%d"`.log
touch /log/nginx/access.log
chmod 777 /log/nginx/access.log

mv error.log error_`date +"%Y%m%d"`.log
touch /log/nginx/error.log
chmod 777 /log/nginx/error.log

mv api-access.log api-access_`date +"%Y%m%d"`.log
touch /log/nginx/api-access.log
chmod 777 /log/nginx/api-access.log

mv api-error.log api-error_`date +"%Y%m%d"`.log
touch /log/nginx/api-error.log
chmod 777 /log/nginx/api-error.log

mv default-access.log default-access_`date +"%Y%m%d"`.log
touch /log/nginx/default-access.log
chmod 777 /log/nginx/default-access.log

mv default-error.log default-error_`date +"%Y%m%d"`.log
touch /log/nginx/default-error.log
chmod 777 /log/nginx/default-error.log

mv default-ssl-access.log default-ssl-access_`date +"%Y%m%d"`.log
touch /log/nginx/default-ssl-access.log
chmod 777 /log/nginx/default-ssl-access.log

mv default-ssl-error.log default-ssl-error_`date +"%Y%m%d"`.log
touch /log/nginx/default-ssl-error.log
chmod 777 /log/nginx/default-ssl-error.log

mv rockmongo-access.log rockmongo-access_`date +"%Y%m%d"`.log
touch /log/nginx/rockmongo-access.log
chmod 777 /log/nginx/rockmongo-access.log

mv rockmongo-error.log rockmongo-error_`date +"%Y%m%d"`.log
touch /log/nginx/rockmongo-error.log
chmod 777 /log/nginx/rockmongo-error.log

kill -USR1 $( cat /var/run/nginx.pid )

-----------------------------------------------

What to do with all those files created with YYYYMMDD?

Well you can then remove them using the following crontab lines at your liking:

here is a line from my crontab that removes every file in my /log/ directory recursive that is older than 10 days:

19 4 * * * find /log/ -type f -mtime +10 | xargs rm


No comments:

Post a Comment