I want log4net to write log files (using RollingFileAppender) to a subfolder of the common application data folder (e.g. C:\Documents and Settings\All Users\Application Data\Company\Product\Logs).
However, on Win XP, there is no environment variable that specifies this folder. We have %ALLUSERSPROFILE%
, we have %APPDATA%
, but there is nothing like %ALLUSERSAPPDATA%
.
Programatically, I could use Environment.SpecialFolder.CommonApplicationData
, but I need to put it in the log4net config, something like this:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="%ALLUSERSAPPDATA%\Company\Product\Logs\error.log" />
</appender>
OK, we could define this in our setup, but maybe someone comes up with a better idea?
Here's the full code from the log4net mailing list that pilif linked to:
Basically the method is to implement a custom pattern converter for the log4net config file.
First add this class to your project:
Then set up the File parameter of your FileAppender as follows:
Basically the
%folder
tells it to look at the converter calledfolder
which points it to the SpecialFolderPatternConverter class. It then callsConvert
on that class, passing in the CommonApplicationData (or whatever) enum value.Apparently in the next release of log4net (1.2.11) there will be a simpler method, as described here.
We just use this:
It works great.
This line can simply be inserted into your current appender configuration:
This posting on the log4net mailinglist explains how you can define your own path replacement variables.
Complete and working solution - content of my Log4net.config file. In actual version of Log4Net there is no need for writing own pattern converter anymore
In the current log4net version (2.0.8.0) you could simply use
<file value="${ProgramData}\myFolder\LogFiles\" />
forC:\ProgramData
${LocalAppData}
forC:\Users\user\AppData\Local\
and
${AppData}
forC:\Users\user\AppData\Roaming\
Now (in 2018 FEB) as per log4net version 2.0.8.0.
You can use without any converter to get Environment Variables as follows.
Refer: log4net.Util.PatternString class documentation for more details.