Log4Net, changing the filename of an Appender at runtime.

Alex van Buitenen

This example shows how to change the filename of a Log4Net Appender at runtime.
Note: The filename defined in the config file will also be written, with a length of 0.

using log4net;
using log4net.Config;
using log4net.Appender;
using log4net.Repository.Hierarchy;
 

private log4net.Appender.FileAppender GetAppender()
{
  log4net.Repository.Hierarchy.Hierarchy h =
  log4net.LogManager.GetRepository() as
  log4net.Repository.Hierarchy.Hierarchy;
  log4net.Appender.FileAppender fa =
    (log4net.Appender.FileAppender)h.Root.GetAppender("RollingFile");
  return fa;
}

/// <summary>
/// //Name of the Abacus main logfile.
/// </summary>
public string LogFileName
{
  get
  {
    if (GetAppender() != null)
      return GetAppender().File;
    else
      return "";
  }

  set
  {
    if (GetAppender() != null)
    {
      GetAppender().File = value;
      GetAppender().ActivateOptions();
    }
  }
}