Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
nginx log rotate bash script
#!/bin/bash
## http://nginx.org/en/docs/control.html
## https://www.nginx.com/resources/wiki/start/topics/examples/logrotation/
## idea is to run this cron job at 12:59 PM daily to move the existing access and error logs and reload nginx
DEBUG=true
CURRENT_DATE=$(date +"%Y-%m-%d")
PROJECT_NAME="test.project"
LOG_FILE_PATH="/var/log/nginx"
ACCESS_FILE=access.log
ERROR_FILE=error.log
ROTATE_ACCESS_FILE=true
ROTATE_ERROR_FILE=true
KILL_USR1=false
## clear the message
MSG=""
## check if backup already executed for access file
if [ -f "$LOG_FILE_PATH/$PROJECT_NAME.$ACCESS_FILE.$CURRENT_DATE" ]; then
MSG+="skipping rotation of file $LOG_FILE_PATH/$PROJECT_NAME.$ACCESS_FILE.$CURRENT_DATE as it exist\n"
ROTATE_ACCESS_FILE=false
fi
## check if backup already executed for error file
if [ -f "$LOG_FILE_PATH/$PROJECT_NAME.$ERROR_FILE.$CURRENT_DATE" ]; then
MSG+="skipping rotation of file $LOG_FILE_PATH/$PROJECT_NAME.$ERROR_FILE.$CURRENT_DATE as it exist\n"
ROTATE_ERROR_FILE=false
fi
## rotate access file
if [[ -f "$LOG_FILE_PATH/$ACCESS_FILE" && $ROTATE_ACCESS_FILE = true ]]; then
MSG+="backing up $ACCESS_FILE as file exist\n"
mv "$LOG_FILE_PATH/$ACCESS_FILE" "$LOG_FILE_PATH/$PROJECT_NAME.$ACCESS_FILE.$CURRENT_DATE"
KILL_USR1=true
else
MSG+="did not rotate $ACCESS_FILE\n"
fi
## rotate error file
if [[ -f "$LOG_FILE_PATH/$ERROR_FILE" && $ROTATE_ERROR_FILE = true ]]; then
MSG+="backing up $ERROR_FILE as file exist\n"
mv "$LOG_FILE_PATH/$ERROR_FILE" "$LOG_FILE_PATH/$PROJECT_NAME.$ERROR_FILE.$CURRENT_DATE"
KILL_USR1=true
else
MSG+="did not rotate $ERROR_FILE\n"
fi
## nginx logrotate http://nginx.org/en/docs/control.html
if [ $KILL_USR1 = true ]; then
kill -USR1 `cat master.nginx.pid`
sleep 1
MSG+="killed USR1 to rotate nginx logs\n"
else
MSG+="no logrotation occured for nginx"
fi
if [ $DEBUG = true ]; then
echo "CURRENT_DATE: $CURRENT_DATE"
echo "PROJECT_NAME: $PROJECT_NAME"
echo "LOG_FILE_PATH: $LOG_FILE_PATH"
echo "ACCESS_FILE: $ACCESS_FILE"
echo "ERROR_FILE: $ERROR_FILE"
echo "ROTATE_ACCESS_FILE: $ROTATE_ACCESS_FILE"
echo "ROTATE_ERROR_FILE: $ROTATE_ERROR_FILE"
echo "KILL_USR1: $KILL_USR1"
fi
printf "%s\n" "$MSG"
# http://nginx.org/en/docs/control.html
# https://www.nginx.com/resources/wiki/start/topics/examples/logrotation/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.