8

我正在使用 log4net,并且我有一个我想在我的 log4net 配置中引用的连接字符串,因为“/Config/connectionStrings.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="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 期望在 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" />

4

1 回答 1

14

代码如下所示:

 //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();
            }
        }
    }
于 2013-08-08T20:04:35.177 回答