6

我想使用 log4net 登录 Windows 事件查看器。
我创建了一个控制台应用程序(.NET Framework 4),我添加了参考 log4net.dll,我将以下代码放在我的 App.config 中:

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

<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>
<root>
  <level value="ALL"/>
  <appender-ref ref="EventLogAppender"/>
</root>
</log4net>

<startup><supportedRuntime version="v2.0.50727"/></startup>
</configuration>

我输入了以下代码:

class Program
{
    static void Main(string[] args)
    {
        log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
        log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));

        Console.Read();
    }
}

它没有记录,没有任何反应,为什么?

谢谢

4

3 回答 3

10

您需要调用configure

改变:

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

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

当您指定ConfigFile = "App.config"它要查找 App.config 但您的文件名将是[FileName].Config.

于 2011-06-29T15:35:25.887 回答
5

您需要从 log4net 库中调用XmlConfigurator.Configure来对其进行初始化。(见下文)

class Program
{
    static void Main(string[] args)
    {
        // you need this
        XmlConfigurator.Configure();
        log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
        log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));

        Console.Read();
    }
}
于 2011-06-29T15:36:47.760 回答
0

在您的应用程序开始时调用 XmlConfigurator.Configure()。

您还需要授予运行应用程序的用户将数据放入事件日志的权限。

一个很好的方法是使用 powershell,管理员模式

  New-EventLog EventLogName -source ApplicationName

另外,将这两个参数添加到附加程序中

  <param name="LogName" value="EventLogName " />
  <param name="ApplicationName" value="ApplicationName" />

问候,

于 2013-05-13T16:16:51.220 回答