Logging in MVC Part 1- Elmah

This is part 1 of the MVC Logging series. Other articles in the series are:


Logging is one of the most useful services that every production website should have.

When errors occur on your website you should be notified about them. Whilst you may think you have written perfect code and unit tested everything to the best of your ability errors can and will still happen. The database server may go down, a 3rd party website may be offline, the shared hosting environment of your website may suffer an outage, a previously undetected bug may occur and the list goes on.

Having a great logging system in place allows you to stay on top of errors when they do happen.

In this series we will be building a logging reporting system that will allow you to drill into the various events that get logged on your website.

Before we get started let’s take a look at the finished solution:

and we would also like to see some graphs so we can quickly pinpoint when errors occurred on our website:

and we also would like to have an RSS feed of our errors:


So let’s write down the goals for what we want to achieve:

1. Log all unhandled exceptions to a database

2. Log entries to our database whenever the website starts up, shuts down, recompiles etc.

3. Log any custom messages that we want to keep track of

4. Handle errors gracefully so that the end-user never sees a yellow screen of death error message.

5. Receive an email when an unhandled exception occurs

6. Allow multiple log providers to be easily swapped in and out of our website.

7. On the website, provide a logging reporting tool that lets us filter and view any message that has been logged.

8. The reporting tool should also allow us to view log entries as an RSS feed so that we can combine multiple feeds from all of the websites under our control.

9. The reporting tool should also have a dashboard or chart so that we can quickly get an overview of any activity on the website.

10. Provide an ability to manage logs, purge old logs, export logs to files or email them to someone.

Well that’s quite a list, so let’s get started!

Getting started

The first thing that we want to do is take care of unhandled exceptions so one of the best tools for that job is ELMAH. ELMAH was created by Atif Aziz and is used on many websites including StackOverflow.

To get started with ELMAH, the following article provides a very good overview of how to set it all up for a normal ASP.Net Web forms website:


I won’t go into all of the details here about setting up Elmah because the above article covers pretty much everything you need to know.

In simple terms you need to :

1. Download Elmah from it’s project page on CodePlex.

2. Extract the files from the zip.

3. The database script is located in the /src/Elmah directory. For SQL Server it is called “SQLServer.sql”. Run the database script to add the Elmah table and stored procs to your database.

4. Add a reference to Elmah for your website.

5. Modify the web.config file sections as explained in the article above. You can download the code I used at the end of this article to see the necessary web.config file alterations.

Configuring Elmah on MVC

However, as we will be using ELMAH on an MVC website we need to do a little bit more than the normal configuration to get it all working together nicely.

In MVC, you normally put [HandleError] attributes on your controllers to handle errors. Like this:

namespace MySampleApp.Controllers
 public class AccountController : Controller

But because we would like to use Elmah to handle our exceptions instead of MVC, we will replace the standard MVC [HandleError] attribute with our own custom attribute called [HandleErrorWithElmah].

The StackOverflow question below provides the necessary details:


The code necessary is shown below:

public class HandleErrorWithELMAHAttribute : HandleErrorAttribute
        public override void OnException(ExceptionContext context)

            var e = context.Exception;
            if (!context.ExceptionHandled   // if unhandled, will be logged anyhow
                    || RaiseErrorSignal(e)      // prefer signaling, if possible
                    || IsFiltered(context))     // filtered?


        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));

At this point we could subsitute the [HandleError] attribute with our [HandleErrorWithELMAH] attribute but we would need to remember to do this on all of our MVC controllers… There has to be a better, easier way! And there is!

The solution is to create a custom Controller factory! And we will also need to write our own ActionInvoker. Let’s write that one first:

public class ErrorHandlingActionInvoker : ControllerActionInvoker
 private readonly IExceptionFilter filter;

 public ErrorHandlingActionInvoker(IExceptionFilter filter)
 if (filter == null)
 throw new ArgumentNullException("filter");

 this.filter = filter;

 protected override FilterInfo GetFilters(
 ControllerContext controllerContext,
 ActionDescriptor actionDescriptor)
 var filterInfo =


 return filterInfo;

And here is the code for the custom controller factory:

public class ErrorHandlingControllerFactory : DefaultControllerFactory
 public override IController CreateController(
 RequestContext requestContext,
 string controllerName)
 var controller =

 var c = controller as Controller;

 if (c != null)
 c.ActionInvoker =
 new ErrorHandlingActionInvoker(
 new HandleErrorWithELMAHAttribute());

 return controller;

The last step is to hook it all up so that happens automatically for each controller we have in our MVC project. To do that we wire up our new controller factory in the Global.asax.cs file:

protected void Application_Start()


 ControllerBuilder.Current.SetControllerFactory(new ErrorHandlingControllerFactory());

So now that it is all wired up, we can actually go ahead and remove the [HandleError] attribute from all of our MVC controllers as our custom controller factory will now automatically inject the [HandleErrorWithElmah] attribute automatically.

The last step is to force an unhandled exception occurring in our application and view the elmah.axd page on our website to see the errors logged.

In the Home Controller I have this:

public ActionResult About()
 // Throw a test error so that we can see that it is handled by Elmah
 // To test go to the ~/elmah.axd page to see if the error is being logged correctly
 throw new Exception("A test exception for ELMAH");

 return View();

and then we just browse to the About page which will generate an exception:

and then browse to the Elmah page to verify that the error was logged correctly.


That ends part 1 of this series. Next time we will look at logging things like when the application starts up, shuts down and recompiles etc.


The sourcecode for part 1 is on the Downloads tab of the associated Codeplex website

Tagged with: , , , ,
Posted in ASP.NET MVC


Welcome to my blog.

Here you will find articles on ASP.NET, MVC

Posted in ASP.NET MVC