我使用的是log4net,我有一个连接字符串要在我的log4net配置中引用,因为"/config/conconnectionStrings.config"中的connectionString将是用户的动态输入。
以下是我要做的:
<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="ConfigConnectionStrings.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在connectionStrings:中期望类似的内容
<connectionString value="data source=SQLSVR;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sa" />
我的参考配置:Config\ConnectionStrings.Config所有这些都是用户输入的,所以我需要第二个connectionString属性的connectionString值,它是
"数据源=(本地);初始目录=DbTwo;集成安全性=True;MultipleActiveResultSets=True;应用程序名称=AppName2"。
有没有一种方法可以使用ASP.NET C#获得这个值,这样我就可以在代码中创建数据库附加程序?或者在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" />
代码如下:
//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();
}
}
}