Log Rotation and Cleanup Scripts
🛠️ Why Log Rotation and Cleanup Matters
In real-world observability:
✅ Logs grow very fast:
✅ If you don't rotate or clean up:
✅ Managing logs = Managing system health and reliability.
🛠️ What is Log Rotation?
✅ Log rotation means:
✅ Keeps your system healthy and searchable without eating up all disk space.
📚 Example 1: Manual Log Rotation Script (Simple)
#!/bin/bash
log_file="/var/log/myapp.log"
timestamp=$(date +%Y%m%d_%H%M%S)
archive_dir="/var/log/archive"
mkdir -p $archive_dir
cp $log_file $archive_dir/myapp.log.$timestamp
> $log_file # Empty the original log file
echo "Log rotated and archived as myapp.log.$timestamp"
✅ What happens:
📚 Example 2: Auto Compress Old Logs
#!/bin/bash
find /var/log/archive -name "*.log*" -mtime +7 -exec gzip {} \\;
✅ Meaning:
✅ Compression saves disk space heavily in observability setups!
📚 Example 3: Cleanup Very Old Logs
#!/bin/bash
find /var/log/archive -name "*.gz" -mtime +30 -exec rm {} \\;
✅ Meaning:
✅ Always keep a balance between retention and disk usage.
🛠️ How to Automate Log Rotation with Cron
✅ Add this to crontab:
0 2 * * * /home/ubuntu/scripts/rotate_logs.sh > /tmp/rotate_logs.log 2>&1
✅ Rotate logs every night at 2 AM
✅ Log rotation itself logs to /tmp/rotate_logs.log
✅ Self-healing observability — no human intervention needed.
🛠️ Bonus: Linux logrotate Tool
✅ Linux has a built-in tool called logrotate!
✅ For complex setups, you can configure /etc/logrotate.d/yourapp:
/var/log/myapp.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 ubuntu ubuntu
}
✅ logrotate runs automatically via cron!
✅ But small shell scripts are super useful for custom automation.
🧠 Simple Analogy
Log rotation is like taking out the trash 🗑️:
✅ Good observability = Good log hygiene.
Preventive log management saves production systems!
🗺️ Where Are We in the Journey?
Linux Fundamentals → Kubernetes Observability → Shell Basics → Background Jobs → Scheduling with Cron → (Now) Smart Log Rotation & Cleanup
You are now automating true system hygiene for observability!