Automated Log Rotation and Compression Scripts for Ubuntu
Your Logs Are Eating Your Server Alive
It happens to everyone. You deploy a slick new app on Ubuntu. Everything runs flawlessly. Then, three months later, your server chokes and dies at 2 AM. Why? Because your log files grew into a massive, 50GB monster that swallowed your disk space whole. Dealing with manual ubuntu log archiving is a nightmare. You shouldn't be logging in every Friday just to delete old text files. Let's fix that.
Stop Reinventing the Wheel: Meet Logrotate
Most people don't realize Ubuntu already ships with a lifesaver. It's called `logrotate`. You don't need a complex pipeline right out of the gate. A simple configuration file in `/etc/logrotate.d/` tells your system exactly how to behave. Tell it to compress old logs. Tell it to keep only the last seven days. It's built-in disk management that takes literally three minutes to set up. Use it.
When You Actually Need a Bash Script
Sometimes the default tools aren't enough. Maybe you need to ship those compressed logs to an AWS S3 bucket. Or maybe your compliance team demands a weird naming convention. That's when a custom logrotate bash script comes into play. Write a tiny script to compress specific `.log` files, stamp them with the date, and securely move them off-site. Keep it simple. Less code means fewer things breaking at midnight.
Stop Hoarding Useless Server Data
Here's the thing. You don't need to keep debug logs from 2022. You just don't. Aggressive disk management is about being ruthless with retention policies. Compress after 24 hours. Delete after 30 days. If you haven't looked at a log file in a month, it's garbage. Treat it like garbage. Archiving everything forever is a fast track to wasting money on premium block storage.
Set the Cron Job and Walk Away
Writing the script is only half the battle. If you have to trigger it manually, you failed. Tie your whole archiving process directly into cron. Set it to run daily at a weird hour. Like 3:17 AM. Why a weird hour? Because running every single maintenance task at exactly midnight causes massive CPU spikes. Spread out your automated jobs. Now close your terminal and go get a coffee.