Header RSS Feed
 
If you only want to see the articles of a certain category, please click on the desired category below:
ALL Android Backup BSD Database Hacks Hardware Internet Linux Mail MySQL Monitoring Network Personal PHP Proxy Shell Solaris Unix Virtualization VMware Windows Wyse

MongoDB 3.x: Create log rotation script
Monday - Jul 6th 2015 - by - (0 comments)

On a recently installed MongoDB 3.x server, it seems that MongoDB now writes much more logs than the previous 2.x version.

According to the documentation, a log rotation, done by MongoDB itself, can be forced by sending the SIGUSR1 signal to the MongoDB process. When this is done, a rotated log file is created with a date extension:

root@mongoserver:/var/log/mongodb# ls -ltr
-rw-r--r-- 1 mongodb nogroup 168167263 Jul  6 10:31 mongod.log.2015-07-06T08-31-32
-rw-r--r-- 1 mongodb nogroup   1371461 Jul  6 10:32 mongod.log

My goal was to use send SIGUSR1 as a prescript command in logrotate and then compress the newly created file (mongod.log.2015-07-06T08-31-32 in this case). Unfortunately this doesn't work with logrotate, because the file extension, created by MongoDB, is too variable.
So I quickly created the following script which sends SIGUSR1 to the MongoDB PID, then compresses the rotated logfile:

#!/bin/bash
#####################################################
# MongoDB Logrotate Script
# (c) Claudio Kuenzler www.claudiokuenzler.com
# 20150706 ck  Created script
#####################################################
# Variables
logpath=/var/log/mongodb
pidfile=/run/mongodb.pid
#####################################################
# 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 `cat $pidfile`
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

This script is now run once a day by as a cronjob.

Successfully tested on Ubuntu 14.04 LTS with MongoDB 3.0.4 (installed from 10gen repo).

Side note: It's of course also possible to add a deletion of old rotated logfiles into the script, for example:

find $logpath/ -name "mongod.log.*gz" -mtime +7 -exec rm {} +

 

Add a comment

Show form to leave a comment

Comments (newest first):

No comments yet.

Go to Homepage home
Linux Howtos how to's
Monitoring Plugins monitoring plugins
Links links

Valid HTML 4.01 Transitional
Valid CSS!
[Valid RSS]

7422 Days
until Death of Computers
Why?