Search code examples
c#configlog4netclass-library

Log4Net Error: Failed to find configuration section 'log4net' in the application's .config file


I currently use a class library to store a class that handles logging using log4net. This class is used in other projects.

I've read a lot of other questions and answers, but I haven't been able to fix it yet...

I enabled internal debugging of log4net because it would not write to a file, and this is the error I get:

log4net:ERROR Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />

These are my files: log4net.config

<log4net debug="true">
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
        <param name="File" value="Logs/log4net.log" />
        <param name="AppendToFile" value="true" />
        <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header]\r\n" />
        <param name="Footer" value="[Footer]\r\n" />
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
        </layout>
    </appender>

    <root>
        <level value="ALL" />
        <appender-ref ref="LogFileAppender" />
    </root>
</log4net>

App.config

<?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
      </configSections>

      <appSettings>
        <add key="log4net.Internal.Debug" value="true"/>
      </appSettings>

      <parameter>
        <parameterName value="@BlogId" />
        <dbType value="Int32" />
        <layout type="log4net.Layout.RawPropertyLayout">
          <key value="BlogId" />
        </layout>
      </parameter>
    </configuration>

AssemblyInfo.cs (just last line)

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Logger.cs

public class Logger : ILogger
    {
        private static ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public Logger()
        {
            XmlConfigurator.Configure();
            logger.Info("NEW LOGGER INSTANCE CREATED");
        }
}

UPDATE I fixed it by letting the class that uses my Logger.cs give its own .config file for log4net. Now log4net reads the given .config files and it works.


Solution

  • You have defined that the log4net section is in your app.config with:

      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
      </configSections>
    

    that means you should add the content of the log4net.config to the app.config file.