5

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

0

3 Answers 3

13

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));
Sign up to request clarification or add additional context in comments.

2 Comments

I used this approach in the end. Thanks Andrei
I like this approach.
5

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".

Comments

2

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();
}

1 Comment

I used @Andrei's approach, but I'm interested in your answer. For this filter, how would I go about setting specific log conditions if it weren't just a standard info log. For example if an exception occurred inside the Index method, could I use the filter to log an exception?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.