Log Rotation and Archiving with Crontab ๐
Automating log rotation and archiving is essential for maintaining system health and managing disk space. Here's how to set up a crontab script to achieve this:
1. Create the Log Rotation Script ๐
First, create a script (e.g., /usr/local/bin/rotate_logs.sh) with the following content:
#!/bin/bash
# Configuration
LOG_DIR="/var/log"
LOG_PREFIX="app"
ARCHIVE_DIR="/var/log/archive"
DAYS_TO_KEEP=7
DATE=$(date +"%Y-%m-%d")
# Ensure archive directory exists
mkdir -p "${ARCHIVE_DIR}"
# Rotate logs
find "${LOG_DIR}" -type f -name "${LOG_PREFIX}*.log" -print0 | while IFS= read -r -d $'\0' log_file; do
if [ -f "${log_file}" ]; then
# Compress and move the log file to archive directory
gzip -c "${log_file}" > "${ARCHIVE_DIR}/${LOG_PREFIX}_${DATE}_$(basename "${log_file}").gz"
# Remove the original log file
rm "${log_file}"
fi
done
# Remove logs older than DAYS_TO_KEEP
find "${ARCHIVE_DIR}" -type f -name "${LOG_PREFIX}*.gz" -mtime +${DAYS_TO_KEEP} -delete
exit 0
Explanation:
LOG_DIR: The directory containing the log files.
LOG_PREFIX: The prefix of the log files to be rotated (e.g., app for app.log).
ARCHIVE_DIR: The directory where archived logs will be stored.
DAYS_TO_KEEP: The number of days to keep archived logs.
- The script finds log files, compresses them, moves them to the archive directory, and removes logs older than the specified number of days.
2. Make the Script Executable ๐
Give the script execute permissions:
sudo chmod +x /usr/local/bin/rotate_logs.sh
3. Configure Crontab โฐ
Open the crontab for editing:
crontab -e
Add the following line to run the script daily:
0 0 * * * /usr/local/bin/rotate_logs.sh
This will run the script every day at midnight.
4. Test the Script (Optional) ๐งช
Run the script manually to ensure it works as expected:
sudo /usr/local/bin/rotate_logs.sh
Summary โจ
By following these steps, you can automate log rotation and archiving using a crontab script, ensuring your system remains clean and efficient.