I have a base class for all controllers and the logger is defined there:
public abstract class BaseService
{
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
protected ILogger Logger => logger;
}
public class ChildClass : BaseClass
{
public void DoStuff()
{
Logger.Info("Some info");
}
}
Now when I use Logger
from a child class, the log entry shows BaseService as logger. Is there a way to tell the log manager to instantiate the logger for the child class?
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
Yes, parent and child classes can have a method with the same name.
This will work because we have cast parent to child and then child to sibling. Parent parent = new Child(); //Assigning child object to parent ref. variable. parent = new Sibling(); // Assigning sibling object to parent.
Calling Parent class Method Well this can done using Python. You just have to create an object of the child class and call the function of the parent class using dot(.)
Here is how you can do it:
public abstract class BaseService
{
protected ILogger Logger => LogManager.GetLogger(this.GetType().FullName);
}
Please note that GetLogger
caches the logger internally (for each different name) so that you don't create a new logger every time the Logger
property is obtained.
The trick here is that this.GetType().FullName
will return the name of the derived type, not BaseService
.
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