How can I log to Special Folders with log4net?

user9969 picture user9969 · Dec 21, 2009 · Viewed 10.9k times · Source

How can I log to special folders (e.g. %APPDATA%) using the app.config file?

I can do it programmatically, but I need to be able to use the app.config file for configuration. I have seen a post of using %envFolderPath.It is not available in the latest released version, but only in their latest code.

Below is the code that I setting the log to special folders programmatically.

public void ExampleLog
{
    XmlConfigurator.Configure();

    var fileName = GetFileName();
    var appender = new log4net.Appender.RollingFileAppender
    {
        Layout = new log4net.Layout.PatternLayout("%d - %m%n"),
        File = fileName,
        MaxSizeRollBackups = 10,
        MaximumFileSize = "100MB",
        AppendToFile = true,
        Threshold = Level.Debug
    };

    appender.ActivateOptions();
    BasicConfigurator.Configure(appender);
}

private static string GetFileName()
{
    const string subPath = "MySubFolder";
    var path = String.Format(@"{0}\{1}", Environment.GetFolderPath  (Environment.SpecialFolder.CommonApplicationData), subPath);
    const string logName = "Log.txt";
    return Path.Combine(path, logName);
}

Answer

Bryan Batchelder picture Bryan Batchelder · Dec 21, 2009

Pretty sure the syntax for this is available in the current release.

<file type="log4net.Util.PatternString" value="%env{APPDATA}\\MyApp\\Log.txt" />

If you need something more, you can look into option of subclassing the PatternString class, as described here: Log4Net can’t find %username property when I name the file in my appender