简体   繁体   English

如何使Log4Net使用app.config

[英]How to get Log4Net to use app.config

The Story: I have a WinForms application with multiple assemblies - MainApp and Utilities. 故事:我有一个带有多个程序集的WinForms应用程序-MainApp和Utilities。 I use Utilities for my logging via log4net. 我使用实用程序通过log4net进行日志记录。 All is fine with the world if I use a separate config file for log4net (aka log4net.config) - no issues. 如果我将单独的配置文件用于log4net(aka log4net.config), 那么一切都很好-没问题。

However, IT staff finds it challenging to tweak two .config files (MainApp.exe.config and log4net.config). 但是,IT人员发现调整两个.config文件(MainApp.exe.config和log4net.config)具有挑战性。 So, I'm trying to add my log4net config settings into my app.config file. 因此,我试图将我的log4net配置设置添加到我的app.config文件中。 Not having any luck. 没有运气。

I've tried several solutions posted in this forum. 我已经尝试过在此论坛中发布的几种解决方案。 This one seemed to experience the same error I get: log4net configuration - failed to find section 这似乎遇到了我遇到的相同错误: log4net配置-找不到部分

I've tried putting this line in my Utilities:AssemblyInfo.cs 我尝试将这一行放在我的Utilities:AssemblyInfo.cs中

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

In my Utilities module where log4net is referenced, I have this: 在我的引用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 gets this error message: _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" />

I noticed in log4net source code that log4net.Config.XmlConfigurator.Configure() calls Assembly.GetCallingAssembly(). 我在log4net源代码中注意到,log4net.Config.XmlConfigurator.Configure()调用Assembly.GetCallingAssembly()。 I've verified that GetCallingAssembly() is indeed MainApp. 我已经确认GetCallingAssembly()确实是MainApp。 My program directory contains all necessary files. 我的程序目录包含所有必需的文件。

This is my app.config 这是我的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>

I figure I'm missing something, but no clue as to what. 我想我丢失了一些东西,但是什么都不知道。 Thanks for your time. 谢谢你的时间。

Note: using VS2013 and log4net 1.2.13.0. 注意:使用VS2013和log4net 1.2.13.0。 Solution targets .NET 4.0 full and x86. 解决方案针对.NET 4.0完整版和x86。

The assembly attribute must be in the MainApp project, not in the Utilities project. Assembly属性必须在MainApp项目中,而不能在Utilities项目中。

As it says in the documentation for assembly attributes 如其在装配属性文档中所述

Therefore if you use configuration attributes you must invoke log4net to allow it to read the attributes. 因此,如果使用配置属性,则必须调用log4net以允许它读取属性。 A simple call to LogManager.GetLogger will cause the attributes on the calling assembly to be read and processed. 对LogManager.GetLogger的简单调用将导致调用程序集上的属性被读取和处理。 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 . 因此,必须在应用程序启动期间尽早并且一定要在加载和调用任何外部程序集之前进行日志记录调用

If you want to put everything in your app.config, make sure you have this in the AssemblyInfo.cs: 如果要将所有内容放入app.config中,请确保在AssemblyInfo.cs中包含以下内容:

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

true or false can be changed if you want to monitor dynamically or not the config file for changes. 如果要动态监视配置文件或不监视更改,则可以更改true或false

and in your config file, make sure you have the appropriate sections. 并在配置文件中,确保您具有适当的部分。 For example in mine I have: 例如在我的我有:

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

If you put log4net configuration setting into the app.config or the web.config file the put into the AssemblyInfo.cs file in the Properties folder of your project the following line: 如果将log4net配置设置放入app.configweb.config文件中,则将以下行放入项目的Properties文件夹中的AssemblyInfo.cs文件中:

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

Quote from the 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM