Best way to dynamically set an appender file path

You are doing this the hard way! Define your log4net config as XML in your application’s configuration file and use %property{} to advantage:

<appender name="YourAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
  ....
</appender>

This is dynamic — you just have to set the log4net property “LogNamebefore you initialize log4net. Thus, in your code any time before you configure log4net, set the desired value of this property:

string LogName = GetType().Assembly.GetName().Name + ".log";
log4net.GlobalContext.Properties["LogName"] = LogName;

Of course, you may use any property name. I’ve chosen “LogName” for a simple example, but you can have one per application if you want, as long as your code knows what the correct property name is and what the correct value should be.

Leave a Comment