使用 xml 文件配置 log4net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1321261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:11:33  来源:igfitidea点击:

Configuring log4net with xml file

.netlogginglog4net

提问by Sebastian Müller

I tried to configure log4net for logging everything to the console output. I have a config file named Log4Net.config

我尝试配置 log4net 以将所有内容记录到控制台输出。我有一个名为的配置文件Log4Net.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
</configuration>

and I have my main class (just a testing case)

我有我的主课(只是一个测试用例)

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

        static void Main(string[] args) {
            log.Info("Info");
            log.Error("Error");
            Console.ReadKey();
        }
    }
}

I added these lines to the AssemblyInfo.cs

我将这些行添加到 AssemblyInfo.cs

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

But now nothing is logged, can someone explain this?

但是现在什么都没有记录,有人可以解释一下吗?

回答by Peter Lillevold

When you have log4net config in a separate config file you should not include the configuration and configSections elements. log4net should be the top level element after the xml declartion.

当您在单独的配置文件中有 log4net 配置时,您不应包含 configuration 和 configSections 元素。log4net 应该是 xml 声明之后的顶级元素。

回答by nithinmohantk

Try this custom configuration through code. Worked for me and tested in multiple apps..

通过代码试试这个自定义配置。对我来说有效并在多个应用程序中进行了测试..

string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "\Config\Log4Net.config");
    FileInfo finfo = new FileInfo(logFilePath);
   log4net.Config.XmlConfigurator.ConfigureAndWatch(finfo); 

I understand it's a very late reply. But will be useful for some right.

我知道这是一个很晚的答复。但对某些权利会有用。