Thursday, July 30, 2015

How to Rotate Log in MongoDB (5 min setup)

This is what I use to rotate my MongoDB log

Assumptions:  You have installed MongoDB and you can execute 'mongo' shell command-line utility from anywhere in your shell.


  1. Create Javascript File:

    nano /home/myname/mongodb_rotate_log.js

    Add the following line:

    db.runCommand( { logRotate : 1 } );

    press CTRL-X, Y, Enter    (to save and exit)

  2. Add to mongo shell command CRONTAB
    crontab -e

    Add the following line:

    33 3 * * 6 mongo admin /home/myname/mongodb_rotate_log.js

    that line will schedule log rotation every Saturday night at 3:33am.

    press CTRL-X, Y, Enter    (to save and exit)

  3. Add shell command to clean-up after ## days

    crontab -e

    Add the following line:

    19 4 * * * find /log/ -type f -mtime +30 | xargs rm

    the line above will schedule log cleanup at /log/ directory recursively
    it will remove any file older than 30 days

    press CTRL-X, Y, Enter    (to save and exit)