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?
You can configure the log4net. config file to create log files. The file is located in the webroot\App_data directory of the installation.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With