Configuring Log Rotation on MongoDB using SIGUSR1 signal

Ambience 2020+ requires MongoDB for the storing of its system data. The example below illustrates how to automate the rotation of the MongoDB logs in a Unix environment using SIGUSR1 signal. This approach does not require any configuration to the system or the use of the logrotate utility.

  1. Create a shell script, e.g. ‘mongodb_logrotate’ and input the following, ensure the logpath variable points to the MongoDB log path in your environment:
#!/bin/bash
# Variables
logpath=/var/log/mongodb
# Start
(
test -f $logpath/mongod.log || exit 1
echo "Starting MongoDB log rotation"
echo "Current logfile:"
ls -la $logpath/mongod.log
echo "Launching SIGUSR1 command"
kill -SIGUSR1 `pidof mongod`
echo "Compressing new logfile"
find $logpath/ -name "mongod.log.$(date +%Y)*" ! -name "*.gz" -exec gzip {} +
echo "Finished MongoDB log rotation"
echo "-----------------------------------------------------"
) 2>&1 | tee -a ${logpath}/rotate.log

exit 0
  1. Execute the shell script at the command line. The following will be printed if successful, e.g.

sudo ./mongodb_logrotate
Starting MongoDB log rotation
Current logfile:
-rw------- 1 mongodb mongodb 9492 Sep 8 15:58 /var/log/mongodb/mongod.log
Launching SIGUSR1 command
Compressing new logfile
Finished MongoDB log rotation

  1. Go to the log path, there will be an archived MongoDB log and a new mongod.log created, the rotate.log captures the log rotation activity, e.g.

-rw------- 1 mongodb mongodb 1240 Sep 8 15:58 mongod.log
-rw------- 1 mongodb mongodb 2288 Sep 8 15:58 mongod.log.2021-09-08T07-58-19.gz
-rw-r–r-- 1 root root 256 Sep 8 15:58 rotate.log

  1. Create a cron job to run the log rotation shell script.

Download the sample shell script here:
mongodb_logrotate.txt (801 Bytes)

The above shell script was adapted from the following article:
https://www.claudiokuenzler.com/blog/566/mongodb-3.x-log-rotation-script