Home > Programming > Using MongoDB as the Audit and Log data store with a custom tracelistener

Using MongoDB as the Audit and Log data store with a custom tracelistener

This post illustrates how one would save changes to ADO entities and other logging via the enterprise library logging application block to MongoDB. MongoDB is an open source agile document oriented nosql database that supports sharding, map-reduce, indexing on attributes, GridFS etc. MongoDB is fast to setup and fast to scale. The choice to move logging to MongoDB was to make use of running map reduce jobs on the dataset.

To be able to connect to MongoDB process you will have to download the latest C# Driver

To be able to log via the Enterprise Logging Application Block I created a custom trace listener and trace listener configuration. The trace listener configuration was to allow specifying MongoDB connection string and database name. The custom trace listener opens the connection to the MongoDB process and inserts the updates. Every attempted change to the entity is stored.

Changes to entity are logged at the point the data context is saving changes by subscribing to the SavingChanges event.

void OnSavingChanges(object sender, EventArgs e)
ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified)
.Where(entity => !entity.IsRelationship && entity.Entity is IEntity)
.Select(entity => new AuditEntry((IEntity)entity.Entity, UserService.GetCurrentUser().Name, entity.State))

The Entriprise lib LogEntry object is sent directly to the database unless it has AuditEntities. AuditEntities are saved in the AuditEntry collection whereas the rest of the log entries are stored in the LogEntry collection. The entity is saved as an attribute of AuditEntry called Entity.

public interface IAuditEntry: IEntity where TEntity : IEntity
TEntity Entity { get; set; }
string EntityModifiedBy { get; set; }
EntityState @EntityState { get; set; }

The Extension file has the code that checks the LogEntry object if it has AuditEntities in the ExtendedProperties and method for logging using the enterprise lib Logger. In the attached file I mocked (Moq) the user IIdentity object, but depending on your application context you know how to get the current user IIdentity. You can download a zip having all the files here.

Categories: Programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: