How do I set up log file rotation?

logrotate

We recommend the use of logrotate. The logrotate configuration is stored under /usr/local/etc/logrotate.conf. If necessary, this includes further configurations under /usr/local/etc/logrotate.d/. A separate configuration file should be created for each service in this directory. Configurations for the usual services such as php-fpm, nginx, etc. are already stored and active there. Using nginx as an example, the following results from inheritance from /usr/local/etc/logrotate.conf

daily
rotate 7
create
compress
include /usr/local/etc/logrotate.d

and /usr/local/etc/logrotate.d/nginx.conf

/var/log/nginx/*.log {
  missingok
  notifempty
  copytruncate
}

If the meaning is not clear from the names of the configuration parameters, please refer to the logrotate man page.

Logrotate is activated by a cronjob in the crontab of the root user:

sudo crontab -e -u root
5 0 * * * /usr/local/sbin/logrotate /usr/local/etc/logrotate.conf > /dev/null 2>&1

newsyslog

Newsyslog can also be used as an alternative to logrotate. The configuration is explained here using the example of the nginx log file.

The configuration files are stored in the /usr/local/etc/newsyslog.conf.d directory. Here too, a separate configuration file should be created for each service. If the directory does not yet exist, it must be created:

mkdir -p /usr/local/etc/newsyslog.conf.d

The configuration file for nginx looks like this, for example:

/var/log/nginx-access.log               644  7     *    @T00  JC    /var/run/nginx.pid
/var/log/nginx-error.log                644  7     *    @T00  JC    /var/run/nginx.pid

/usr/local/etc/newsyslog.conf.d/nginx

Description of the columns:

/var/log/nginx-access.log6447*@T00JC/var/run/nginx.pid
The source file to be rotatedPermissions for target filesHow many files should be keptSize of the file from which to rotate. (Rotate regardless of the size)when the rotation should take place (Here: Daily 0:00)Flags
J = compress
C = recreate file
Path to the pid for signals after rotation

A detailed description of the newsyslog configuration can be found in the newsyslog man page.