Dynamically Set Log4net Appender File Path

Fri, Feb 20, 2009

Technology

I spent some time today working out how to configure log4net.  While an extremely powerful logging tool it can be a little confusing to configure for the first time.  During my testing I thought it might be useful to set the filename of the log dynamically so that I can insert in the name of the assembly, or the name of the class file, instead of a static file name in the log4net configuration file.

UPDATE:  Leave it to the great folks at StackOverflow to know a better and more efficient way to accomplish this task:

<appender name="YourAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
  ....
</appender>
string LogName = GetType().Assembly.GetName().Name + ".log";
log4net.GlobalContext.Properties["LogName"] = LogName;

It took a little longer than I would like to admit but I was able to get to the configuration I wanted.  I’m sharing this in hopes that it might help prevent other people from having to go through the same effort.  I chose to put the code in the Global.asax file so that it will be loaded when the application starts.  You can also add this to a class file.  Which ever suits your needs.

// Bind to the root hierarchy of log4net
log4net.Repository.Hierarchy.Hierarchy root =
  log4net.LogManager.GetRepository()
    as log4net.Repository.Hierarchy.Hierarchy;

if (root != null)
{
  // Bind to the RollingFileAppender
  log4net.Appender.RollingFileAppender rfa =
    (log4net.Appender.RollingFileAppender)root.Root.GetAppender("RollingLogFileAppender");

  if (rfa != null)
  {
    // Set the file name based on the assembly name
    string filePath =
      string.Format("~/App_Data/{0}.log", GetType().Assembly.GetName().Name);

    // Assign the value to the appender
    rfa.File = Server.MapPath(filePath);

    // Apply changes to the appender
    rfa.ActivateOptions();
  }
}

Comments are closed.