Nlog: GetCurrentClassLogger in base class wrong Class logger

Created on 24 Apr 2015  路  10Comments  路  Source: NLog/NLog

public abstract class BaseClass
{
    private Logger _logger;
    protected Logger Logger
    {
        get { return _logger ?? (_logger = LogManager.GetCurrentClassLogger()); }
    }
}

public class Derived : BaseClass
{
    public Derived()
    {
        Logger.Info("test");
        // Logger "BaseClass"
        // Expected "Derived"  
    }
}

Workaround:
_logger = LogManager.GetLogger(GetType().Name)

question

Most helpful comment

the benefit is to not have to implement a logger in all derived classes

All 10 comments

I would expect "baseclass" because it's defined in baseclass.

This is expected behavior.

What would you expect with class Derived2: BaseClass...?

What would you expect with class Derived2: BaseClass...?

logger: Derived2

BaseClass is an abstract class. I expect that it use the instantiated class

Yes but the method is not abstract

the method says: GetCurrentClassLogger

I expect the current instantiated class, maybe I'm wrong...

So what is the best practice if i want to have a base abstract class with a logger?

The best practice it to create a private field for each class. So each class have:

private Logger _logger = LogManager.GetCurrentClassLogger(); //or static if desired. 

There is no benefit creating this in an abstract class IMO

the benefit is to not have to implement a logger in all derived classes

It saves 1 line of code for each class, yes.

LogManager.GetLogger(GetType().Name) looks also fine to me.

Closed as this seems answered, please reopen if needed

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ErcinDedeoglu picture ErcinDedeoglu  路  3Comments

imanushin picture imanushin  路  3Comments

FaMouZx3 picture FaMouZx3  路  3Comments

linmasaki picture linmasaki  路  3Comments

carkov1990 picture carkov1990  路  3Comments