Folks, this post is partly a reminder to myself and anyone else who goes
through the searching and suffering of how to configure log4net at runtime.
Log4net is well featured, but web is fully of "kiddy" examples that only
use xml config files, and any serious app is going to have to change things
at runtime. The classic problem for me was how to change the path of the
rolling log file.

One guy says for web apps to put file="~/App_Data/foo.log". I didn't try
this but I found that %environment%  variables don't work. I still haven't
found a clear definition of just what "variables" or special tokens are
recognised in xml elements.

Some people suggest that you create the appender at runtime, but the code
is ugly as sin. Others tell you to find the appender in the collection,
change the property value and ActivateOptions(), which works, but it leaves
a zero length file of the original file name. Someone else tried putting
file="%property{myname}" but it didn't replace the global property value.
This last attempt was nearly there and I finally found someone's tweak to
make it work. Here's the answer:

<appender name="Roller" ...>
    <file type="log4net.Util.PatternString"value="%property{rollpath}\zroll.log"
/>
    :
</appender>

string rollpath = Path.Combine(... whatever you need...);
log4net.GlobalContext.Properties["rollpath"] = rollpath;
log4net.Config.XmlConfigurator.Configure();

The subtle fix is the bit I highlighted and it's damn easy to miss. Lord
knows how many other obscure "fixes" I'll be looking for.

Greg K

Reply via email to