Jacques
Jacques

Reputation: 7135

ASP.NET MVC Controller extension method to make Log available to all controllers

Is it possible to extend the Controller type in Asp.net MVC to make a method available to all controller classes for application logging?
I've tried this:

public static class ControllerExtensions
    {
        public static ILog Log(this Controller controller)
        {
            log4net.Config.XmlConfigurator.Configure();
            return log4net.LogManager.GetLogger(controller.GetType());
        }
    }

But, if I try to access the method as in:

Controller.Log.Info("hello");

It won't compile with the error message: 'System.Web.Mvc.Controller' does not contain a definition for 'Log'

I do have a using statement bringing the static class into scope.

Any help would be great.
Jacques

Upvotes: 5

Views: 11013

Answers (3)

Andrei
Andrei

Reputation: 44600

I would suggest to implement abstract base controller class for this purpose:

public abstract class BaseController : Controller
{
    public ILog Log
    {
        get { return LogManager.GetLogger(GetType()); }
    }
}

You can also achieve similar result using protected static log instance, here is an example with Serilog:

protected static readonly ILogger log = Log.ForContext(typeof(MyController));

Upvotes: 13

chamara
chamara

Reputation: 12711

How about creating a custom action filter?

create a class LogInfo inherited by ActionFilterattribute

public class LogInfo : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
           //Logging operation code here
        }
    }

Controller:

[LogInfo]
public ActionResult Index()
{
   return View();
}

Upvotes: 2

dcastro
dcastro

Reputation: 68660

Try

//inside a controller's method
this.Log().Info("hello");

You're not adding a property Log, you're adding an extension method Log().

There's no such thing as "extension properties".

Upvotes: 5

Related Questions