title: Logging errors in ASP.NET MVC
body: <p>I'm currently using log4net in my ASP.NET MVC application to log exceptions.  The way I'm doing this is by having all my controllers inherit from a BaseController class.  In the BaseController's OnActionExecuting event, I log any exceptions that may have occurred:</p>
  
  <pre><code>protected override void OnActionExecuted(ActionExecutedContext filterContext)
  {
      // Log any exceptions
      ILog log = LogManager.GetLogger(filterContext.Controller.GetType());
  
      if (filterContext.Exception != null)
      {
          log.Error("Unhandled exception: " + filterContext.Exception.Message +
              ". Stack trace: " + filterContext.Exception.StackTrace, 
              filterContext.Exception);
      }
  }
  </code></pre>
  
  <p>This works great if an unhandled exception occurred during a controller action.</p>
  
  <p>As for 404 errors, I have a custom error set up in my web.config like so:</p>
  
  <pre><code>&lt;customErrors mode="On"&gt;
      &lt;error statusCode="404" redirect="~/page-not-found"/&gt;
  &lt;/customErrors&gt;
  </code></pre>
  
  <p>And in the controller action that handles the "page-not-found" url, I log the original url being requested:</p>
  
  <pre><code>[AcceptVerbs(HttpVerbs.Get)]
  public ActionResult PageNotFound()
  {
      log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));
  
      return View();
  }
  </code></pre>
  
  <p>And this also works.</p>
  
  <p>The problem that I'm having is how to log errors that are on the .aspx pages themselves.  Let's say I have a compilation error on one of the pages or some inline code that will throw an exception:</p>
  
  <pre><code>&lt;% ThisIsNotAValidFunction(); %&gt;
  &lt;% throw new Exception("help!"); %&gt;
  </code></pre>
  
  <p>It appears that the HandleError attribute is correctly rerouting this to my Error.aspx page in the Shared folder, but it is definitely not being caught by my BaseController's OnActionExecuted method.  I was thinking I could maybe put the logging code on the Error.aspx page itself, but I'm unsure of how to retrieve the error information at that level.</p>