Logrotate is a system utility that manages the automatic rotation and compression of log files. If log files were not rotated, compressed, and periodically pruned, they could eventually consume all available disk space on a system.

Logrotate’s configuration information can generally be found in two places:

/etc/logrotate.conf: this file contains some default settings and sets up the rotation for a few logs that are not owned by any system packages. It also uses an include statement to pull in configuration from any file in the /etc/logrotate.d directory.

/etc/logrotate.d/: this is where any packages you install that need help with log rotation will place their Logrotate configuration. On a standard install, you should already have files here for basic system tools like apt, dpkg, rsyslog and so on.

Example

/var/log/apt/history.log

{
  rotate 12
  monthly
  compress
  missingok
  notifempty
  create 0640 www-data www-data
  sharedscripts
  postrotate
  systemctl reload example-app
  endscript
}

Explanation:

  • rotate 12: keep twelve old log files.

  • monthly: rotate once a month.

  • compress: compress the rotated files. this uses gzip by default and results in files ending in .gz. The compression command can be changed using the compresscmd option.

  • missingok: don’t write an error message if the log file is missing.

  • notifempty: don’t rotate the log file if it is empty.

  • create 0640 www-data www-data: this creates a new empty log file after rotation, with the specified permissions (0640), owner (www-data), and group (also www-data).

  • sharedscripts: this flag means that any scripts added to the configuration are run only once per run, instead of for each file rotated. Since this configuration would match two log files in the example-app directory, the script specified in postrotate would run twice without this option.

  • postrotate to endscript: this block contains a script to run after the log file is rotated. In this case we’re reloading our example app. This is sometimes necessary to get your application to switch over to the newly created log file. Note that postrotate runs before logs are compressed. Compression could take a long time, and your software should switch to the new logfile immediately. For tasks that need to run after logs are compressed, use the lastaction block instead.