Mongodb - proper way to rotate logs

Solution 1:

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
}

Solution 2:

The server crashed for me if you send SIGUSR1 to mongod after you have moved the logfile out of the way with logrotate.

The following config is safe for the version I've tested - 2.6.6 on ubuntu 12.04 - the previous examples crashed the server. Put this into /etc/logrotate.d/mongod:

/var/log/mongodb/mongodb.log {
    weekly
    missingok
    rotate 4
    compress
    notifempty
    create
    postrotate
        /usr/bin/pkill -USR1 mongod
        rm /var/log/mongodb/mongodb.log.????-??-??T??-??-??
    endscript
}

See: https://jira.mongodb.org/browse/SERVER-11087 for more details and a suggestion from Akshay Kumar which I used in the above (use create instead of nocreate and cp /dev/null to the logfile).

In later releases there is supposed to be a logRotate option you can use to reopen the file - not rename it - which will work around the rename problem - but it didn't work in my version (it was unsupported).

See: https://github.com/mongodb/mongo/commit/616461d294bd9f5054ca38b302b6fc5d70fde20c

I've tested this with

logrotate -v -f /etc/logrotate.d/mongod

Solution 3:

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
}