Joe Lowrance said, er tweeted, it best when he said,

"the amount of attention ELMAH hasn't got is shocking."

ELMAH is one of those largely unknown and deeply awesome .NET Open Source projects that should be part of ASP.NET proper.

What is ELMAH?

I like to say that ELMAH is Tivo for your ASP.NET Errors. You can get your Yellow Screens of Death, with full call-stack back and analyze what's really happening. It's Exception Driven Development. What's it really do?

Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilites without changing a single line of your code: Logging of nearly all unhandled exceptions.

A web page to remotely view the entire log of recoded exceptions.

A web page to remotely view the full details of any one logged exception.

In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.

mode turned off. An e-mail notification of each error at the time it occurs.

An RSS feed of the last 15 errors from the log.

A number of backing storage implementations for the log, including in-memory, Microsoft SQL Server and several contributed by the community.

Created by Atif Aziz (@raboof on Twitter) and Scott Mitchell , ELMAH means is "Error Logging Modules and Handlers" and has been rocking my world since, well, September of 2004.

(Small Correction, Scott Mitchell helped writing the original MSDN article. ELMAH is 100% conceived of by Atif.)

From the project site:

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

ELMAH is wonderful for many reasons. First, because it just works. Second, because it's a fantastic example of effective use of HttpModules and HttpHandlers working together. Third, because it's been design with enough thought that nearly anything you'd want from it for use in a production site is there.

I'm sitting here in a cafe and I'm going to add ELMAH to the ASP.NET MVC-based NerdDinner.com Source Code. Actually, the site, as I don't need to recompile the source if I'm not doing anything tricky. ;)

Implementing ELMAH on your ASP.NET (MVC or otherwise) Site

I download ELMAH, and I put its DLL in my /bin folder (or wherever you like to put libraries). ELMAH doesn't need to be referenced by your project directly if you don't want to. Ultimately it just needs to be in your bin folder so it can be found. You can put it in /lib and make a build event if you like, as long as it ends up in /bin.

Then I open up two instances of notepad and copy over a few HttpHandlers and HttpModules into my existing web.config. Tedious, but straightforward.

Where you put these depends on if you're using IIS6 or IIS7, but the general idea is the handlers looks like this:



....



....



and the modules looks like this:



...







...



You can pare it down a bit if you don't need ErrorMail, for example. Then, I hit my site at http://localhost:xxxx/elmah.axd and I get this Error log, similar to what you'd see via Trace.axd.

Ok, no errors. Let's make some. I'll visit some messed up URLs and intentionally cause trouble...here's what ELMAH says now:

And I can drill down and see the Yellow Screen of Death (YSOD) as it "would have been."

Now, this assumes my ASP.NET MVC site has no error handling to speak of. ELMAH is watching for unhandled exceptions and recording them, holding them in memory. I can also setup logs to SQL Server or VistaDB or SQLLite so they'll live beyond application recycles.

You can certainly secure access to the ELMAH pages. You can also pull the errors into your favorite RSS Reader, which is a killer feature, IMHO.

Making ELMAH work with ASP.NET MVC's "HandleError" Attribute

In ASP.NET MVC there's an attribute called [HandleError] that will grab anything that goes wrong inside your controllers and show the ~\Shared\Error.aspx View. However, because it "handles" the error, it hides it from ELMAH. Remember that [HandleError] is a declarative try/catch. In my case, I want to have ELMAH handle it.

There's two ways around this.

One, I made a method in my Controller like this:

public ActionResult Trouble()

{

return View("Error");

}

In my web.config, I have a customErrors section like this:







This sends folks to /Dinners/Trouble which shows the Error page, after ELMAH takes care of it.

Second, as an advanced technique, I could write my own derived HandleErrorWithELMAHAttribute that logs the error using ELMAH's API, then passes the exception up to the default handler with ASP.NET MVC.

Looks like Dan Swatik's blog is dead. :( UPDATE: Looks like Dan Swatik was coincidentally doing a similar thing error this morning ! What's nice about the solution on Dan's Blog, is that it was written with the help of Atif Aziz himself! (Remember, Atif's The primary author of ELMAH!) Here's the StackOverflow question.

My naive solution is below, but Atif's is better as it signals the error to ELMAH's pipeline rather that logging directly as mine does. Here's the more correct version:

namespace MvcDemo

{

using System;

using System.Web;

using System.Web.Mvc;

using Elmah;



public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute

{

public override void OnException(ExceptionContext context)

{

base.OnException(context);



var e = context.Exception;

if (!context.ExceptionHandled // if unhandled, will be logged anyhow

|| RaiseErrorSignal(e) // prefer signaling, if possible

|| IsFiltered(context)) // filtered?

return;



LogException(e);

}



private static bool RaiseErrorSignal(Exception e)

{

var context = HttpContext.Current;

if (context == null)

return false;

var signal = ErrorSignal.FromContext(context);

if (signal == null)

return false;

signal.Raise(e, context);

return true;

}



private static bool IsFiltered(ExceptionContext context)

{

var config = context.HttpContext.GetSection("elmah/errorFilter")

as ErrorFilterConfiguration;



if (config == null)

return false;



var testContext = new ErrorFilterModule.AssertionHelperContext(

context.Exception, HttpContext.Current);



return config.Assertion.Test(testContext);

}



private static void LogException(Exception e)

{

var context = HttpContext.Current;

ErrorLog.GetDefault(context).Log(new Error(e, context));

}

}

}

Below is my naive version.

I made this HandleErrorWithELMAHAttribute:

public class HandleErrorWithELMAHAttribute : HandleErrorAttribute

{

public override void OnException(ExceptionContext filterContext)

{

try

{

var context = HttpContext.Current;

Error error = new Error(filterContext.Exception, context);

ErrorLog log = ErrorLog.GetDefault(context);

string id = log.Log(error);

}

catch (Exception localException)

{

//

// IMPORTANT! We swallow any exception raised during the

// logging and send them out to the trace . The idea

// here is that logging of exceptions by itself should not

// be critical to the overall operation of the application.

// The bad thing is that we catch ANY kind of exception,

// even system ones and potentially let them slip by.

//



Trace.WriteLine(localException);

}



base.OnException(filterContext);

}

}



Then I put the attribute on my ASP.NET MVC Controller like this:

[HandleErrorWithELMAHAttribute]

public class DinnersController : Controller {

...

Either way works, I actually kind of prefer the first one, although it requires a controller to have an essentially empty method to send folks to the shared error page. I keep the /Confused and /Trouble methods in there as I think it makes the site more personal.

Anyway, ELMAH rocks and you should use it today. Phil Haack loves ELMAH too! Jeff and the guys at StackOverflow use ELMAH also, albeit a "custom fork." (Release your code, Jeff!)

Time for me to to donate some money to the ELMAH Open Source efforts.

Related