Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling log levels in log4net

I'm writing a simple test project to experiment with log4net and I've hit a wall right off the bat. No matter what I do in my config file, the my logger is initialized with all "IsXXXXEnabled" flags set to false. Here is my very simple app.config:

  <log4netgroup>
    <log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
        <param name="LogName" value="Application" />
        <param name="ApplicationName" value="HelloProgram" />
        <threshold value="DEBUG"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger - %newline%message" />
        </layout>
      </appender>

      <root>
        <level value="DEBUG" />
        <appender-ref ref="EventLogAppender" />
      </root>
      <logger name="HelloLogger">
        <level value="DEBUG" />
        <appender-ref ref="EventLogAppender" />
      </logger>
    </log4net>
  </log4netgroup>

Here is the trivial test in Main:

    ILog Log = LogManager.GetLogger("HelloLogger");

    if(Log.IsErrorEnabled)
        Console.WriteLine("The logger is working!");
    else
        Console.WriteLine("Nope");

The output is "Nope". I tried switching the threshold and level values to "ALL", but nothing changed. This seems so simple, what am I missing to enable everything? Thanks

like image 500
BradV Avatar asked Mar 09 '11 23:03

BradV


1 Answers

You should configure the root logger:

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

Any non-root loggers (the ones you create with <logger name="...">) apply only to classes whose namespace-qualified name has the logger name as a prefix. So the logger you have created will only apply to a classes that is outside of a namespace and whose name is HelloLogger, or to any classes residing in a namespace called HelloLogger (and possibly within namespaces nested inside that one). (When I say that a logger "applies to" a class X, I mean that that that's the logger you will get when you call LogManager.GetLogger(typeof(X)).)

Edit: You also need to call log4net.Config.XmlConfigurator.Configure(); in order to get log4net to read App.config. Also, delete the outermost <log4netgroup> element and rename the config section name: <section name="log4net" .../>.

like image 189
Aasmund Eldhuset Avatar answered Oct 14 '22 03:10

Aasmund Eldhuset