为什么配置文件中无法识别 log4net?

2023-12-25

我使用 C# 编写了一个测试控制台应用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using log4net;
using log4net.Config;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace Log4Net_Test
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));

        static void Main(string[] args)
        {    
            log.Info("Entering application");    
            log.Debug("Debug message");    
            log.Info("Leaving application");
        }
    }
}

My App.config文件看起来像这样:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
  </appSettings>
  <log4net>
    <!-- A1 is set to be a ConsoleAppender -->
    <appender name="A1" type="log4net.Appender.FileAppender">
      <file value="logfile.txt" />
      <appendToFile value="false" />

      <!-- A1 uses PatternLayout -->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />
      </layout>
    </appender>

    <!-- Set root logger level to DEBUG and its only appender to A1 -->
    <root>
      <level value="DEBUG" />
      <appender-ref ref="A1" />
    </root>
  </log4net>
</configuration>

执行测试程序最终会出现以下错误消息:

log4net:ERROR Exception while reading ConfigurationSettings. Check your .config
file is well formed XML.
System.Configuration.ConfigurationErrorsException: Configuration system failed t
o initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognize
d configuration section log4net. 

我的配置文件有什么问题吗?

更新1: The configSections´ part was missing, as pointed out in the accepted answer. But I also had to remove thestartupsection, otherwise the same error appeared. I do not know why the启动部分也导致了问题。也许更有经验的人可以告诉并写评论。


你需要添加log4net也在分区块中

<configSections>

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

</configSections>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么配置文件中无法识别 log4net? 的相关文章

随机推荐