Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 766
now he who must not be named. Avatar asked May 29 '26 21:05

now he who must not be named.


2 Answers

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?'

like image 167
PetarPenev Avatar answered May 31 '26 12:05

PetarPenev


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();
like image 23
Sergey Berezovskiy Avatar answered May 31 '26 13:05

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!