12

以下配置没有任何反应。

应用程序配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <log4net>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

Form1.cs(示例)

public partial class Form1 : Form
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public Form1()
    {
        InitializeComponent();

        log.Fatal("Test!");
    }
}
4

3 回答 3

14

您缺少根配置,因此您需要类似的东西

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
      <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <startup>
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
  <log4net debug="true">
      <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <applicationName value="MyApp" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
      </appender>


      <root>
        <level value="All" />
        <appender-ref ref="EventLogAppender" />
      </root>


  </log4net>
</configuration>

另请注意,如果您的程序名为 app.exe,那么您需要一个名为 app.exe 的事件日志源。如果这不存在,那么 Log4net 将尝试创建它,但这需要管理员权限,因此您可能需要以管理员身份至少运行一次程序才能创建此事件源。为避免这种情况,通常会在安装过程中创建事件源,该过程已经以管理员身份运行。

于 2013-02-26T18:09:32.587 回答
6

You should add:

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

in the AssemblyInfo.cs of your project. This will initialize the logger. And put the log4net into a file named log4net.config.

于 2013-02-26T12:06:25.957 回答
0

确保您授予用户的写入权限:

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\EventLog\MyApp

如果您想添加更多记录器,则必须遵循此命名法:

<root name="EventLog">
  <level value="ALL"/>
  <appender-ref ref="FirstLog"/>
</root>

<logger name="FileLogger" additivity="false">
  <level value="ALL" />
  <appender-ref ref="Second_Log" />
</logger>

祝你好运。

于 2016-06-24T00:26:26.533 回答