How to Setup Log Rotation on MongoDB 3.4

mongodb log rotationIn this article, I'm going to tell about MongoDB log rotation. Logs are text files which can include informational, warning or error records while our program runs. We need to perform log rotation as these files can become too large and use too much disk space. Also large files take more time to be opened and analyzed. Old log files can be also zipped to reduce their size.

I am going to use CentOS 7 virtual machine created in VMware Workstation with 1 vCPU, 1 GB of RAM and 20 GB of disk space and MongoDB 3.4 .

By default MongoDB logs are located in /var/log/mongodb. You can change the location of the log file by starting MongoDB service with --logpath

# mongod -v --logpath /var/log/mongodb/server1.log

The easiest way to perform log rotation is to manually execute

# kill -SIGUSR1 $(cat /var/lib/mongo/mongod.lock)

and remove logs

# rm -rf /var/log/mongodb/mongod.log.*

or compress them to free some disk space

# tar -cf /var/log/mongodb/mongod.log.*

SIGUSR1 signal is sent to the mongod process and performs log rotation.
Another way doing log rotation is to enter mongo console by typing 'mongo' in command line. Then in database console execute

    > use admin
    > db.runCommand( { logRotate : 1 } )

Output must be

    { "ok" : 1 }

You can also specify the behavior of the logRotate command by starting mongo with the --logRotate key. You should specify the option for this key rename or reopen. By default option rename is used. Rename option just renames the log file. Reopen option closes and reopens file. This option must be used with --logappend key and logrotate utility to avoid data loss.

For automated rotaion we can use logrotate utility.
First of all create file

# vi /etc/logrotate.d/mongodb

and insert there

/var/log/mongodb/mongodb.log {
    daily
    rotate 30
    compress
    missingok
    sharedscripts
    postrotate
        	kill -SIGUSR1 $(cat /var/lib/mongo/mongod.lock)
    endscript
}

Just a few words about this configuration file. 'Daily' means that logs are rotated every day, 'rotate 30' - logs will be kept for 30 days before being sent via email or deleted, 'compress' - old logs are compressed with gzip, 'missingok' - skip any errors in any log file is missing, 'sharedscript's - scripts that are run script once, 'postrotate' and 'endscript' - execute script after log rotation.

Logs can be also sent to the host system log file by running mongo instanse with --syslog. This option is not supported on Windows hosts.

About Pavlo Maiorchyk

Systems Administrator and hardware developer with 4 years of professional experience in IT. My goal is to deliver only best solutions and customer support.

Author Archive Page

Have anything to say?

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.