Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parent class logger in child class

Tags:

c#

nlog

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?

like image 613
Andrey Avatar asked Jan 31 '16 20:01

Andrey


People also ask

Can child classes access parent methods?

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.

Can child class have same method name as parent class?

Yes, parent and child classes can have a method with the same name.

Can we cast parent to child in C#?

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.

Can the parent class use methods from the child class python?

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(.)


1 Answers

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.

like image 198
Yacoub Massad Avatar answered Oct 11 '22 15:10

Yacoub Massad