log4netappdomainappdomainsetup

Passing log4net ConfigurationFile to a new AppDomain


What I need to do is get hold of the the :

<param name="File" value=".\MyExe.exe.log"/>

value but when I try to access the appender using the following :-

var rootAppender = ((Hierarchy)LogManager.GetRepository())
    .Root.Appenders.OfType<RollingFileAppender>()
    .FirstOrDefault();
var myFilePath = rootAppender != null ? rootAppender.File : string.Empty;

I find all I get is null. So how do I access my path?

This is my log4net config section :-

<log4net threshold="All">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value=".\MyExe.exe.log"/>
      <param name="AppendToFile" value="true"/>
      <param name="ImmediateFlush" value="true"/>
      <param name="RollingStyle" value="size"/>
      <param name="MaxSizeRollBackups" value="5"/>
      <param name="MaximumFileSize" value="1MB"/>

      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
      </layout>

      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    </appender>

    <logger name="MYLOGGER">
      <level value="All"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </logger>

  </log4net>

Thanks


Solution

  • The reason you can't find the file name is that you are querying the root logger - but you don't have a root logger defined in your config, and the default root does not have any appenders linked to it.

    You would need to run this code instead which uses your defined logger to get the filename:

    var loggerAppender = LogManager.GetLogger("MYLOGGER").Logger.Repository
                                   .GetAppenders()
                                   .OfType<RollingFileAppender>()
                                   .FirstOrDefault();
    
    var myFilePath = loggerAppender != null ? loggerAppender.File : string.Empty;