How to Configure NGINX Log Rotation


configure nginx log rotation

NGINX is a powerful web server with an excellent logging system that records various kinds of messages. However, if you leave the log files to grow forever, they will fill your entire file system. You can prevent it by setting NGINX to periodically clean up log files. It is called log rotation and is easy to setup. Let us take a look at how to configure NGINX log rotation.

 

How to Configure NGINX Log Rotation

Here are the steps to configure NGINX log rotation. We will install logrotate module in NGINX that will compress or rename main log file when a condition is triggered, and log the next even in a black file.

It will also delete old log files and keep only the recent ones. You can always decide how it should determine old log files and how frequently it should rotate logs.

 

1. Install Logrotate in Linux

You can install Logrotate with the following command

On Debian and Ubuntu


# sudo apt update && aptitude install logrotate

On CentOS, RHEL and Fedora


# yum update && yum install logrotate

 

It will add the config file at /etc/logrotate.conf. You can also include more service-specific settings in /etc/logrotate.d

 

 

2. Configure Log Rotation

Logrotate offers many directives to help us configure how and when the logs should be rotated. You can add log rotation config for NGINX by creating a new file called nginx.conf at /etc/logrotate.d, if it doesn’t exist.


$ sudo vim /etc/logrotate.d/nginx.conf

Add the following lines in it


/var/log/nginx/* {
 weekly
 rotate 3
 size 10M
 compress
 delaycompress
}

 

In the above code,

  • weekly – rotate logs every week
  • rotate 3 – keep only last 3 logs. older ones should be deleted
  • size 10M – rotate logs only when their size reaches 10Mb
  • delaycompress – compress all logs except the most recent one

 

3. Test Log Rotation

Test the logrotate configuration with the following command


$ sudo logrotate -d /etc/logrotate.d/nginx.conf

 

You will see the file names of rotated logs in output

 

4. Customization

By default, logrotate will name the logs as access.log , access.log.1, etc. If you want to add a date stamp you can use the dateext directive. If you also want to specify a date format, use the dateformat directive, as shown below in bold


/var/log/nginx/* {
 weekly
 rotate 3
 size 10M
 compress
 delaycompress
 dateext
 dateformat -%d%m%Y
}

 

The installation of logrotate will also create a crontab file at /etc/cron.daily named logrotate, which runs every day at 6:25am.

That’s it! You have installed and configured NGINX log rotation.

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!