将log4net配置添加到app.config时出现ConfigurationErrorsException

时间:2014-11-12 11:03:23

标签: logging log4net appsettings

我正在测试log4net;它真的很好用。但是当我将log4net配置添加到我的应用程序的app.config时,它会抛出ConfigurationErrorsException。这是我的app.config文件:

<?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>    

和以下代码

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"); 
            }
    }
}

异常发生在以下行

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

1 个答案:

答案 0 :(得分:1)

您的<configSections>节点必须是web.config中<configuration>节点的the first child,否则配置文件无效

  

如果configSections元素在配置文件中,则   configSections元素必须是第一个子元素   配置元素。