5

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.

3
  • Have you tried actually doing what is documented in that tutorial? Commented Aug 24, 2018 at 1:46
  • 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 . Commented Aug 24, 2018 at 1:50
  • I can only confirm that your simple test pasted above, works in my setup Commented Sep 12, 2018 at 9:23

1 Answer 1

6

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)
4
  • 3
    why not to use logrotate for this? Commented Sep 12, 2018 at 9:06
  • Because I can do it in a single line of bash Commented Sep 12, 2018 at 10:35
  • but then you cannot ask that one line of code to save only 14 days of historic logs, supposing that this feature is wanted. Commented Feb 21, 2020 at 6:49
  • True. I'll need a second line of code to delete the log files which are more than 14 days old. Commented Feb 21, 2020 at 18:56

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.