6

I would like to log in the Windows Event Viewer using log4net.
I created a Console Application (.NET Framework 4), I added the reference log4net.dll, I put the following code in my 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>

And I put the following code :

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

It doesn't log, nothing happens, why?

Thanks

Philipp M
  • 1,877
  • 7
  • 27
  • 38
Nico
  • 575
  • 3
  • 8
  • 19

3 Answers3

10

You need to call configure.

Change:

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

To

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

When you specify ConfigFile = "App.config" its going to look for App.config but your filename would be [FileName].Config.

Nix
  • 57,072
  • 29
  • 149
  • 198
  • 1
    I'm under an administrator account. I tried to run my app as admin, same problem. I tried to reboot visual studio as admin, same result. – Nico Jun 29 '11 at 15:39
  • Do you have a configure statement ? – Nix Jun 29 '11 at 15:39
  • like this ? [assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)] i used the default App.config, i tried to put this in AssemblyInfo.cs, same result. – Nico Jun 29 '11 at 15:43
5

You need to call XmlConfigurator.Configure from the log4net library to initialize it. (see below)

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();
    }
}
Mike Marshall
  • 7,788
  • 4
  • 39
  • 63
0

Call XmlConfigurator.Configure() at the begining of your App.

You also need to grant the user running the application rights to put data in the eventlog.

A good way to do this is with powershell, admin mode

  New-EventLog EventLogName -source ApplicationName

Also, add this two parameters into the appender

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

Regards,

JavierCaruso
  • 305
  • 1
  • 4
  • 13