Click here to Skip to main content
14,219,126 members

Error logging in MVC and WebAPI using ELMAH

Rate this:
4.80 (7 votes)
Please Sign up or sign in to vote.
4.80 (7 votes)
22 Jun 2015CPOL
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.

and execute required SQL scripts (download from here).

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

<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.

<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.

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.

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.

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.

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.

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)

Share

About the Author

saurabhsharmacs
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
memberBrady Kelly3-Dec-16 22:36 
QuestionDoes the mdf file have to be in the app start folder? Pin
Dylan Hyslop11-Mar-16 18:16
memberDylan Hyslop11-Mar-16 18:16 
AnswerRe: Does the mdf file have to be in the app start folder? Pin
saurabhsharmacs26-Apr-16 21:51
membersaurabhsharmacs26-Apr-16 21:51 
QuestionWill this log 500 errors Pin
Dylan Hyslop9-Mar-16 8:38
memberDylan Hyslop9-Mar-16 8:38 
QuestionWhat is the difference between ELMAH and ELMAH.Contrib.WebApi Pin
Member 112864419-Jan-16 3:35
memberMember 112864419-Jan-16 3:35 
QuestionWorks good but i receive 2 emails Pin
Simon Ntumba26-Nov-15 4:22
memberSimon Ntumba26-Nov-15 4:22 
AnswerRe: Works good but i receive 2 emails Pin
saurabhsharmacs28-Nov-15 3:35
membersaurabhsharmacs28-Nov-15 3:35 
QuestionElmah.MVC Pin
Bastien Vandamme19-Nov-15 20:34
memberBastien Vandamme19-Nov-15 20:34 
AnswerRe: Elmah.MVC Pin
saurabhsharmacs28-Nov-15 3:43
membersaurabhsharmacs28-Nov-15 3:43 
QuestionWork Great at first try. Pin
Gabriela_Macias14-Nov-15 8:36
memberGabriela_Macias14-Nov-15 8:36 
QuestionNot able to compile Pin
TalkCP24-Jul-15 3:17
memberTalkCP24-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
john_172625-Jun-15 8:11
memberjohn_172625-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
john_172625-Jun-15 8:15
memberjohn_172625-Jun-15 8:15 
QuestionExceptionless Pin
Blake A Niemyjski23-Jun-15 4:13
memberBlake A Niemyjski23-Jun-15 4:13 
AnswerRe: Exceptionless Pin
saurabhsharmacs24-Jun-15 1:17
membersaurabhsharmacs24-Jun-15 1:17 
AnswerRe: Exceptionless Pin
Bastien Vandamme19-Nov-15 21:06
memberBastien 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.

Tip/Trick
Posted 22 Jun 2015

Stats

37.4K views
724 downloads
11 bookmarked