Keep your Mongo log database small deleting old logs
As I showed in an old post, Mongo Db is perfect to store logs, but as everyone knows, log databases tend to become really big, especially if the verbosity level is high, so I usually schedule a process that deletes all log older than a certain date to free space in log databases. To cleanup record in a Mongo Db I decided to create a little Powershell script to delete all entry in a collection that are older than a certain value. The whole scritp is reported here.
|
|
The scritp is really simple first of all I get the actual date with the Get-Date powershell function, then I subtract 20 days to create the date limit and grab the year, month and day part of it The cleanup process is a simple call to Mongo.exe command line tool that accepts the address of the database as first argument in the form of address:port/databasename followed by –eval to directly execute a command. The real delete command has this form: *db.NameOfTheCollection.Remove(Condition),*in this situation the condition is something like {timestamp: {$lt:new Date(year, month, day)}}. Pay attention to the thick sign (`) before the $lt, because it is the escape character used in powershell and it is needed to insert a dollar sign inside a string.
All you need to do is schedule this script to run once a day to keep in your Mongo database only the last 20 days of logs.
Gian Maria