Logging is an essential part of any system. It helps us to debug and monitor the system. Log files are a common way to store logs generated by a system or application.

When there are a lot of logs generated by the system, it can consume a lot of disk space. To manage the log files, we can use the logrotate utility in Linux.

Log rotate configuration

Setting up log rotate to manage logs is simple. We need to create a configuration file in the /etc/logrotate.d/ directory.

Here is an example configuration file for logrotate:

Rotate log files daily and keep 7 days of logs:

/home/user/server-app/logs/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
}

The above configuration will

  • rotate the log files daily
  • retain 7 days of log files (deletes older log files)
  • compress the rotated log files
  • delay compression of the log files
  • ignore missing log files
  • do not rotate empty log files

We can also configure to rotate based on size

/home/user/server-app/logs/*.log {
    size 100M
    rotate 5
    compress
    delaycompress
    missingok
    notifempty
}

The above configuration will rotate the log files when the size reaches 100MB and retain 5 log files.

We can configure postrotate and prerotate scripts to run before and after log rotation.

/home/user/server-app/logs/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    prerotate
        systemctl stop myapp
    postrotate
        systemctl start myapp
    endscript
}

Running logrotate

To run logrotate manually, use the following command:

logrotate -f /etc/logrotate.d/myapp