I am using log4net. The problem is I create the connection string only after the application is started based on the connection string in the config file. This means the config file does not have a proper connection string yet. I am able to modify the connection string of the appender using this code..
IAppender[] appenders = log.Logger.Repository.GetAppenders();
foreach(IAppender appender in appenders)
{
AdoNetAppender adoAppender = appender as AdoNetAppender;
if (adoAppender != null)
{
adoAppender.ConnectionString = new conn string;
}
}
However, in order to get the logger (first line of the code sample), the logger tries to connect using the default connection string ans hence throws an exception.
Is there any other way to get the appender string so that I don't have to connect before modifying the string?
After messing with it a bit (referring to this question/answer and this blog), it looks like the <connectionString>
setting under the AdoNetAppender in the app.config needs to be removed, and a <connectionType>
setting needs to be added (if it's not already there):
<connectionType value="System.Data.SqlClient.SqlConnection,
System.Data,
Version=4.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089" />
Then you can modify the connection string in the code:
log4net.Config.XmlConfigurator.Configure();
log4net.Repository.Hierarchy.Hierarchy hier = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;
if (hier != null)
{
var adoAppender = (AdoNetAppender)hier.GetAppenders()
.Where(appender => appender.Name.Equals("AdoNetAppender", StringComparison.InvariantCultureIgnoreCase))
.FirstOrDefault();
if (adoAppender != null)
{
adoAppender.ConnectionString = connstring;
adoAppender.ActivateOptions(); //refresh settings of appender
}
}
ILog log = LogManager.GetLogger("test");
log.Info("Test Message");
Another alternative, if the connection string is under the <connectionString>
's in the app.config file, then you can add the following to your appender:
<connectionStringName value="ConnectionStringNameFromAppConfig" />