Log4Net 错误:无法在应用程序的 .config 文件中找到配置部分“log4net”

Mas*_*son 4 c# log4net class-library config

我目前使用一个类库来存储一个使用 log4net 处理日志记录的类。此类用于其他项目。

我已经阅读了很多其他问题和答案,但我还没有解决它......

我启用了 log4net 的内部调试,因为它不会写入文件,这是我得到的错误:

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" />
Run Code Online (Sandbox Code Playgroud)

这些是我的文件: 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>
Run Code Online (Sandbox Code Playgroud)

应用配置

<?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>
Run Code Online (Sandbox Code Playgroud)

AssemblyInfo.cs(就在最后一行)

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Run Code Online (Sandbox Code Playgroud)

记录器

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");
        }
}
Run Code Online (Sandbox Code Playgroud)

更新 我通过让使用我的 Logger.cs 的类为 log4net 提供自己的 .config 文件来修复它。现在 log4net 读取给定的 .config 文件并且它可以工作。

Pet*_*ter 8

你已经定义了 log4net 部分在你的 app.config 中:

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
Run Code Online (Sandbox Code Playgroud)

这意味着您应该将 log4net.config 的内容添加到 app.config 文件中。