Friday, January 27, 2012

Install Elmah logging with ASP.NET MVC 3

Elmah is a great logging tool for ASP.NET and works fine with ASP.NAT MVC 3 with these quick steps:

1. Ensure NuGet is installed in Visual Studio 2010 (shows as Library Package Manager under Tools menu)

2. Open the Package Manager console and install Elmah by typing:
PM> Install-Package Elmah.MVC
This updates the web.config with sectionGroup, httpModules and httpHandlers and adds dll references.

3. Add to web.config:
  <elmah>
    <security allowRemoteAccess="no" />
    <errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/App_Data/Elmah" />
  </elmah>

4. To enable error logging when customErrors is "on" add the following to Global.asax: [see: http://stackoverflow.com/questions/766610/how-to-get-elmah-to-work-with-asp-net-mvc-handleerror-attribute/5936867#5936867]

public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
    public void OnException (ExceptionContext context)
    {
        // Log only handled exceptions, because all other will be caught by ELMAH anyway.
        if (context.ExceptionHandled)
            Elmah.ErrorSignal.FromCurrentContext().Raise(context.Exception);
    }
}


And:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ElmahHandledErrorLoggerFilter());  // Required so that Elmah still loggs errors when customErrors mode="On"
            filters.Add(new HandleErrorAttribute());
        }

Done.

1 comment: