MongoDB Logrotate
2021-08-12 (updated 2025-10-25)Notes | 2 min read
#ansible #linux #logs #mongodb
MongoDB does not rotate it’s log on it’s own.
To get it to ratet we will use logrotate.
First, we need to configure some things in mongod.conf to get the desired behaviour when we utilize logrotate.
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
logRotate: reopen
Afterwards, we can create a logroatet configuration going in /etc/logrotate.d/mongodb.
/var/log/mongodb/mongod.log
{
rotate 5 # Keep the last 5 rotated logs, so 6 files including the currently active
size 10M # Rotate once the log reaches 10MB in size, depending on your envrionment you could instead use daily, weekly, monthly, etc
missingok # It's ok if the log file does not exist
create 0600 mongodb mongodb # Permissions and ownership for the roatetd logs
delaycompress # Don't compress on first rotation, so we have the current log and log.1 uncompressed
compress # Compress everything else
sharedscripts # Run this script only once and not for every matching file
postrotate # Script to run after rotating
/bin/kill -SIGUSR1 $(systemctl show --property MainPID --value mongod.service)
endscript # End of script
}
The postrotate script simply finds the PID of mongod.service: systemctl show --property MainPID --value mongod.service
and sends it a SIGUSR1 which is the signal MongoDB expects if you wish to rotate the log.
Finally, test the configuration by running
ls -la /var/log/mongodb/
sudo logrotate --force /etc/logrotate.d/mongodb
ls -la /var/log/mongodb/
For quick reference this Ansible task can be used to provision this logrotate configuration, simply place it locally in files/logrotate-mongodb and include it in your play.
- name: Provision MongoDB logrotate configuration
copy:
src: "logrotate-mongod"
dest: "/etc/logrotate.d/mongodb"
owner: "root"
mode: "644"
force: true
become: true