Why hardcode class name when using a logger in .NET?

I have seen many people write this lines of code.

       var logger = log4net.LogManager.GetLogger(typeof(ServiceRequestController));

But, why should we hard-code the controller name.

It is better to simply write,

       var logger = log4net.LogManager.GetLogger(this.GetType());

A large majority of people are writing in the first way (they hard-code the class name). But I wonder why?

Simply one could use the latter version right ?

Or I am over-seeing something here ?

Upvotes: 3

Views: 1577

Answers (3)

samy
samy

Reputation: 14962

It really depends where in the class you declare your logger; most examples make use of a static logger per class, with a logger name pulled from reflecting the containing type.

class MyClass
{
    private static log4net.ILog Log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );
    public static void DoSomething()
    {
        Log.Info( "Doing something" );
    }
}

Of course in this case there is no instance of the MyClass object to dereference to get its type, so typeof is used instead.

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

I think its matter of taste and coding guidelines of your team. First option has better readability for me. Second one is more compact, but more confusing and as already mentioned type is defined at runtime, which can give a little performance hit. What is real performance hit in your case is local loggers. I recommend to use single static logger instance per type. Also for even more compact logger creation you can use current stack frame to get declaring type, like it is implemented in NLog:

private static Logger Logger = LogManager.GetCurrentClassLogger();

Upvotes: 3

PetarPenev
PetarPenev

Reputation: 339

Typeof provides you with the type at compilation time, while this.GetType - at execution time. Moreover, the 'hardcoded' variant is often more readable (you do not need to make the mental trip thinking about 'OK, so what does this signifies in this context?'

Upvotes: 6

Related Questions