Setting a log4net AdoNetAppender Connection String at Runtime

I recently implemented log4net in a project to log to a database using the log4net AdoNetAppender class. But I had a need to be able to specify the connection string at runtime. Here's how I was able to do it. Hopefully this will help out someone who has the same need. :)

protected void SetLog4NetAppenderConnectionString(string connectionString)
{
    log4net.Repository.Hierarchy.Hierarchy hierarchy =
        log4net.LogManager.GetLoggerRepository() 
            as log4net.Repository.Hierarchy.Hierarchy;
 
    if (hierarchy != null)
    {
        log4net.Appender.AdoNetAppender appender
            = (log4net.Appender.AdoNetAppender)hierarchy.GetAppenders()
                .Where(x => x.GetType() == 
                    typeof(log4net.Appender.AdoNetAppender))
                .FirstOrDefault();
 
        if (appender != null)
        {
            appender.ConnectionString = connectionString;
            appender.ActivateOptions();
        }
    }
}

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader