BASH
Automate Log File Archiving and Rotation
Bash script to automate archiving and rotating application log files, preventing disk space issues and simplifying log management for web applications.
#!/bin/bash
LOG_DIR="/var/log/my_app"
OLD_LOG_DIR="$LOG_DIR/archive"
LOG_FILE="application.log"
DATE=$(date +%Y-%m-%d)
# Create archive directory if it doesn't exist
mkdir -p "$OLD_LOG_DIR"
# Check if log file exists
if [ ! -f "$LOG_DIR/$LOG_FILE" ]; then
echo "Log file $LOG_DIR/$LOG_FILE not found. Exiting."
exit 0
fi
# Compress and move the current log file to archive
echo "Archiving $LOG_FILE to $OLD_LOG_DIR/${LOG_FILE}.${DATE}.gz"
CURRENT_LOG_PATH="$LOG_DIR/$LOG_FILE"
ARCHIVE_PATH="$OLD_LOG_DIR/${LOG_FILE}.${DATE}.gz"
gzip -c "$CURRENT_LOG_PATH" > "$ARCHIVE_PATH"
if [ $? -eq 0 ]; then
# Truncate the original log file after successful archiving
echo "" > "$CURRENT_LOG_PATH"
echo "Log file archived and truncated successfully."
else
echo "Error archiving log file. Original file not truncated."
exit 1
fi
# Optional: Remove old archives (e.g., older than 30 days)
# find "$OLD_LOG_DIR" -name "*.gz" -type f -mtime +30 -delete
# echo "Removed log archives older than 30 days."
How it works: This script manages application log files by compressing the current log and moving it to an archive directory, then truncating the original log file. This prevents logs from growing indefinitely and consuming excessive disk space. An optional `find` command is included to delete old archives, helping maintain server hygiene crucial for long-running web applications.