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.
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 100Mmeans the log file will be rotated when it exceeds 100 megabytes.copytruncateallows the log file to be truncated in place after being copied, which is useful for logs that are being written continuously.rotate 30keeps the last 30 rotated logs.- Other options like
compress,missingok,notifempty, andcreateprovide additional log management features.
Create a systemd service file to run logrotate:
-
Create a file named
/etc/systemd/system/logrotate.servicewith the following content:[Unit] Description=Rotate log files [Service] ExecStart=/usr/sbin/logrotate /etc/logrotate.conf
-
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
logrotateto run every 15 minutes.
-
Reload the
systemddaemon, enable, and start the timer:sudo systemctl daemon-reload sudo systemctl enable logrotate.timer sudo systemctl start logrotate.timer -
To check the status of the timer, use:
sudo systemctl list-timers
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.