Prerequisites
Before automating log cleanup, make sure you have:
- SSH access to your VPS
- Root or sudo privileges
Method 1: Using logrotate (Recommended)
Connect to your VPS:
ssh hxroot@YOUR_SERVER_IP -p 22
Create custom logrotate config:
sudo nano /etc/logrotate.d/cleanup
Add rules:
/var/log/*.log {
weekly
rotate 4
compress
delaycompress
missingok
notifempty
create 644 root root
}
/var/log/nginx/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
/var/log/journal/*.journal {
weekly
rotate 2
compress
missingok
}
Test logrotate:
sudo logrotate -d /etc/logrotate.conf
Force run:
sudo logrotate -f /etc/logrotate.conf
Method 2: Using Cron with find
Create cleanup script:
sudo nano /usr/local/bin/cleanup-old-logs.sh
#!/bin/bash
# Delete logs older than 30 days
find /var/log -type f -name "*.log" -mtime +30 -delete
find /var/log -type f -name "*.gz" -mtime +90 -delete
# Clean systemd journal older than 7 days
journalctl --vacuum-time=7d
# Remove temporary files older than 2 days
find /tmp -type f -atime +2 -delete
find /var/tmp -type f -atime +2 -delete
echo "Log cleanup completed at $(date)" >> /var/log/cleanup.log
Make executable:
sudo chmod +x /usr/local/bin/cleanup-old-logs.sh
Schedule via cron:
sudo crontab -e
0 3 * * 0 /usr/local/bin/cleanup-old-logs.sh
Clean Apache/Nginx Access Logs Older Than 30 Days
find /var/log/apache2 -name "access.log.*.gz" -mtime +30 -delete
find /var/log/nginx -name "access.log.*.gz" -mtime +30 -delete
Empty Log Files Without Deleting Them
sudo find /var/log -type f -name "*.log" -exec truncate -s 0 {} ;
Monitor Log Cleanup Effectiveness
du -sh /var/log
ls -la /var/log/ | head -20
Set Up Email Alert on Cleanup Failure
Add to script:
if [ $? -ne 0 ]; then
echo "Log cleanup failed on $(hostname)" | mail -s "Cleanup Error" admin@example.com
fi
✅ Automated log cleanup configured. Old logs will be removed regularly to save disk space.