Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare log4net logger once per class or in base class?

Tags:

It seems cleaner to declare a logger and call LogManager.GetLogger in a base class so that everyone who is inheriting can use it. However, on log4net site and other blogs like in this blog post it states that it is better to declare one logger per class because:

You can use loggers this way to isolate logging concerns across your objects, and I wholly recommend you do so. This will enable you to throttle and direct log output from individual loggers using log4net's hierarchical configuration mechanism.

Does this mean if I put it in base class, it will make that logger a bottleneck?

If so, are there other solutions or do I just have to create a logger per class?

like image 913
dev.e.loper Avatar asked Jan 30 '12 22:01

dev.e.loper


People also ask

Where to put log4net config file?

You can configure the log4net. config file to create log files. The file is located in the webroot\App_data directory of the installation.

How to implement log4net in asp net c#?

Add a class Log. cs in the Utilities folder. Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers. Here, you need to create Debug(), Error(), Info(), Warn(), Fatal() methods which will call respective methods from Log4 net.

Why we use log4net?

log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary.


1 Answers

The post is not specifically telling you to use a different logger in each derived class, but instead a different logger per class type in general. You can, but don't have to use a new logger instance in each derived class.

One way to look at it is that it might be confusing to have two separate loggers instantiated at the same time (because the base one will still exist), especially if you hide the base one using the same logger name. Your base class methods (not overridden) will still reference the base static logger, and overridden ones will use a different one.

Also, the article instantiates the logger like this:

static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType ); 

while a slightly simpler way might be to use:

static readonly ILog Log = LogManager.GetLogger(typeof(YourClass)); 

First of all, it's marked readonly, meaning you won't be able to change the field accidentally, once initialized. And using the type will work the same way as with reflection, but slightly faster (resolved at compile time). Visual Studio will also update the class name automatically if you choose to rename it (which it wouldn't it you used the string overload).

like image 72
Groo Avatar answered Sep 18 '22 15:09

Groo