How do I use a GlobalContext property in a log4net appender name?

Long Pham picture Long Pham · Feb 18, 2009 · Viewed 40.3k times · Source

I'm trying to customise a log4net file path to use a property I have set in the log4net.GlobalContext.Properties dictionary.

log4net.GlobalContext.Properties["LogPathModifier"] = "SomeValue";

I can see that this value is set correctly when debugging through it. and then in my configuration

<file type="log4net.Util.PatternString" 
      value="Logs\%appdomain_%property{LogPathModifier}.log" />

However, the output of this gives me "_(null).log" at the end of the path. What gives?

Answer

Dscoduc picture Dscoduc · Feb 21, 2009

I ran into the same behavior and solved it by setting the global variable before calling the XmlConfigurator... Here is what I am successfully using:

log4net.config details:

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
  <File type="log4net.Util.PatternString" value="App_Data/%property{LogName}" />
  ...
</appender>

Global.asax details:

private static readonly log4net.ILog log = log4net.LogManager.GetLogger("Global.asax");
void Application_Start(object sender, EventArgs e) 
{
    // Set logfile name and application name variables
    log4net.GlobalContext.Properties["LogName"] = GetType().Assembly.GetName().Name + ".log";
    log4net.GlobalContext.Properties["ApplicationName"] = GetType().Assembly.GetName().Name;

    // Load log4net configuration
    System.IO.FileInfo logfile = new System.IO.FileInfo(Server.MapPath("log4net.config"));
    log4net.Config.XmlConfigurator.ConfigureAndWatch(logfile);

    // Record application startup
    log.Debug("Application startup");
}

Hope this helps...