我正在使用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" />
我的参考配置: 配置\ ConnectionStrings.config 所有这些都是来自用户的输入,所以我需要第二个connectionString属性的connectionString值,这是
“Data Source =(local); Initial Catalog = DbTwo; Integrated Security = True; MultipleActiveResultSets = True; Application Name = AppName2”。
有没有办法使用ASP.NET C#获取此值,所以我可以在代码中创建数据库appender?或者还有另一个我在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" />
答案 0 :(得分:7)
代码如下所示:
//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();
}
}
}