Just started using log4net and trying to get my head around the config and logger hierarchy. Is this hierarchy based on namespaces or class and method/function hierarchy?
Lets say I have the following class structure…
public class MyClass
{
private static readonly ILog log = LogManager.GetLogger(typeof(MyClass));
public void Method1()
{
log4net.info("message");
}
public void Method2()
{
log4net.info("message");
}
}
Is it possible to setup in the config for the log4net.info in method1 to use one appender and the log4net.info in method 2 to use another appender, even if they are off the same type e.g. SmtpAppender. If so how would the config look. here is my first attempt at it.
<appender name="SMTP1" type="log4net.Appender.SMTPAppender">
</appender>
<appender name="SMTP2" type="log4net.Appender.SMTPAppender">
</appender>
<logger name="MyClass.Method1">
<level value="INFO" />
<appender-ref ref="SMTP1" />
</logger>
<logger name="MyClass.Method2">
<level value="INFO" />
<appender-ref ref="SMTP2" />
</logger>
The hierarchy is based on “names”. What does that mean?
Well, you can specify a namespace in your logger xml (eg.
Foo.Bar) and then fetch a logger for a class in that namespace using theGetLoggermethod which takes aType. Any “sub” namespace underFoo.Barwill inheritFoo.Bar‘s logger config.Alternatively, you can fetch a logger based on any old string using the
GetLoggermethod which takes astring.You can fetch loggers a couple of different ways. Most notably, by
Typeor bystring.Being able to fetch by
string, you really can name your loggers anything and fetch them using anything. What you currently have won’t work becauselog4netwill fetch the logger based on the class… so you will be using the same logger for both methods.For what you want to do you have to create two loggers:
Here is the same logger xml file:
I’m not too experienced with .Net, so maybe someone can find a better/more robust way to get the loggers for each method using some ninja Reflection, but that is the best I could do.