nginx and Logrotate

February 3, 2012

I wanted to start cycling and compressing my previous nginx log files, as they were getting a little large. NGINX doesn't have built in support for log rotation, there is a system level linux command called logrotate that handles this on behalf of many applications. I'm doing this on a Debian squeeze.

/etc/logrotate.d

In /etc/logrotate.d you'll find a file for each application that is using logrotate. There should be one in here called nginx that contains the following:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
            [ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

This is the default rotate process for nginx files. I store my logs in /home/drumcoder/logs, so we will specify another block in this same file, using many of the same options.

/home/drumcoder/log/*.access.log {
    daily
    missingok
    rotate 52
    mail drumcoder@here.com
    compress
    delaycompress
    notifempty
    sharedscripts
    postrotate
            [ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

The following options are used:

  • daily - rotates the log files daily
  • missingok - it's fine if there is no log to rotate
  • rotate 52 - rotate logs 52 times, and then delete the oldest
  • mail drumcoder@here.com - before you delete an old log, send it to this mail address
  • compress - use gzip on old logs
  • delaycompress - leave one rotated log that isn't compressed so the process can still write to it if needed
  • notifempty - don't rotate empty file
  • sharedscripts - when telling nginx that logs have been rotated, only do it once rather than once for each file group

The bottom postrotate block sends a signal to nginx to tell it that logs have been rotated and it should pick up the file handles for the new ones.

References

Tags: nginx logrotate