Modify Logger's adoAppender.ConnectionString

自古美人都是妖i 提交于 2019-12-11 06:26:05

问题


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

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/19962870/modify-loggers-adoappender-connectionstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!