So the question is: How can we enhance the Log4Net AdoNetAppender to have the ability to refer to an already existing connection string defined in the connectionStrings section of the configuration?
The good news is that the team behind Log4Net is already working on this feature. The bad news is that as of now* this feature has not yet been released. This article describes how we can implement a simple solution ourselves.
1) Create a class that inherits from AdoNetAppender.
2) Next create a ConnectionStringName property that will set the Log4Net ConnectionString property to a connection string that is retrieved by the .Net ConfigurationManager.
3) Create a ConnectionStringName entry in the AdoNetAppender section of your config file which maps to an existing connectionString in the connectionStrings section of your config file.
Sample Custom AdoNetAppender Class:
using System.Configuration; using log4net.Appender; namespace WebUI.Infrastructure { public class MyCustomAdoNetAppender : AdoNetAppender { public string ConnectionStringName { set { ConnectionString = ConfigurationManager.ConnectionStrings[value].ToString(); } } } }
Sample Configuration File:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="AdoNetAppender" type="WebUI.Infrastructure.MyCustomAdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<ConnectionStringName value="MyConnectionName"/>
<!--Additional Info goes here -->
</appender>
<root>
<level value="All"/>
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
<connectionStrings>
<add name="MyConnectionName"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
</configuration>
* 03/26/2011
No comments:
Post a Comment
Your feedback is appreciated!