ConfigurationErrorsException when adding log4net configuration to the app.config

955 views Asked by At

I am testing log4net; it is really working well. But when I add the log4net configuration to the app.config for my application, it throws a ConfigurationErrorsException. here is my app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configsections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,     log4net" />
  </configsections>
  <log4net>
    <!-- Set root logger level to DEBUG and its only appender to A1 -->
    <root>
      <level value="ERROR" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <file value="c:\log\" />
      <datePattern value="yyyy-MM-dd'_siteAgent.log'" />
      <staticLogFileName value="false" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] -     %message%newline" />
      </layout>
    </appender>
  </log4net>
  <appSettings>
    <add key ="test" value="tttt"/>
  </appSettings>
</configuration>    

and code below

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LogTest
{
    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);  

        static void Main(string[] args)
        {
            string t = ConfigurationManager.AppSettings["test"].ToString();
            log.Info(t);
            log.Info("Form Init End");
            log.Debug("debug Form Init End");
            log.Error("error");
            log.Warn("warn");
            log.Fatal("fatal");
                log.Info("Form Init End"); 
            }
    }
}

The exception occurs at the following line

string t = ConfigurationManager.AppSettings["test"].ToString();
1

There are 1 answers

2
samy On

Your <configSections> node must be the first child of the <configuration> node in the web.config, else the configuration file is invalid

If the configSections element is in a configuration file, the configSections element must be the first child element of the configuration element.