NoSQL Zone is brought to you in partnership with:

I started programming with Vic20 and never stopped, I passed from Pascal to Fortran C/C++, assembly and I worked with Microsoft .NET since the first public beta. Actually I work in Italy as independent consultant on developing web and desktop applications for windows environment. Ricci is a DZone MVB and is not an employee of DZone and has posted 9 posts at DZone. You can read more from them at their website. View Full User Profile

Purge Old Mongo Logs without User Intervention

05.23.2012
| 2285 views |
  • submit to reddit

One of the coolest feature of Mongo is the concept of Capped Collection, or “fixed size” collection. They are based on a FIFO queue where the first record to be discharded is the first inserted, and this is exceptional to create a log-collection that automatically purge all old logs without any user intervention.

To be able to automatically enable this feature on the Log4Net Mongo appender you need to do a little modification to the code, this is because the original code simply gets a reference to the collection with this code.

connection = MongoServer.Create(mongoConnectionString.ToString());
connection.Connect();
var db = connection.GetDatabase(DatabaseName);
collection = db.GetCollection(CollectionName);

C# drivers for Mongo automatically creates a collection if it is not present, this means that when you call db.GetCollection if the collection is not present it will be automatically created, but it is not capped. To solve this problem you can modify the initialization code with this code.

if (!db.CollectionExists(collectionName)) {
    var options =  CollectionOptions
        .SetCapped(true)
        .SetMaxSize(CappedSize);
    db.CreateCollection(collectionName, options);
}
collection = db.GetCollection(CollectionName);

MongoDb C# drivers has a class called CollectionOptions used to setup options to create a new MongoCollection and it can be accessed with a really easy Fluent-Interface, in my example I call SetCapped(true) to enable a capped collection and SetMaxSize() to setup the maximum size in bytes. The size of the capped-collection is stored in the appender property called CappedSize, the default is 500MB, but you can setup any size you likes in standard log4Net configuration.

Published at DZone with permission of Ricci Gian Maria, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)