0

Can use tail to rotate a nginx log file in orderer to have a single log file capped in size?

tail -c 1000000 access.log > temp.log
mv temp.log access.log
kill -USR1 `cat /var/run/nginx.pid`

The above would be executed in a cron job (running every 5 minutes) every time access.log exceeds 1100000 bytes.

The last line tells nginx to reopen log files (as the second line deletes the original access.log)

I've read about variuos methods to rotate (nginx) logs but I've never read about this approach.

This way I end up having a single file capped in size.

And rotation is not applied to a set of files but to the log entries inside a single log file.

Of course tail -c (as from comments) will truncate the first (oldest line).

The major issue with that is that while tail is writing the truncate file the process is still writing log entries so some entries may get lost.


Bottom note:

I'm aware of logrotate and newsyslog tools, I've read the main parts of the documentation and they are also trivial to setup for ordinary scenarios.

My attempt is not to reinvent the wheel. I'm just "curious" to know if things can be done in a different way.

The answer probably is no for very good reasons.

I'm just trying to have a better understanding on the subject.

Paolo
  • 149
  • 6
  • 6
    Why have you decided not to use logrotate? – Tim Mar 26 '17 at 22:09
  • If you use `-c` there, you will get broken lines. – Tero Kilkanen Mar 26 '17 at 23:00
  • 2
    Terrible. Application keeps writing to the (still open) filehandle for the (deleted but still open) `access.log` and the disk fills up mysteriously until in confusion the system is rebooted or (hopefully) someone knows something about `lsof` and how to setup proper logrotation. – thrig Mar 27 '17 at 03:28
  • @thrig you're right. however nginx provides a way to reopen log files, I updated the question. – Paolo Mar 27 '17 at 16:23
  • @Tim It's just a question... Probably I'll go with logrotate, or newsyslog (since in this case I'm on mac OS). However I was looking for a solution that let me keep a single file with the last `x` MB of logs instead of a set of rotating files. – Paolo Mar 27 '17 at 16:29
  • @TeroKilkanen only the first (oldest) line will be truncated. I can live with that. – Paolo Mar 27 '17 at 16:32
  • https://superuser.com/questions/291368/log-rotation-of-stdout#291397 may be of some interest – thrig Mar 27 '17 at 16:56
  • Actually I became a friend of logrotate. It's a nice tool you already have on your system, created just for this purpose. It's a standard solution so another system administrator knows how to handle your setup. The configuration can be hold in a specific file (e.g. /etc/logrotate.d/nginx) so your configuration can be managed by Puppet, Chef or whatever. Using a wrench to bang in a nail might be a solution if you don't have a hammer. – Jens Bradler Mar 28 '17 at 07:46

0 Answers0