BASH
Archive and Rotate Web Server Log Files
A bash script to archive web server log files with a timestamp, compress them, and optionally remove old archives to manage disk space on the server.
#!/bin/bash
# Configuration
LOG_DIR="/var/log/nginx" # Directory containing log files
ARCHIVE_DIR="/var/log/nginx/archive" # Directory to store archived logs
LOG_FILE_PREFIX="access.log" # The log file name (e.g., access.log, error.log)
DAYS_TO_KEEP=30 # Number of days to keep archived logs (0 for no deletion)
TIMESTAMP=$(date +%Y%m%d%H%M%S)
# Create archive directory if it doesn't exist
mkdir -p "$ARCHIVE_DIR"
# Loop through log files that match the prefix
for log_file in "$LOG_DIR"/"$LOG_FILE_PREFIX"*;
do
if [ -f "$log_file" ]; then
echo "Archiving $log_file..."
# Move, timestamp, and compress the log file
mv "$log_file" "$ARCHIVE_DIR/$(basename "$log_file").$TIMESTAMP"
gzip "$ARCHIVE_DIR/$(basename "$log_file").$TIMESTAMP"
echo "Archived to $ARCHIVE_DIR/$(basename "$log_file").$TIMESTAMP.gz"
# Optional: Recreate empty log file with correct permissions
# This is often handled by logrotate or the service itself, but included for completeness.
# If the service expects the file to always exist, uncomment and adjust permissions.
# touch "$log_file"
# chmod 640 "$log_file"
# chown www-data:adm "$log_file" # Adjust user/group as needed
else
echo "No log files matching '$LOG_FILE_PREFIX' found in '$LOG_DIR'."
fi
done
# Optional: Delete old archives
if [ "$DAYS_TO_KEEP" -gt 0 ]; then
echo "Deleting archives older than $DAYS_TO_KEEP days..."
find "$ARCHIVE_DIR" -type f -name "*.gz" -mtime +"$DAYS_TO_KEEP" -delete
fi
# Optional: Reload/restart service if it writes directly to the log file
# For Nginx, use 'systemctl reload nginx' to reopen log files without dropping connections.
# systemctl reload nginx
echo "Log rotation complete."
How it works: This script automates the process of archiving and rotating web server log files to prevent them from consuming excessive disk space. It moves existing log files to an archive directory, timestamps and compresses them using `gzip`. An optional `find` command is included to delete archives older than a specified number of days, providing a complete log management solution. Remember to adjust file permissions and service reload commands as per your specific server setup.