Thursday, 5 July 2012

How I Modernized My Error Logging by ELMAH

In one of my ASP.NET applications, I didn't have enough time to add a better error logging mechanism, so I ended up with this:

protected void Application_Error(object sender, EventArgs e)
{
    IPrincipal principal = Thread.CurrentPrincipal;
    var err = "Error Caught in MyApplication\n" +
            "Error in: " + Request.Url +
            "\r\nUsername: " + principal.Identity.Name +
            "\r\nError Message:" + objErr.Message +
            "\r\nStack Trace:" + objErr.StackTrace;
    SendMail(
        "from@example.com",
        "to@example.com",
        String.Format("Exception @{0}"DateTime.Now),
        err);
}

And of course having my custom error settings and pages in the web.config:
      <customErrors defaultRedirect="GenericErrorPage.aspx"
        mode="RemoteOnly" xdt:Transform="Replace">
        <error statusCode="404" redirect="FileNotFound.aspx" />
      </customErrors>

Actually, it did the job for me and I was receiving emails from the above code into my inbox whenever there was any unhandled exception in that application. The problem with this approach is that it is not configurable and I was receiving so many emails into my inbox even for 404 error code which is Http file not found error. In addition, I needed to store the exceptions somewhere i.e. in a database easy and without any coding, so I will be able to generate some reports out of it later.

ELMAH

ELMAH (Error Logging Modules and Handlers for ASP.NET) is the right and fast answer for this need. Actually, it has been there for years. First, you need to install ELMAH into your web project from nuget running this command in your Package Manager Console in Visual Studio:
Install-Package elmah

This command will do almost everything for you specially your web.config settings. To test it, just point to below URL to generate a test exception in your web application.
http://YourLocalWebSiteUrl/elmah.axd/test

Then point to http://YourLocalwebSiteUrl/elmah.axd to see the ELMAH output.

If you can see ELMAH output, then it is working for your in-memory logs. Now, you need to make it to store logs into your SQL Server database (or any other db that it supports). To set up ELMAH to save logs to SQL Server, you need to create the error log source data table and stored procedures in your database by 
running a DBML script from:
http://code.google.com/p/elmah/downloads/detail?name=ELMAH-1.2-db-SQLServer.sql

The web.config settings for database logging is:

<errorLog type="Elmah.SqlErrorLog, Elmah" 
          applicationName="YourApp"
          connectionStringName="YourConnectionStringName" />

Notice to the applicationName property in above settings which is useful when you are using a centralized database to log errors for all of your web applications.To add email notifications all you need is:
 <errorMail from="from@example.com"
            to="to@example.com"
            subject="Unhandled Exception in My Application"
            priority="High"
            async="true"
            smtpPort="25"
            smtpServer="YourSMTPServer"
            useSsl="false"
            noYsod="false" />

If you want to filter some errors like 404 error, so ELMAH won't log them or send email then:

<errorFilter>
  <test>
    <or>
      <and>
        <equal binding="HttpStatusCode" value="404" type="Int32" />
      </and>
    </or>
  </test>
</errorFilter>    

If you want ELMAH to log 404 errors, but does not send emails for this type of error:
<errorFilter>
  <test>
    <or>
      <and>
        <equal binding="HttpStatusCode" value="404" type="Int32" />
        <regex binding="FilterSourceType.Name" pattern="ErrorMailModule" />
      </and>
    </or>
  </test>
</errorFilter>

Resources

16 comments:

  1. I am really happy with your blog because your article is very unique and powerful for new reader.
    selenium training in chennai
    selenium training in bangalore

    ReplyDelete
    Replies
    1. nice blog.. good information which is useful . Microsoft Dynamics CRM Training Online

      Microsoft Dynamics CRM Training Online

      Delete
  2. nice blog.. good information which is useful . Microsoft Dynamics CRM Training Online

    Microsoft Dynamics CRM Training Online




    ReplyDelete
  3. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    Devops Training courses
    Devops Training in Bangalore
    Best Devops Training in pune
    Devops interview questions and answers

    ReplyDelete
  4. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.


    rpa training in chennai |
    best rpa training in chennai
    rpa online training
    rpa course in bangalore
    rpa training in pune
    rpa training in marathahalli
    rpa training in btm

    ReplyDelete
  5. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.

    best rpa training in chennai
    rpa training in chennai |
    rpa online training
    rpa course in bangalore
    rpa training in pune
    rpa training in marathahalli
    rpa training in btm

    ReplyDelete
  6. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.
    python course institute in bangalore | python Course institute in bangalore| python course institute in bangalore

    ReplyDelete
  7. I’m planning to start my blog soon, but I’m a little lost on everything. Would you suggest starting with a free platform like Word Press or go for a paid option? There are so many choices out there that I’m completely confused. Any suggestions? Thanks a lot.



    AWS Training in NewYork City | Amazon Web Services Training in Newyork City


    AWS Training in London | Amazon Web Services Training in London, UK

    Amazon Web Services Online Training in USA | AWS Online Course in USA

    ReplyDelete
  8. Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ReplyDelete
  9. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    ReplyDelete