Thursday 5 February 2015

Error Logging with ELMAH

If you don't know about ELMAH you should. Here's how to set it up to Log your MVC 4 application errors.

References:

Install the Nuget Package:

Install-Package Elmah.MVC

Set up Database Logging

Download and run the SQL script https://code.google.com/p/elmah/downloads/detail?name=ELMAH-1.2-db-SQLServer.sql

Web.config

Modify your web.config file as follows:

<elmah></elmah> <elmah> <security allowRemoteAccess="true" /> <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="DefaultConnection" /> </elmah>

Under <appSettings>

<add key="elmah.mvc.requiresAuthentication" value="true" /> <add key="elmah.mvc.allowedRoles" value="Administrator" /> <add key="elmah.mvc.allowedUsers" value="Administrator" />

Try it out:

Login to your application as Administrator and Navigate to: {your url}/elmah

Update: Logging Handled Exceptions

By default ELMAH only logs unmanaged exceptions. To Log handled exceptions add the following to your Try Catch Blocks:

E.g.
try{ }

catch (Exception e)
          {
                Elmah.ErrorSignal.FromCurrentContext().Raise(e);
                ViewBag.ErrorMessage = e.ToString();
                return View("Error");
      }