Click here to Skip to main content
15,884,176 members
Articles / Web Development / HTML
Tip/Trick

Error logging in MVC and WebAPI using ELMAH

Rate me:
Please Sign up or sign in to vote.
4.35/5 (8 votes)
22 Jun 2015CPOL2 min read 55.2K   788   11   16
This tip demonstrates how to use ELMAH (Error Logging Modules and Handlers) in ASP.NET MVC and WebAPI.

Introduction

Once a web application is live, it is very difficult to monitor it round the clock and there can be magnitude of reasons behind any exception / error occurring in application. Therefore, it is always wise to have an integrated error logging and notification mechanism in a web application to find the root cause for an issue and to minimize the error detection time and down time of the web application.

In this tip, we will integrate ELMAH to a web application (using MVC and WebAPI) for error logging (in local DB) as well as to send notification emails.

Background

I have been working on a web application which has both Web API and MVC and required exception logging on both platforms and since both Web API and MVC have different pipelines, ELMAH implementation required specific changes for each platform.

Using the Code

Firstly, ELMAH nuget package is to be installed.

install ELMAH nuget package

Then, add an mdf database file in App_Start folder.

Image 2

and execute required SQL scripts (download from here).

Add connection string to local database in web.config file.

XML
<add name="ELMAHConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\elmah.mdf;Initial Catalog=elmah;Integrated Security=True;
MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

Update the elmah section of web.config file with connection string and email server details.

XML
<elmah>
    <!--
        See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for 
        more information on remote access and securing ELMAH.
    -->
    <security allowRemoteAccess="false" />
  <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="ELMAHConnectionString" 
   applicationName="codeproject demo" />
  <errorMail from="fromemail@email.com" to="toemail@email.com" 
   subject="codeproject elmah error mail" async="false" smtpPort="587" 
   smtpServer="smtp.emailserver.com" userName="username" password="pwd"/>
</elmah>

Implementation in MVC

Create a class inherited by System.Web.Mvc.HandleErrorAttribute and overriding OnException method to log error occurring in MVC application.

C#
public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
   {
       public override void OnException(ExceptionContext context)
       {
           base.OnException(context);
           var e = context.Exception;
           var httpcontext = HttpContext.Current;

           var signal = ErrorSignal.FromContext(httpcontext);
           if (signal != null)
           {
               signal.Raise(e, httpcontext);
           }
       }
   }

Add class instance to GlobalFilterCollection in App_Start/FilterConfig.cs.

C#
public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ElmahHandleErrorAttribute());
        }
    }

Implementation in WebAPI

Create a class inherited by System.Web.Http.Filters.ExceptionFilterAttribute and overriding OnException method to log error occurring in WebAPI.

C#
public class ElmahHandleWebApiErrorAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var e = context.Exception;
            RaiseErrorSignal(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;
        }
    }

Add class instance to HttpConfiguration filters in App_Start/WebApiConfig.cs.

C#
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Filters.Add(new ElmahHandleWebApiErrorAttribute());
        }
    }

Error Logs can be viewed by appending elmah.axd to root url at local machine.

Image 3

Error notifications will automatically be sent to all recipients(semi-colon';' separated) in to attribute of <errorMail> tag within <elmah> section.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Saurabh Sharma is a .Net Programmer.

Comments and Discussions

 
QuestionWhy duplicate what Elmah does? Pin
Brady Kelly3-Dec-16 22:36
Brady Kelly3-Dec-16 22:36 
QuestionDoes the mdf file have to be in the app start folder? Pin
Dylan Hyslop11-Mar-16 18:16
Dylan Hyslop11-Mar-16 18:16 
AnswerRe: Does the mdf file have to be in the app start folder? Pin
saurabhsharmacs26-Apr-16 21:51
saurabhsharmacs26-Apr-16 21:51 
QuestionWill this log 500 errors Pin
Dylan Hyslop9-Mar-16 8:38
Dylan Hyslop9-Mar-16 8:38 
QuestionWhat is the difference between ELMAH and ELMAH.Contrib.WebApi Pin
Member 112864419-Jan-16 3:35
Member 112864419-Jan-16 3:35 
QuestionWorks good but i receive 2 emails Pin
Simon Ntumba26-Nov-15 4:22
Simon Ntumba26-Nov-15 4:22 
AnswerRe: Works good but i receive 2 emails Pin
saurabhsharmacs28-Nov-15 3:35
saurabhsharmacs28-Nov-15 3:35 
QuestionElmah.MVC Pin
Bastien Vandamme19-Nov-15 20:34
Bastien Vandamme19-Nov-15 20:34 
Hello,

I have two questions:
  1. Do you know what is the Elmah.MVC nugget package?
  2. Do you know why there is no new stable version for 3 years now?

AnswerRe: Elmah.MVC Pin
saurabhsharmacs28-Nov-15 3:43
saurabhsharmacs28-Nov-15 3:43 
QuestionWork Great at first try. Pin
Gabriela_Macias14-Nov-15 8:36
Gabriela_Macias14-Nov-15 8:36 
QuestionNot able to compile Pin
TalkCP24-Jul-15 3:17
TalkCP24-Jul-15 3:17 
QuestionError CS0246 The type or namespace name 'ActionResult' could not be found (are you missing a using directive or an assembly reference?) Pin
Roger C Moore25-Jun-15 8:11
Roger C Moore25-Jun-15 8:11 
AnswerRe: Error CS0246 The type or namespace name 'ActionResult' could not be found (are you missing a using directive or an assembly reference?) Pin
Roger C Moore25-Jun-15 8:15
Roger C Moore25-Jun-15 8:15 
QuestionExceptionless Pin
Blake A Niemyjski23-Jun-15 4:13
Blake A Niemyjski23-Jun-15 4:13 
AnswerRe: Exceptionless Pin
saurabhsharmacs24-Jun-15 1:17
saurabhsharmacs24-Jun-15 1:17 
AnswerRe: Exceptionless Pin
Bastien Vandamme19-Nov-15 21:06
Bastien Vandamme19-Nov-15 21:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.