Linux Basic — Log Rotation & Cleanup

less than 1 minute read

Log Rotation & Cleanup

Logs grow without bound. Automated cleanup prevents disk-full surprises.


Most distros include logrotate, configured in /etc/logrotate.d/. For a custom app log:

/var/log/myapp/*.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 0640 myapp myapp
}

logrotate runs from cron daily and handles rotation, compression, and cleanup automatically.


Custom Cleanup Script

When logrotate isn’t available or you need a one-off cleanup:

#!/usr/bin/env bash
set -euo pipefail

LOG_DIR="/var/log/myapp"
DAYS=7

echo "cleaning logs older than $DAYS days in $LOG_DIR"
find "$LOG_DIR" -type f -name "*.log" -mtime +$DAYS -delete

# compress logs older than 1 day
find "$LOG_DIR" -type f -name "*.log" -mtime +1 ! -name "*.gz" \
    -exec gzip {} \;

Safe find Practices

  • Always test with -print before -delete
  • Use -maxdepth 1 to avoid recursing into subdirs
  • Quote paths to handle spaces
# dry-run first
find "$LOG_DIR" -type f -name "*.log" -mtime +7 -print
# then delete
find "$LOG_DIR" -type f -name "*.log" -mtime +7 -delete

Cron Entry

0 3 * * * /opt/scripts/cleanup-logs.sh

Runs daily at 3 AM, after backups.


Next → Practice Exercises

Updated: