Course contentsShow
← Linux
Lesson 1293 of 1,81911. Automation and System SchedulingFree lesson

Automating Log Rotation Triggers

Customise logrotate triggers to execute post-rotation cleanup or compression jobs.

In this lesson, you will learn how to extend the standard log rotation process by executing custom post-rotation scripts to handle cleanup or specialized compression tasks.

While logrotate is primarily designed to manage file sizes and retention, it is often necessary to perform secondary maintenance—such as uploading an archived log to off-site storage, clearing temporary cache files, or notifying a monitoring service—immediately after a file has been rotated.

Integrating Custom Hooks

logrotate provides specific directives within its configuration files to trigger external scripts. The most common tool for this is the postrotate block. When you define this in a configuration file (usually found in /etc/logrotate.d/), logrotate will execute your commands only after the rotation cycle is complete for that specific log file.

Consider this example configuration for a custom application log:

/var/log/myapp/*.log {
    daily
    rotate 7
    compress
    postrotate
        /usr/local/bin/archive_logs.sh --target /mnt/backup
        find /var/log/myapp/ -name "*.old" -delete
    endscript
}

Why Use postrotate?

The postrotate block is powerful because it runs with the same privileges as the logrotate process (typically root). By placing your cleanup logic inside the endscript block, you ensure that these tasks happen in sequence with the rotation. If the rotation fails, the script will not execute, which helps maintain the integrity of your automation.

Best Practices for Automation

When writing these scripts, remember the principles of idempotency you learned earlier: ensure your postrotate logic can handle cases where a file might have been moved or renamed by a previous process. Since logrotate runs periodically, your cleanup script should avoid blocking the system for long periods. If your cleanup task is resource-intensive, consider having the postrotate script simply trigger a systemd unit or a background task, allowing the rotation process to complete instantly without waiting for heavy I/O operations to finish.

Key Takeaway: Use the postrotate and endscript directives in your logrotate configuration to seamlessly bridge the gap between log maintenance and automated system cleanup tasks.