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

Can I extend the controller type in Asp.net MVC to make the method available to all controller classes for application logging?
I 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 will not compile with the error message: "System.Web.Mvc.Controller" does not contain a definition for "Log"

I have a using statement that casts a static class into scope.

Any help would be great.
Jacques

+4
source share
3 answers

I would suggest implementing an abstract base controller class for this:

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

Try

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

You do not add the Log property, you add the Log() extension method.

There are no such things as "extension properties."

+4
source

How to create a custom action filter?

create a LogInfo class inherited by ActionFilterattribute

 public class LogInfo : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { //Logging operation code here } } 

Controller:

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

Source: https://habr.com/ru/post/1500100/


All Articles