Linux Tips guides, explanations and reader checklists on whilenetworking.com

How to Automate Log File Rotation and Cleanup Using logrotate Configuration Directives

Log files are the lifeblood of system diagnostics, but they can quickly consume disk space on production servers if left unmanaged. Without automation,…

Log files are the lifeblood of system diagnostics, but they can quickly consume disk space on production servers if left unmanaged. Without automation, administrators must manually intervene to truncate or delete logs, risking data loss or service interruption. The standard solution in Linux distributions is logrotate, a versatile utility that automates log file rotation and cleanup based on configurable directives. This guide provides a comprehensive walkthrough for configuring logrotate effectively, moving from basic setup to advanced scenarios suitable for both student labs and production environments.

Understanding the Core Mechanism

Before diving into configuration, it is essential to understand how logrotate operates. The utility reads configuration files located in /etc/logrotate.d/. It scans these files for directives that specify which log files to manage (e.g., /var/log/syslog) and how to handle them (e.g., rotate after 7 days).

The core workflow involves:
1. Rotation: Renaming the current log file (e.g., syslog becomes syslog.1).
2. Compression: Optionally compressing older logs (syslog.1.gz) to save space.
3. Cleanup: Removing old logs that exceed the retention policy defined in the configuration.

This process is typically triggered by a cron job, often running daily at midnight, though it can be executed manually for testing purposes. Understanding this flow prevents common errors where logs accumulate unexpectedly.

Basic Configuration: A Real-World Scenario

Consider a web server hosting a critical application. The application writes access logs to /var/log/myapp/app.log. Currently, the disk partition is 90% full due to unbounded log growth. We need to configure logrotate to keep only the last three months of logs, compressing files older than one week.

Step-by-Step Configuration

  1. Access the Configuration Directory:
    Navigate to the directory where logrotate configurations reside:
    bash
    sudo nano /etc/logrotate.d/myapp

  2. Define Rotation Policies:
    Insert the following directives into the file. Each line serves a specific function:

    logrotate
    /var/log/myapp/app.log {
    daily # Check for new logs every day
    rotate 4 # Keep 4 rotated copies (covering roughly 28 days)
    compress # Compress old logs automatically
    delaycompress # Wait one rotation cycle before compressing
    missingok # Do not error if the log file is missing
    notifempty # Do not rotate if the log file is empty
    create 0644 myapp myapp # Create new log files with these permissions and owner
    dateext # Append a date to rotated files (e.g., app.log-20231027)
    dateformat -%Y%m%d # Define the date format for rotation
    maxage 2592000 # Keep logs for roughly 30 days regardless of count
    }

Explaining the Directives

  • daily: Runs the rotation check once every 24 hours. Using weekly or monthly reduces CPU load but may delay cleanup on high-volume systems.
  • rotate 4: Retains four old log files. Combined with maxage, this ensures logs are deleted even if they were not rotated recently.
  • compress and delaycompress: These optimize storage. The current log is uncompressed for immediate readability, while the previous rotation is compressed immediately in the next cycle.
  • missingok and notifempty: These safety valves prevent the script from crashing if a service restarts and clears the log file unexpectedly.

Verifying Configuration and Testing

Before applying changes to a live system, it is prudent to test the configuration syntax. This step identifies typos or conflicting directives that could cause failures during rotation.

Run the following command to check for errors:

sudo logrotate -d /etc/logrotate.d/myapp

The -d flag stands for debug. It simulates the rotation process without actually moving or deleting files. You will see output similar to:

reading config file myapp
Warning: 'myapp' config contains a directive that was not recognized: 'dateformat'
...
considering log /var/log/myapp/app.log
  Now: Wed Oct 25 10:30:00 2023
  Last rotated at Wed Oct 24 00:00:00 2023
  is not scheduled to rotate

Note: The warning about dateformat in the debug output above is illustrative; newer versions of logrotate handle this differently. If you see “Error” instead of “Warning,” fix the syntax immediately.

To force a rotation for testing without waiting for the schedule, use the -f flag:

sudo logrotate -f /etc/logrotate.d/myapp

After forcing a rotation, verify that the new file exists and is compressed:

ls -lh /var/log/myapp/
# Expected output: app.log (new, small), app.log-20231025.gz (compressed)

Advanced Scenarios and Common Pitfalls

In complex environments, default configurations may not suffice. For instance, some applications write logs to subdirectories or require specific ownership changes.

Handling Subdirectories and Multiple Logs

If an application writes multiple logs to /var/log/myapp/debug.log and /var/log/myapp/error.log, you can group them in a single configuration block:

/var/log/myapp/*.log {
    daily
    rotate 4
    compress
    delaycompress
    missingok
    notifempty
    create 0644 myapp myapp
}

The wildcard *.log captures all files ending in .log within that directory.

Common Errors and Fixes

  • Permission Denied: If the rotation fails with “Operation not permitted,” ensure the user running logrotate (usually root) has write access to the target directory. Check with ls -ld /var/log/myapp.
  • File Ownership Mismatch: If the new log file is created with the wrong owner, the application may fail to write to it. Always use the create directive to specify the correct user and group (e.g., www-data for Apache/Nginx).
  • Disk Space Issues: Ensure that the temporary directory used by logrotate (/var/tmp) has sufficient space, especially when compressing large files.

Student Practice Task

To solidify your understanding, set up a controlled lab environment:
1. Create a dummy log file: echo "Test entry $(date)" > /tmp/test.log.
2. Write a custom configuration in /etc/logrotate.d/testlab using a rotation count of 2 and compression enabled.
3. Execute sudo logrotate -v -f /etc/logrotate.d/testlab (the -v flag provides verbose output).
4. List the directory contents to confirm that test.log was rotated and compressed, while the original filename was restored for new entries.

Industry Application Checklist

For experienced practitioners deploying this on production infrastructure, use this checklist before finalizing configurations:

  • [ ] Backup Configuration: Always copy the existing /etc/logrotate.conf and files in /etc/logrotate.d/ before making changes.
  • [ ] Test First: Run with -d (debug) mode to verify syntax without side effects.
  • [ ] Validate Permissions: Ensure the create directive matches the application’s user/group requirements.
  • [ ] Monitor Logs: Check /var/log/syslog or /var/log/messages after rotation to confirm no errors occurred during the process.
  • [ ] Review Retention Policies: Align maxage and rotate counts with your organization’s data retention compliance requirements (e.g., GDPR, HIPAA).

Conclusion

Automating log file rotation using logrotate is a fundamental skill for any Linux administrator. By configuring directives such as daily, compress, and maxage, you ensure that systems remain performant and compliant with storage policies. Remember to always test configurations in a non-production environment first and verify that the new log files are being created with the correct ownership. Proper management of logs not only prevents disk space exhaustion but also ensures that historical data remains accessible for debugging when needed.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.