The Importance of Log Management
On any active Linux server, application and system logs can grow rapidly, eventually consuming all available disk space if left unchecked. Logrotate is a powerful utility built into Ubuntu Linux that automatically rotates, compresses, removes, and mails log files, ensuring your system remains organized and prevents storage exhaustion.
Step 1: Verify Logrotate Installation
Logrotate is usually installed by default on Ubuntu server distributions. You can verify its presence and check the installed version by running:
logrotate --version
Step 2: Understand the Global Configuration
The main configuration file for Logrotate is located at /etc/logrotate.conf. Open it using a text editor like Nano:
sudo nano /etc/logrotate.conf
Here you will find global settings, such as rotating logs weekly, keeping 4 weeks of backlogs, and creating new empty log files after rotation. While you can edit these, it is generally recommended to leave the global defaults and create application-specific rules.
Step 3: Create a Custom Logrotate Configuration
Application-specific configurations are stored in the /etc/logrotate.d/ directory. To create a rule for a custom application (e.g., a web app logging to /var/log/myapp.log), create a new file:
sudo nano /etc/logrotate.d/myapp
Step 4: Define the Rotation Rules
In the new file, define how the logs should be handled. A standard configuration looks like this:
/var/log/myapp.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 640 root adm
}
This configuration rotates the log daily, keeps 7 compressed archives, skips the process if the log is missing or empty, and creates a new file with specific permissions.
Step 5: Test the Configuration
To ensure your configuration contains no syntax errors and to simulate what Logrotate will do without actually modifying the files, run a dry-run test using the -d flag:
sudo logrotate -d /etc/logrotate.d/myapp
If the output shows no errors and correctly identifies the log file to rotate, your configuration is active and will be executed automatically by the system’s daily cron job.