Log rotation in nginx

15,624

Just set a cron task for a minute to midnight to move the logfile and rename it with the date and then send a USR1 signal to Nginx. This will trigger it to reopen log files and create a new one for the following day.

59 23 * * * mv /var/log/nginx/access.log /var/log/nginx/$(date +%F).access.log && kill -USR1 $(cat /run/nginx.pid)
Share:
15,624

Related videos on Youtube

jonnybot
Author by

jonnybot

Updated on September 18, 2022

Comments

  • jonnybot
    jonnybot over 1 year

    I've found an example of doing log rotation in Nginx here

    But a simple test with:

        set $date "2018-08-24";
        access_log /home/tim/log/access-http-$date.log default;
    

    produces a log file named access-http-.log. I'm using nginx 1.13.6 (with openresty).

    Update

    After much hacking & tweaking, I've come up with the following logrotate script to rotate the different log files that nginx produces. I've put it into /etc/logrotate. The remaining issue is that the logs don't rotate daily (I'm unsure why at present), but a logrotate -f <filename> produces exactly the result I want.

    An interesting note is that nginx -s reload can be used instead of USR1. That's unfortunately not referenced in the nginx logging page but I found it (in the man page IIRC). I build openresty/nginx manually to incorporate extra modules I need so I don't get various extras that come in the packaged version like the pid keeping.

    /path/to/log/access-http.log /path/to/log/access-https.log /path/to/log/api.log /path/to/log/error.log {
        daily
        missingok
        notifempty
        create 664 nobody tim
        dateext
        dateformat -%Y-%m-%d
        dateyesterday
        rotate 10
        su tim tim
        postrotate
            /usr/local/bin/openresty -s reload
        endscript
    }
    

    I figure this will be useful for anyone with a large nginx config serving both web pages and an API. I keep the http separate as I don't serve non-https pages and it keeps the script kiddie crap out of my page logs.

    • Michael Hampton
      Michael Hampton over 5 years
      Have you tried actually doing what is documented in that tutorial?
    • jonnybot
      jonnybot over 5 years
      I've tried the command that sets the $year, $month and $day variables. And then tried access_log /home/tim/log/access-$year.log; Same log file name .
    • Krzysztof Księżyk
      Krzysztof Księżyk over 5 years
      I can only confirm that your simple test pasted above, works in my setup
  • Krzysztof Księżyk
    Krzysztof Księżyk over 5 years
    why not to use logrotate for this?
  • Kid_Learning_C
    Kid_Learning_C about 4 years
    but then you cannot ask that one line of code to save only 14 days of historic logs, supposing that this feature is wanted.
  • miknik
    miknik about 4 years
    True. I'll need a second line of code to delete the log files which are more than 14 days old.