log4net AdoNetAppender Connection String from App Config


Currently log4net version 1.2.10.0 is not supporting reading connection strings from or directly. But in order to read connection string from <appSettings>, we have to  override ActivateOptions and ConnectionString property of AdoNetAppender. 

Here is the code:

AppSettingsConnectionStringAdoNetAppender.cs file

namespace MyNameSpace
{

[Serializable()]
    public class AppSettingsConnectionStringAdoNetAppender : AdoNetAppender
    {
        public override void ActivateOptions()
        {
            PopulateConnectionString();            
            base.ActivateOptions();
        }

        private void PopulateConnectionString()
        {
            ConnectionString = ConnectionString;
        }

        public new string ConnectionString
        {
            get { return base.ConnectionString; }
            set {  
                  base.ConnectionString 
                      = ConfigurationManager.AppSettings["conn1"].ToString(); 
                 }
        }       
    }  
}


App.Config Entries for log4net:

<configuration>
  <configSections>
    <section name="log4net"   type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  <configSections>

<log4net>
    <root>
      <priority value="Info"/>     
      <appender-ref ref="CustomAdoNetAppender"/>
    <root>       
   
    <appender name="CustomAdoNetAppender" type="MyNameSpace.AppSettingsConnectionStringAdoNetAppender">     
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />     
      <commandText value="INSERT STATEMENT " />     
      <parameter>

      </parameter>
    </appender>
  </log4net>
</configuration>

 Main Program:

class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));

        static void Main(string[] args)
        {
log4net.Config.XmlConfigurator.Configure();
log.ErrorFormat("This is Test Error1!");
            Console.ReadLine(); 
        }
    }

This will insert a new error into Database.


Comments

Popular posts from this blog

Windows Azure Package Build Error: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Resource ID : 1. The request limit for the database is 180 and has been reached.

Update Excel Sheet using C#, Where Excel not Installed on Server