Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different appenders per namespace

Tags:

log4net

I'm trying to set up a common logging library which determines the ILog instance based on the current stack and what is the best instance of ILog to use.

I've got my config set up like this:

<log4net>
  <!-- appenders omitted -->
  <root></root>

  <logger name="MyAssembly.MyNamespace">
    <level value="WARN" />
    <!-- appender list -->
  </logger>
</log4net>

And I have a class like this:

namespace MyAssembly.MyNamespace.SubNamespace {
  public class MyClass { ... } 
}

When I try and get an instance of ILog I pass in the type (var log = LogManager.GetLogger(typeof(MyClass)).Namespace);) and I want it to detect that there isn't any logger configured, so it will then go up one level in the namespace tree (to MyAssembly.MyNamespace) and then see if it is configured at that point.

The problem is that the ILog returned for MyAssembly.MyNamespace.SubNamespace is configured for WARN events (and above), essentially what I configured for it's parent. Log4net seems to be returning the ILog when the required name contains a defined name, rather than when it equals the name.

How do I get Log4net to only return a valid logger when the name is the same as one defined in the config?

like image 924
Aaron Powell Avatar asked Jul 23 '09 00:07

Aaron Powell


People also ask

What are log4net Appenders?

For log4net to know where to store your log messages, you add one or more appenders to your configuration. An appender is a C# class that can transform a log message, including its properties, and persist it somewhere. Examples of appenders are the console, a file, a database, an API call, elmah.io, etc.


1 Answers

log4net treats loggers as existing in a hierarchy based on their names, so the logger with name MyAssembly.MyNamespace.SubNamespace is a child of the logger with name MyAssembly.MyNamespace.

If no level (WARN etc.) is specified for a logger, the system traverses the logger hierarchy until it finds a logger with a configured level - and that becomes the effective level for that logger.

In your case, the child logger has no level specified, so it inherits the level of its parent - WARN. If you specify

<logger name="MyAssembly.MyNamespace.SubNamespace">
    <level value="DEBUG" /> <!-- or whatever -->
    <!-- no need to specify appenders, will use parent's -->
</logger>

then you will get DEBUG output from the child logger (sent to the appenders configured for the parent).

like image 101
Vinay Sajip Avatar answered Sep 22 '22 15:09

Vinay Sajip