如何让Log4Net使用app.config

时间:2015-06-25 15:17:43

标签: c# log4net app-config

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

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

我已尝试在此论坛中发布了多个解决方案。这个似乎遇到了同样的错误: log4net configuration - failed to find section

我已尝试将此行放入我的实用程序:AssemblyInfo.cs

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

在我的Utilities模块中引用了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。

3 个答案:

答案 0 :(得分:2)

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

正如documentation for assembly attributes

中所述
  

因此,如果使用配置属性,则必须调用log4net   允许它读取属性。一个简单的电话   LogManager.GetLogger将导致调用程序集上的属性   被阅读和处理。 因此必须进行日志记录   在应用程序启动期间尽早调用,以及   当然,在加载和调用任何外部程序集之前

答案 1 :(得分:2)

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

    [assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
如果您想动态监控配置文件以进行更改,可以更改

true或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>

答案 2 :(得分:0)

如果将log4net配置设置放入项目的app.config文件夹中的web.configAssemblyInfo.cs文件中,则将其放入Properties文件中的以下行: / p>

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