Tuesday, November 20, 2012

Elmah: filtering "spam" exceptions

Elmah is a great logging facility for ASP.NET.

It can be easily configured in Web.config. Here an example:
 <configuration>  
  <elmah>  
   <errorLog type ="Elmah.XmlFileErrorLog, Elmah" logPath ="~/errors/" />   
   <security allowRemoteAccess ="1" />   
   <errorMail from ="noreply@server.com" to= "admin@example.com" subject ="Web Exception" async= "true "smtpPort ="0"></errorMail>   
  </elmah>  
 </configuration>  

But it's very likely that you will get a lot of "spam" error messages in your log and on your e-mail. So you'll want to filter some of those messages.

You can do it in a very flexible way as follows:
 <configuration>  
  <elmah>  
   <errorLog type ="Elmah.XmlFileErrorLog, Elmah" logPath ="~/errors/" />  
   <errorFilter>  
    <test>  
     <or>  
      <equal binding ="HttpStatusCode" value ="404" type ="Int32" />  
      <regex binding ="Exception.Message" pattern =" ^A potentially dangerous Request$" />  
      <regex binding ="Exception.Message" pattern =" ^The parameters dictionary contains a null entry$" />  
      <and>  
       <regex binding ="Exception.Message "pattern ="^The operation has timed out$" />  
       <regex binding ="Context.Request.ServerVariables['URL']" pattern =".*/some-url/$" caseInsensitive="true" />  
      </and>  
      <and>  
       <regex binding ="Exception.Message" pattern ="^Invalid image profile*" />  
       <regex binding ="Context.Request.ServerVariables['HTTP_USER_AGENT']" pattern ="bot" />  
      </and>  
     </or>  
    </test>  
   </errorFilter>  
   <security allowRemoteAccess ="1" />  
   <errorMail from ="noreply@server.com" to= "admin@example.com" subject ="Web Exception" async= "true "smtpPort ="0"></errorMail>  
  </elmah>  
 </configuration>  

As you can see, we just added <errorFilter> section with various filter conditions, separated by Boolean operations(<or>, <and>). It is a very intuitive way to filter errors that you don't want to track down with Elmah.

No comments:

Post a Comment