How do I set up log file rotation?

logrotate

We recommend using logrotate. The logrotate configuration is stored in /usr/local/etc/logrotate.conf. This file may include additional configurations located in /usr/local/etc/logrotate.d/. A separate configuration file should be created in this directory for each service. Configurations for common services such as php-fpm, nginx, etc., are already stored there and are active. Using nginx as an example, the configuration is inherited 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 cron job in the root user's crontab:

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

newsyslog

As an alternative to logrotate, you can also use newsyslog. The configuration is explained here using the nginx log file as an example.

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

For example, the configuration file for nginx looks like this:

/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*@T00 JC/var/run/nginx.pid
The source file to be rotatedPermissions for target filesNumber of files to retainFile size at which rotation begins. (Rotate regardless of size) When rotation should take place (Here: Daily at 12:00 AM)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.