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

36 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
  10. Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read  about their market situation nowadays.
    python course in pune
    python course in chennai
    python course in Bangalore

    ReplyDelete
  11. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.

    Java training in Chennai | Java training institute in Chennai | Java course in Chennai

    Java training in Bangalore | Java training institute in Bangalore | Java course in Bangalore

    Java online training | Java Certification Online course-Gangboard

    Java training in Pune

    ReplyDelete
  12. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject

    rpa training in chennai |rpa course in chennai|
    rpa training in bangalore | best rpa training in bangalore | rpa course in bangalore | rpa training institute in bangalore | rpa training in bangalore | rpa online training

    ReplyDelete
  13. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.
    AWS Training in Bangalore | Amazon Web Services Training in Bangalore
    Advanced Amazon Web Services Training in Pune | Best AWS Training in Pune
    AWS Online Training | Best Online AWS Certification Course - Gangboard
    Best Top 110 plus AWS Interview Question and Answers 2019

    ReplyDelete
  14. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    rpa course in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  15. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.
    Python Online training
    python Training in Chennai
    Python training in Bangalore

    ReplyDelete
  16. The desire to play is normal, if you are passionate passion, then use it for the benefit of yourself. best online casino roulette I would play as if I live on the last day.

    ReplyDelete
  17. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    Python Online certification training
    python Training institute in Chennai
    Python training institute in Bangalore

    ReplyDelete
  18. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    AWS Training in Bangalore | Best AWS Amazon Web Services…
    Amazon Web Services (AWS) Training in Pune India
    AWS Training | AWS Training and Certification | AWS online training
    AWS Training in Bangalore cost| Aws training in Bangalore with placements

    ReplyDelete
  19. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.
    microsoft azure training in bangalore
    rpa training in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  20. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    AWS Training in pune
    AWS Online Training

    ReplyDelete
  21. Thank you so much for sharing. Keep updating your blog. It will very useful to the many users Top Web Design Company in Bangalore | Website Developers in Bangalore | Website Designing Company in Bangalore

    ReplyDelete
  22. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Data Science Training in Indira nagar
    Data Science training in marathahalli
    Data Science Interview questions and answers
    Data Science training in btm layout
    Data Science Training in BTM Layout
    Data science training in bangalore

    ReplyDelete
  23. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience.
    Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in


    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium interview questions and answers

    ReplyDelete