29

我一直在努力寻找重复项,但无论看起来多么基本,都必须问以下问题,以便一劳永逸地弄清楚!

在 64 位 W7 上的 VS28KSP1 上使用 log4net 版本 1.2.10.0 的全新控制台应用程序中,我有以下代码:-

using log4net;
using log4net.Config;

namespace ConsoleApplication1
{
    class Program
    {
        static readonly ILog _log = LogManager.GetLogger(typeof(Program));
        static void Main(string[] args)
        {
            _log.Info("Ran");
        }
    }
}

在我的app.config,我有:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Program.log" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%username] %date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>

</configuration>

这不会写任何东西,除非我添加一个属性:

[ assembly:XmlConfigurator ]

或者在 Main() 中显式初始化它:

_log.Info("This will not go to the log");
XmlConfigurator.Configure();
_log.Info("Ran");

这提出了以下问题:

  1. 我几乎可以肯定我已经看到它在某些版本的 log4net 上工作,而无需添加程序集属性或调用 Main。有人可以向我保证我不会想象吗?
  2. 有人可以指出我在文档中的哪个位置明确指出配置部分和初始化挂钩都是必需的 - 希望解释一下何时更改,如果确实如此?

我可以很容易地想象为什么这可能是政策 - 明确初始化步骤以避免意外等,只是我似乎记得情况并非总是如此......(通常我将配置放在单独的文件中,这通常会将配置部分排除在外)

4

1 回答 1

31

根据手册中的配置页面

log4net 配置可以使用程序集级属性进行配置,而不是通过编程方式指定。

XmlConfiguratorAttribute:log4net.Config.XmlConfiguratorAttribute允许XmlConfigurator使用以下属性进行配置:

  • 配置文件...
  • 配置文件扩展...

如果未指定 ConfigFile 或 ConfigFileExtension 属性,则应用程序配置文件(例如 TestApp.exe.config)将用作 log4net 配置文件。

示例用法:

// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
// This will cause log4net to look for a configuration file
// called TestApp.exe.config in the application base
// directory (i.e. the directory containing TestApp.exe)
// The config file will be watched for changes.
                        

I agree that it's a bit ambiguous, but I interpret the existence of the example usage to mean that log4net will not use the .config file without the above attribute; and the fact that they point out that you have to use one of the two properties, but do not say anything about leaving out the attribute altogether, suggests to me that the attribute (or programmatic call) is required to use app.config in the way you want.

于 2009-08-11T16:19:05.870 回答