Mongodb - proper way to rotate logs

Mongo docs say that I can:

  1. use -SIGUSR1 signal and get the old log renamed and current switched
  2. use logrotate from OS

I want the OS's logrotate ability to zip old files and remove oldest, but see no way to tell mongod process to switch current log other than sending SIGUSR1.

So I wrote

/var/log/mongodb/*.log {
    daily
    rotate 5
    compress
    dateext
    missingok
    notifempty
    sharedscripts
    postrotate
        /usr/bin/killall -SIGUSR1 mongod
        /usr/bin/killall -SIGUSR1 mongos
    endscript
}

to /etc/logrotate.d/mongo.

And now get well-named logfiles from logrotate and empty logfiles like mongodb.log.2013-09-18T23-49-44 as traces of SIGUSR1 switching. How to get rid of the latter?


Solution 1:

copytruncate works pretty well for logrotation.

a config similar to this should do the job for you:

/var/log/mongodb/*.log {
  daily
  missingok
  rotate 5
  compress
  dateext
  delaycompress
  copytruncate
  notifempty
}

Solution 2:

Since mongodb 3.0 you can change the behavior of mongodb with the logRotate parameter, change in /etc/mongod.conf

systemLog:
  logAppend: true
  logRotate: reopen

See also Mongo Manuals.

Then you can use this logrotate configuration:

/var/log/mongodb/*.log {
    daily
    rotate 30
    size 50M
    compress
    dateext
    missingok
    notifempty
    sharedscripts
    postrotate
        /bin/kill -SIGUSR1 `cat /var/lib/mongodb/mongod.lock 2> /dev/null` 2> /dev/null || true
    endscript
}