Skip to content

Instantly share code, notes, and snippets.

@pancudaniel7
Created January 17, 2024 22:20
Show Gist options
  • Save pancudaniel7/ca7e8d2c6df7831161250041f850d82a to your computer and use it in GitHub Desktop.
Save pancudaniel7/ca7e8d2c6df7831161250041f850d82a to your computer and use it in GitHub Desktop.

Logrotate Configuration with Systemd Timer

This document explains how to set up logrotate to manage log files more frequently using a systemd timer. This approach is useful for log files that grow rapidly and need to be rotated more often than the daily rotation typically provided by cron jobs.

Logrotate Configuration

First, set up the logrotate configuration for your specific log file. Create a file in /etc/logrotate.d/ for your application. Here is an example configuration that rotates a log file when it reaches a certain size:

# /etc/logrotate.d/your-application
/path/to/your/logfile.log {
    size 100M
    copytruncate
    rotate 30
    compress
    missingok
    notifempty
    create 640 root adm
}
  • size 100M means the log file will be rotated when it exceeds 100 megabytes.
  • copytruncate allows the log file to be truncated in place after being copied, which is useful for logs that are being written continuously.
  • rotate 30 keeps the last 30 rotated logs.
  • Other options like compress, missingok, notifempty, and create provide additional log management features.

Systemd Timer Setup

Creating the Service File

Create a systemd service file to run logrotate:

  1. Create a file named /etc/systemd/system/logrotate.service with the following content:

    [Unit]
    Description=Rotate log files
    
    [Service]
    ExecStart=/usr/sbin/logrotate /etc/logrotate.conf

Creating the Timer File

  1. Create a timer file named /etc/systemd/system/logrotate.timer:

    [Unit]
    Description=Run logrotate every 10 minutes
    
    [Timer]
    OnCalendar=*:0/10
    Persistent=true
    
    [Install]
    WantedBy=timers.target

    This schedules logrotate to run every 15 minutes.

Enabling and Starting the Timer

  1. Reload the systemd daemon, enable, and start the timer:

    sudo systemctl daemon-reload
    sudo systemctl enable logrotate.timer
    sudo systemctl start logrotate.timer
  2. To check the status of the timer, use:

    sudo systemctl list-timers

Conclusion

This setup allows for more frequent rotation of log files, which can be crucial for logs that grow quickly. Remember to monitor your system's performance, as more frequent log rotation can increase system load.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment