Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log to Special Folders with log4net?

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);
}
like image 510
user9969 Avatar asked Dec 21 '09 21:12

user9969


2 Answers

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

like image 122
Bryan Batchelder Avatar answered Oct 08 '22 22:10

Bryan Batchelder


Check out the RollingFileAppender configuration sample on the log4net docs (for all the other parameters).

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="log.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="100KB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.SimpleLayout" />
    </layout>
</appender>

I've referenced environment variables (including special folders) with the basic log4net variable format ${NAME}. And the file tag doesn't need to have the PatternLayout specified, it's implied.

<file value="${APPDATA}\log.txt" />
like image 35
Anthony Mastrean Avatar answered Oct 09 '22 00:10

Anthony Mastrean