Sunday, July 10, 2011

ELMAH - Logging errors in ASP.NET

Catching and logging unhandled exceptions is one of the first tasks in developing an ASP.NET application.

Typically you put code which handles exceptions into Global.asax:

 


The are many ways to report an error: you may write it into a database, send an email or store it in memory.  I got tired of copying such code from one app to another and finally found a component that allows me to handle errors in a code-less way. It is ELMAH



ELMAH provides an HttpModule which does exactly the same work that I previously used to do.
All I need is to configure its behavior in Web.config.



Installing ELMAH


The easiest way to install ELMAH is using NuGet.
I am not familiar with the command line and always prefer a graphic UI, so I used its this one:



Search for ELMAH package:


Select ELMAH, click 'Install' - that's it.

ELMAH in action

Any time you have an unhandled exception you see the "yellow screen of death":




At the same time the ELMAH module has captured this exception along with all related data and gives you simple web access to the recent errors logged (by default at /elmah.axd)







Configuration

By default ELMAH stores logs in memory, but it supports XML and database storages.
Go back to the NuGet package manager and select one of these additional packages: 'ELMA on XML Log', 'ELMA on MS Sql Server Compact', 'ELMAH on MongoDB', etc.

The selected storage appears in sections in Web.config:



I assume that it is possible to implement a custom logger by deriving the Elmah.ErrorLog class

Log an expected exception

ELMAH allows to log any exception from your code.

For example if you have a code flow which might throw an exception and you gracefully handle it (e.g. with a try/catch block). Such a swallowed exception will not be propagated and logged by the ELMAH module. For such a case ELMAH provides the ErrorSignal API:




More features

 ELMAH has a lot more features, which are not part of this short overview. You can:

  • Filter unwanted exceptions, programmatically and via configuration.
  • Get a digest RSS feed that lists errors by day and up to last 15 days. 
  • Send error notifications as tweets to Twitter.
  • Send an e-mail notification of each error at the time it occurs. 
  • and more...

1 comment:

  1. This is a great logging library:
    http://www.kellermansoftware.com/p-14-net-logging-library.aspx

    ReplyDelete