修改记录器的adoAppender

修改记录器的adoAppender

本文介绍了修改记录器的adoAppender.ConnectionString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用log4net.问题是我仅在应用程序启动后根据配置文件中的连接字符串创建连接字符串.这意味着配置文件还没有正确的连接字符串.我可以使用此代码修改附加程序的连接字符串.

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;
           }
}

但是,为了获取记录器(代码示例的第一行),记录器尝试使用默认的连接字符串ans进行连接,因此引发异常.

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?

推荐答案

稍微弄乱之后(请参阅此和此博客),看起来需要删除app.config中AdoNetAppender下的<connectionString>设置,并且需要添加<connectionType>设置(如果尚不存在):

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");

另一种选择,如果连接字符串位于app.config文件中<connectionString>的下面,则可以将以下内容添加到附加程序中:

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" />

这篇关于修改记录器的adoAppender.ConnectionString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:45