Search code examples
asp.net-mvc-3elmahhttpcontexterror-loggingapplication-start

Elmah log error in Asp.Net MVC Application_Start


Possible Duplicate:
elmah: exceptions without HttpContext?

In Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        throw new Exception("TEST");
    }


    // ... other usual methods
}

Elmah is not logging the exception.

I do quite a bit of initialisation and configuration work in here and it's kinda important that I get error logs if anything goes wrong.

Not sure why it doesn't work but presumably to do with the MVC lifecycle - perhaps there is no HttpContext at this stage? Is there any way to log errors through Elmah here?


Solution

  • You're definitely right about one thing, HttpContext.Current does not exist in Application_Start, which is probably one of the problems of why Elmah doesn't log errors from that method.

    But, if you have an exception in Application_Start, you have bigger problems than Elmah not logging the exception. You're Application_Start method should be flawless, or if it's not, it needs to be written so that it fails in your dev environment so you can see the problem before you push it to production. If it's an intermittent exception, I would suggest putting the problem code elsewhere.

    UPDATE

    Based on your comment, maybe this would work for you. It also has the additional benefit of checking on every request to see if it failed the first time.

    protected void Application_BeginRequest(object sender, EventArgs args)
    {
      CheckConfiguration();
    }
    
    private static readonly object ConfigurationLockObject = new object();
    private void CheckConfiguration()
    {
      /** Lock Bypass **/
      if (IsConfigured()) 
      {
        return;
      }
    
      // The lock ensures the configuration only gets called one at a time.
      lock (ConfigurationLockObject)
      {
        // Must check for configuration again, just in case multiple threads had hit the lock
        if (!IsConfigured())
        {
          try
          {
            // Configuration Code
          }
          catch (Exception exception)
          {
            Log.Error("Exception Occurred", exception);
          }
        }
      }
    }