log4net在Windows事件查看器中无法记录日志。

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();
    }
}

它没有记录,什么都没有发生,为什么?
谢谢。
3个回答

10
你需要调用configure函数。
更改:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)] 

To

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

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

1
我正在使用管理员帐户。我尝试以管理员身份运行我的应用程序,但是出现了相同的问题。我尝试以管理员身份重新启动Visual Studio,但结果相同。 - Nico
你有配置语句吗? - Nix
我使用了默认的App.config,尝试将此代码放入AssemblyInfo.cs中,但结果相同。[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)] - Nico

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();
    }
}

0
在您的应用程序开头调用XmlConfigurator.Configure()。
您还需要授予运行应用程序的用户将数据放入事件日志的权限。
一个好的方法是使用管理员模式的PowerShell。
  New-EventLog EventLogName -source ApplicationName

此外,将这两个参数添加到appender中

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

敬礼,


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接