Here is a simple way to make sure you don't have to put the connectionstring in the config file for Log4Net and instead just pull it from the connectionString setting:
using System;
using System.Collections.Generic;
using System.Configuration;
using log4net.Appender;
using System.Data.Common;
namespace Log4net.Appender
{
public class AppSettingsConnectionStringAdoNetAppender : AdoNetAppender
{
string _connectionStringName;
public string ConnectionStringName
{
get { return _connectionStringName; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Null or empty connection string name.");
try
{
ConnectionStringSettings connectionString =
ConfigurationManager.ConnectionStrings[value];
DbProviderFactory factory = DbProviderFactories.GetFactory(
connectionString.ProviderName);
using (DbConnection connection = factory.CreateConnection())
{
this.ConnectionType = connection.GetType().ToString();
this.ConnectionString = connectionString.ConnectionString;
}
_connectionStringName = value;
}
catch(Exception ex)
{
throw new ArgumentException("We can't initialize connection string from the name passed. " + value, ex);
}
}
}
}
}
Take this code and add it to your appender library or create your own library and build the assembly. After that, in your log4net config file you can call the appender now like any other appender:
<appender name="My_AdoNetAppender" type="Log4Net.Appender.AppSettingsConnectionStringAdoNetAppender, JLFramework.Log4Net.Appender">
</appender>
No comments:
Post a Comment