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

No comments:

Post a Comment