I needed to be able to change the file log4net was logging
on programmatically, on the same time I wanted to use the other configuration
options available in the config file.
After several different approaches I ended up with writing a
method like the one listed below:
static bool ChangeLogFileName(string
AppenderName, string NewFilename)
{
log4net.Repository.ILoggerRepository RootRep;
RootRep = log4net.LogManager.GetRepository();
foreach
(log4net.Appender.IAppender iApp in RootRep.GetAppenders())
{
if (iApp.Name.CompareTo(AppenderName) == 0
&& iApp is
log4net.Appender.FileAppender)
{
log4net.Appender.FileAppender
fApp = (log4net.Appender.FileAppender)iApp;
fApp.File = NewFilename;
fApp.ActivateOptions();
return
true; // Appender found and name changed to NewFilename
}
}
return false; // appender not
found
}
The method basically search through all appenders to find
the appender named in the input parameter. When an appender with the right name
is found, it check if the appender is a FileAppender (or to be more precise,
that the object found, implement the IFileAppender interface).
I anyone know a more efficient way to find a named appender,
I would very much like to know about it.
I found out that using a standard configuration section in
the config file failed if the filename was missing,
and if a filename was stated that file would be created during the normal
configuration (log4net.Config.XmlConfigurator.Configure()), therefore
I ended up using the nul device as the filename. My config section is listed below:
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="nul"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
Since the RollingFileAppender inherits the FileAppender, the
same method will also work with the RollingFileAppender.
Using the nul device, causes the RollingFileAppender to issue some internal error messages
during configuration (you will be able to see they if you turn on internal
log4net debug).
A small sidenote on the nul device. The nul device or the
“nul” filename has been around in Windows and Dos since the beginning of time,
at least since Dos 2.0. I believe it is inherited from the unix operating
system. If you try to write to a file named nul, the content you write to the
file will simply disappear. You can try it out with Notepad, save a file on
c:\nul.txt, you will be warned that the file already exists, but you will be
able to save to it. But you will never be able to retrieve anything (WROM Write
only memory).