Implementing ELMAH in an ASP.NET MVC 4 Application
I’m sure that by now many of you have heard about ELMAH (Error Logging Modules and Handlers) and all of the built in exception handling and error logging wonderfulness that it brings. For those of us who have not had the pleasure of working with ELMAH, it is a pluggable application-wide error logging solution that provides the following:
• Exception logging
• A web page for remotely viewing your exception log
• A web page for remotely viewing exception details
• Email notification capabilities
• RSS feed capabilities
I decided to write yet another post about implementing ELMAH, but specifically in an ASP.NET MVC application because I find that there are times when we want to implement a solution that we were promised would be a simple task; only to find ourselves looking through tons of blog posts and documentation to actually be able to implement that “simple” solution. My goal is to provide you with all of the information needed to implement ELMAH in a single location.
Installing ELMAH
Installing ELMAH is a very simple task that can be done via two methods. The first method requires you to simply open the NuGet Package Manager, search for ELMAH, and click on the Install button:
The second method is to open the Package Manager Console and type in the following command:
Both methods will ensure that the appropriate libraries are added to your project. It will also cause the following entries to be added to your Web.config file:
At this point we have the capability of running our application and viewing the exception log via the web page that ELMAH provides for us (URL structure: [your application URL]/elmah.axd):
Configuring ELMAH to Log errors to a SQL Server Database
You have several options for storing your ELMAH exception logs i.e. XML files, MySQL, SQL Server, etc. but as an example I will cover logging to a SQL Server database.
You can download a SQL script from the following location that can be used to create the table structure that ELMAH expects to write to: https://code.google.com/p/elmah/downloads/detail?name=ELMAH-1.2-db-SQLServer.sql. The table structure is displayed below:
Once the table is in place configuring ELMAH to log to a SQL Server database is as simple as adding a connection string for the ELMAH database to your project’s config file, setting the log type to SqlErrorLog, and referencing the ELMAH connection string as shown below:
One thing to note is that you have to use the SQL Server format for the ELMAH connection string because it is what ELMAH expects.
Creating a Custom ExceptionFilterAttribute Class
For MVC you will need to create a custom ExceptionFilterAttribute class that will be used to call Elmah when an exception occurs in your application:
Registering the Custom ExceptionFilterAttribute Class
The final step is to register the custom Exception FilterAttriute class on application start up: