Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# derived class type needed in base for logging using NLog

We're using NLog for logging in an C# MVC3 web application. All of our controllers extend a custom base "ApplicationController" that gives us access to a constantly needed methodes and s members.

I'd like all controllers to have access to the Logger via this base class, but want the detail of knowing what derived class the log statements originated in.

Our application controller looks like this:

public abstract class ApplicationController : Controller
{
    protected Logger _logger;
    protected virtual Logger Logger
    {
        get { return _logger ?? (_logger = LogManager.GetCurrentClassLogger()); }
    }

    protected ApplicationController()
    {
        Context = new Entities();
    }

If a derived controller doesn't override the Logger than all statements will show they originated from the Application controller. Currently, I've got essentially the same Logger statement in all derived controllers. For example:

public class PropertyController : ApplicationController
{
    private readonly DatatapeService _datatapeService;
    private readonly PropertyService _propertyService;
    protected override Logger Logger
    {
        get { return _logger ?? (_logger = LogManager.GetCurrentClassLogger()); }
    }

Obviously this is poor implementation practice.

  1. How can I dry this up? Specifically, what is my understanding of C# lacking to accomplish exactly this specific task?
  2. Is there a logging pattern that I should be following where I'm not exposing the logging class (NLog) directly?

TIA!

like image 219
Bobby B Avatar asked Jan 03 '12 11:01

Bobby B


3 Answers

NLog API is slightly different than Log4net. You need to use

Logger = LogManager.GetLogger(GetType().Name);

if you only pass the type, LogManager will expect a logger type (i.e. a custom logger)

like image 54
Sebastian Slutzky Avatar answered Oct 01 '22 00:10

Sebastian Slutzky


I am unfamiliar with NLog but in Log4Net the syntax LogManager.GetLogger(this.GetType()) will accomplish what you want. GetTypereturns the leaf type in your inheritance hierarchy, even if called in the base ApplicationController class, when the logger is first created (ie: on first access to the Logger property) it will instantiate it with type PropertyController

like image 42
Dr. Andrew Burnett-Thompson Avatar answered Sep 30 '22 23:09

Dr. Andrew Burnett-Thompson


The How to create Logger for sub classes page of the NLog wiki now suggests the following pattern:

class BaseClass
{
    protected BaseClass()
    {
        Log = LogManager.GetLogger(GetType().ToString());
    }

    protected Logger Log { get; private set; }
}

class ExactClass : BaseClass
{
    public ExactClass() : base() { }
    ...
}
like image 40
Holistic Developer Avatar answered Sep 30 '22 23:09

Holistic Developer