I am using log4net and I am have a connection string I want to reference in my log4net config, because the connectionString in "/Config/connectionStrings.config" will be dynamic input from the user.
Here is what I am trying to do:
<log4net xmlns="log4net">
<root>
<level value="ERROR" />
<appender-ref ref="DatabaseAppender" />
</root>
<appender name="DatabaseAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionStrings configSource="Config\ConnectionStrings.config" />
<commandText value="INSERT INTO dm.ErrorLogs ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
<parameter>....
</appender>
</log4net>
Log4net expects something like this in the connectionStrings:
<connectionString value="data source=SQLSVR;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sa" />
My reference config: Config\ConnectionStrings.config All of which is input from the user, so I need the connectionString value of the second connectionString attribute which is
"Data Source=(local);Initial Catalog=DbTwo;Integrated Security=True;MultipleActiveResultSets=True;Application Name=AppName2".
Is there a way to get this value using ASP.NET C#, so I can create a database appender in code? Or is there another I cold do this in the log4net.config?
<connectionStrings>
<add name="Connection1"
connectionString="Data Source=(local);Initial Catalog=DbOne;Integrated Security=True;Application Name=AppName1"
providerName="System.Data.SqlClient" />
<add name="Connection2"
connectionString="Data Source=(local);Initial Catalog=DbTwo;Integrated Security=True;MultipleActiveResultSets=True;Application Name=AppName2"
providerName="System.Data.SqlClient" />
Code looks like this:
//connectionString is the Web.config's connectionString, which I wanted to share.
public static void SetUpDbConnection(string connectionString, string logConfig)
{
//update connection string for log4net dynamically
var hier = LogManager.GetRepository() as Hierarchy;
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(logConfig));
if (hier != null)
{
var adoNetAppenders = hier.GetAppenders().OfType<AdoNetAppender>();
foreach (var adoNetAppender in adoNetAppenders)
{
adoNetAppender.ConnectionString = connectionString;
adoNetAppender.ActivateOptions();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With