Logging Errors with ELMAH in ASP.NET MVC 3 – Part 3 – (Filtering)

Tags: ASP.NET, MVC, Logging, Error Handler, Elmah

Filtering Unwanted Errors

Ok, the reason I really like receiving an email for the every error message is because it will get annoying really fast. This results in me fixing the errors really fast. But there are just some errors that you just can't (or don't want to) "fix". If you noticed in Part 1, the error page contained some 404 errors for /favicon.ico. Errors like these will get annoying really quickly, and fortunately there's an easy way to filter them out. This chunk of code will filter out all 404 errors with a URL matching /favicon.ico.

<system.web>
  <httpModules>
    <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
  </httpModules>
</system.web>

<system.webServer>
  <modules>
    <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
  </modules>
</system.webServer>

<elmah>
  <errorFilter>
    <test> <!-- do not log favicon.ico 404's -->
      <and>
        <equal binding="HttpStatusCode" value="404" type="Int32" />
        <regex binding="Context.Request.ServerVariables['URL']"
               pattern="/favicon\.ico(\z|\?)" />
      </and>
    </test>
  </errorFilter>
</elmah>

Filtering 404 errors out of the ErrorMailModule

Some errors are less important than others, for example 404 errors. I want to log all the 404's my site may receive, but I do not want an email every time someone mistypes a url on my site. To keep logging all errors (including 404's), but filter some from being sent via email, we can add this method to our Global.asax.cs file.

public void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e)
{
    var httpException = e.Exception as HttpException;
    if (httpException != null && httpException.GetHttpCode() == 404)
    {
        e.Dismiss();
    }
}

The ELMAH filtering can do a lot of cool stuff, you can even write scripts in JScript, but for the most part, the example above will be enough to do what you want. For more on filtering go to the wiki page.

Next Step: Logging Errors with ELMAH in ASP.NET MVC 3 – Part 4 – (HandleErrorAttribute) »

This Post is Part of a Multi-Part Series

Add a Comment