Get log4net log file in C#

Solution is quite easy in your situation; just use this code:

var rootAppender = ((Hierarchy)LogManager.GetRepository())
                                         .Root.Appenders.OfType<FileAppender>()
                                         .FirstOrDefault();

string filename = rootAppender != null ? rootAppender.File : string.Empty;

When having multiple file appenders, you might want to get them by name. Also to make sure to get the appender even if it is not referenced by the root node, the following code helps:

public static string GetLogFileName(string name)
{
     var rootAppender = LogManager.GetRepository()
                                  .GetAppenders()
                                  .OfType<FileAppender>()
                                  .FirstOrDefault(fa => fa.Name == name);

     return rootAppender != null ? rootAppender.File : string.Empty;
}

Since I already had a logger defined in the class I just used it. One thing to be aware of is that there may be more than one appender and often the first one is the console (which doesn't have a file). Here is my solution for what its worth.

using log4net;
using log4net.Appender;
using log4net.Repository;

namespace MyNameSpace {
public class MyClass {

    private static readonly ILog logger = LogManager.GetLogger(typeof(MyClass));

    public String GetLogFileName() {

        String filename = null;

        IAppender[] appenders = logger.Logger.Repository.GetAppenders();
        // Check each appender this logger has
        foreach (IAppender appender in appenders) {
            Type t = appender.GetType();
            // Get the file name from the first FileAppender found and return
            if (t.Equals(typeof(FileAppender)) || t.Equals(typeof(RollingFileAppender))) {
                filename = ((FileAppender)appender).File;
                break;
            }
        }
        return filename;
    }
}

}

Tags:

C#

.Net

Log4Net