Asynchronous Ado.Net Log4Net Appender

As I mentioned in my last post, the out of the box AdoNetAppender in Log4Net is a synchronous appender. This may be fine for many scenarios, but in cases where you have some latency between your application and your database server, you typically want to minimise interaction with the database, and a large amount of logging may cripple the perofrmance of your application.

I thought that it may be simple enough to create your own Log4Net appender, and sure enough, it turned out to be easy enough.

I decompiled the source code for the AdoNetAppender via reflector and set to work for a couple of hours a few false starts.

The configuration for the async version is practically identical to AdoNetAppender, we just need to reference the type from my assembly, instead of log4net.

I had to modify the code substantially to make it thread-safe as the IDbConnection and IDbCommand objects were fields that were overwritten for each log message leading to BeginTransaction being called on the same IDbConnection which throws an exception. Now – each log message receives it’s own connection and command object.

Interestingly, it seems to run slower than the synchronous ADO Appender on a local Sql Server. I think this is to be expected due to the context switching of all the threads when run in a tight loop. However, the logging does not block the main thread anymore, so this meets my requirements of logging not impacting the performance of theĀ  production code.

Source code is available for download under BSD license as well as Console and Winforms Test apps.

I have not tested this software extensively. I have written it to scratch an itch, not for production purposes, so please test extensively before relying on it.

Any feedback or bug reports welcome.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
This entry was posted in log4net, logging. Bookmark the permalink.