如何让 Log4Net 使用 app.config

How to get Log4Net to use app.config

故事:我有一个包含多个程序集的 WinForms 应用程序 - MainApp 和 Utilities。我使用实用程序通过 log4net 进行日志记录。世界上一切都很好 if 我为 log4net 使用单独的配置文件(又名 log4net.config)- 没问题。

但是,IT 人员发现调整两个 .config 文件(MainApp.exe.config 和 log4net.config)具有挑战性。所以,我正在尝试将我的 log4net 配置设置添加到我的 app.config 文件中。运气不好。

我已经尝试了本论坛中发布的几种解决方案。这个似乎遇到了我得到的相同错误: log4net configuration - failed to find section

我试过将此行放入我的 Utilities:AssemblyInfo.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "MainApp.exe.config", Watch = false)]

在我引用 log4net 的实用程序模块中,我有这个:

const string TEMP_VARIABLE = "TEMP";
string tempDir = Environment.GetEnvironmentVariable( TEMP_VARIABLE );
StringBuilder userTempDirLogFile = new StringBuilder( tempDir );
userTempDirLogFile.Append( @"\" );
userTempDirLogFile.Append( Environment.MachineName );
userTempDirLogFile.Append( "_MAIN_" );
userTempDirLogFile.Append( DateTime.Now.DayOfWeek );
userTempDirLogFile.Append( ".log" );
log4net.GlobalContext.Properties["MainLogFileName"] = userTempDirLogFile.ToString();
StringBuilder utilityLogFile = ( userTempDirLogFile.Replace( "_MAIN_", "_UTILITIES_" ) );
log4net.GlobalContext.Properties["UtilityLogFileName"] = utilityLogFile.ToString();
log4net.Config.XmlConfigurator.Configure();
_mainLogger = LogManager.GetLogger( "MAIN" );

_mainLogger 收到此错误消息:

log4net:ERROR XmlConfigurator: 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" />

我在 log4net 源代码中注意到 log4net.Config.XmlConfigurator.Configure() 调用了 Assembly.GetCallingAssembly()。我已经验证 GetCallingAssembly() 确实是 MainApp。我的程序目录包含所有必需的文件。

这是我的app.config

<?xml version="1.0"?>
<configuration>
    <!-- configSections MUST be first! -->
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
    </configSections>

    <log4net>
        <appender name="MainLogFile" type="log4net.Appender.RollingFileAppender">
            <file type="log4net.Util.PatternString" value="%property{MainLogFileName}"/>
            <appendToFile value="false" />
            <maximumFileSize value="20MB" />
            <maxSizeRollBackups value="3" />
            <param name="Encoding" value="unicodeFFFE" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date{ISO8601}&#9;%property{messageId}&#9;%-5level&#9;%message%newline" />
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">
                <param name="LevelMin" value="ALL" />
                <param name="LevelMax" value="OFF" />
            </filter>
        </appender>

        <appender name="UtilityLogFile" type="log4net.Appender.RollingFileAppender">
            <file type="log4net.Util.PatternString" value="%property{UtilityLogFileName}"/>
            <appendToFile value="false" />
            <maximumFileSize value="20MB" />
            <maxSizeRollBackups value="3" />
            <param name="Encoding" value="unicodeFFFE" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date{ISO8601}&#9;%property{messageId}&#9;%-5level&#9;%message%newline" />
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">
                <param name="LevelMin" value="ALL" />
                <param name="LevelMax" value="OFF" />
            </filter>
        </appender>

        <logger name="MAIN">
            <level value="DEBUG" />
            <appender-ref ref="MainLogFile" />
        </logger>

        <logger name="UTILITY">
            <level value="DEBUG" />
            <appender-ref ref="UtilityLogFile" />
        </logger>
    </log4net>

    <startup>
        <!-- Leave sku out so that both 4.0 and 4.5 are supported -->
        <supportedRuntime version="v4.0" />
    </startup>

    <system.windows.forms jitDebugging="true" />

    <system.diagnostics>
        <trace useGlobalLock="false" />
    </system.diagnostics>

    <appSettings>
        <add key="PRINT_CALL_STACK" value="false"/>
        <add key="TRACK_PERFORMANCE" value="false"/>
        <add key="USING_TEST_MODE" value="false"/>
        <add key="WAIT_FOR_LOGON" value="0"/>
    </appSettings>

</configuration>

我想我遗漏了什么,但不知道是什么。感谢您的宝贵时间。

注意:使用VS2013和log4net 1.2.13.0。解决方案针对 .NET 4.0 full 和 x86。

程序集属性必须在 MainApp 项目中,而不是在 Utilities 项目中。

正如 documentation for assembly attributes

中所说

Therefore if you use configuration attributes you must invoke log4net to allow it to read the attributes. A simple call to LogManager.GetLogger will cause the attributes on the calling assembly to be read and processed. Therefore it is imperative to make a logging call as early as possible during the application start-up, and certainly before any external assemblies have been loaded and invoked.

如果你想把所有东西都放在你的 app.config 中,请确保你在 AssemblyInfo.cs:

中有这个
    [assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]

true or false 可以更改,如果你想动态监控或不监控配置文件的变化。

并在您的配置文件中,确保您有适当的部分。例如在我的我有:

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

  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <param name="file" value="logs/App.log"/>
      <param name="appendToFile" value="True"/>
      <param name="encoding" value="utf-8"/>
      <param name="staticLogFileName" value="False"/>
      <param name="RollingStyle" value="Size"/>
      <param name="MaxSizeRollBackups" value="1"/>
      <param name="MaxFileSize" value="10485760"/>
      <param name="threshold" value="Debug"/>
      <layout type="log4net.Layout.PatternLayout">
        <param value="%d [%t] %-5p %c{2} - %m%n" name="conversionPattern"/>
      </layout>
    </appender>

    <root>
      <level value="INFO" />
      <appender-ref ref="FileAppender" />
    </root>
  </log4net>

如果您将 log4net 配置设置放入 app.configweb.config 文件中,请将以下行放入项目 Properties 文件夹中的 AssemblyInfo.cs 文件中:

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

引自manual

// 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.