log4net argument to LogManager.GetLogger

Viewed 85872

Why do most log4net examples get the logger for a class by doing this:

private static ILog logger = 
    LogManager.GetLogger(
    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Rather than just passing typeof(MyClass):

private static ILog logger = LogManager.GetLogger(typeof(MyClass));

Is there any other reason for doing this, beside the fact that the first option does not require you to type a specific class name?

6 Answers

I think you've got the reason. I do it that way so I don't have to worry about the class name and can just copy and paste boiler plate code in a new class.

For the official answer, see: How do I get the fully-qualified name of a class in a static block? at the log4net faq

As you say - its convenient as you can create a logger in a method without knowing the name of the class (trivial I know) but allows you to cut and paste methods between classes without having to rename the call.

It also makes it easier to create Codesmith templates for code generation purposes.

The following portable solution worked for me in .NET Core 6:

private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType);
Related