Back to home

How to Rotate Log Files

Introduction

Sometimes, log files can get fairly big. To avoid this, they can be “rotated” frequently. For that, logrotate is the best tool we know.

As an example, this article covers the configuration of logrotate for the log files of a Tomcat 8 instance, which are located in /home/www-data/example.ch/logs/catalina.out.

Configure Logrotate

You will need to add a configuration file (for instance, as a hidden file in the home folder): ~/.logrotate.conf.

A simple configuration could look like this:

/home/www-data/example.ch/logs/catalina.out {
  daily
  rotate 14
  notifempty
  compress
  copytruncate
}

With this configuration, logrotate:

  • rotates the file ~/example.ch/logs/catalina.out once per day
  • keeps 14 log files
  • does not rotate if the file is empty
  • compresses the log files

The copytruncate option does copy the log file and empties the log file afterwards.

This will end up in daily log files like this:

  • .../catalina.out-20161212.gz
  • .../catalina.out-20161213.gz
  • .../catalina.out-20161214.gz

More options to configure logrotate can be found here.

Execute Logrotate Daily

Logrotate can be executed like this:

/usr/sbin/logrotate -s ~/.logrotate.status.tmp ~/.logrotate.conf

We have to provide a custom state file with the -s option, since the global state file is only writeable by the root user.

To execute this command daily, we can add it to cron by executing crontab -e. Simply add following line to the end of the file:

0 0 * * * /usr/sbin/logrotate -s ~/.logrotate.status.tmp ~/.logrotate.conf >/dev/null 2>&1

Now, the logrotate is executed once a day at midnight. Be aware that with >/dev/null 2>&1 at the and of the command all output of the command is suppressed.

More information about the configuration of cron can be found here.

Didn't find what you were looking for?

Contact our support:

+41 44 637 40 40 Support Portal support@nine.ch