BASH
Automate Log File Rotation and Archiving with Bash
Efficiently manage server log files using a bash script that rotates, compresses, and archives old logs to save disk space and maintain order.
#!/bin/bash
LOG_DIR="/var/log/apache2"
LOG_FILE_PREFIX="access.log"
ARCHIVE_DIR="/var/log/apache2/archive"
RETENTION_DAYS=30 # Days to keep compressed logs
# Create archive directory if it doesn't exist
mkdir -p "$ARCHIVE_DIR"
# Rotate and compress log files
# Find log files matching the prefix, older than 1 day, and not already compressed (.gz)
find "$LOG_DIR" -maxdepth 1 -type f -name "${LOG_FILE_PREFIX}*" ! -name "*.gz" -mtime +0 -print0 | while IFS= read -r -d $'' logfile;
do
TIMESTAMP=$(date +%Y%m%d%H%M%S)
BASENAME=$(basename "$logfile")
NEW_NAME="${BASENAME%.*}-$TIMESTAMP.gz"
echo "Rotating and compressing $logfile to $ARCHIVE_DIR/$NEW_NAME"
gzip -c "$logfile" > "$ARCHIVE_DIR/$NEW_NAME" && rm "$logfile"
done
# Clean up old archived logs
echo "Cleaning up archived logs older than $RETENTION_DAYS days..."
find "$ARCHIVE_DIR" -type f -name "*.gz" -mtime +"$RETENTION_DAYS" -delete
echo "Log rotation and archiving complete."
How it works: This script helps manage server log files by automating their rotation and archiving. It looks for log files in a specified directory (`LOG_DIR`) matching a prefix (`LOG_FILE_PREFIX`), compresses them using `gzip`, renames them with a timestamp, and moves them to an `ARCHIVE_DIR`. After compression, the original log files are deleted. Additionally, it cleans up archived logs that are older than `RETENTION_DAYS`. This process helps prevent log files from consuming too much disk space and keeps your log directories tidy. Remember to adjust `LOG_DIR`, `LOG_FILE_PREFIX`, `ARCHIVE_DIR`, and `RETENTION_DAYS` according to your needs.