简体   繁体   中英

Can't get log4net working in MVC3 sub-classed controller

I have an MVC3 application that I'd like to get log4net working in.
I got the code I'm using from this site

I can get the logging to work if I add this code to an Action method.

  public ActionResult Index() {  
      log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());  
      log.Info("Here I am in Index.");   
      return View();  
  } 

I'd like to enable logging in all my controllers, so I added the following class to my project,

  public class LoggingController :Controller {
      protected log4net.ILog Log;

      public LoggingController () {
          Log = log4net.LogManager.GetLogger(GetType());
      }
  }

and I'm having my Home controller inherit from this class, LoggingController.

I've put a break point on my LoggingController's constructor and determined the constructor is being called, however my logging isn't working when done this way.

My question then is:

Why isn't this working? OR Is there a better way of accomplishing what I'm trying to do here?

Thanks in advance.

Why isn't this working?

Because the type argument you pass to the GetLogger method must match that of the containing type. You are passing HomeController (by using GetType() ) instead of LoggingController which is where the variable is declared. Try like this:

public LoggingController () {
    Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM