ASP.NET

How to stop ELMAH logging repeating errors

A system I look after uses ELMAH for logging errors which works very effectively.

However, there have been a couple of occasions recently where we have experienced network problems between our web and database servers and this resulted in a stream of over 9000 ELMAH error log files being created; these were all of type Win32Exception.

So, I wanted a solution where if a Win32Exception error was repeatedly being logged by ELMAH then logging of this error would stop (but other errors would still be logged); I reckoned to stop logging once a Win32Exception error had been logged consecutively 10 times in the previous 60 seconds.

My solution was to add the following code to the ErrorLog_Filtering method in the Global.asax.cs file:

 
void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
{
    if (e.Exception.GetBaseException() is System.ComponentModel.Win32Exception)
    {
       var periodInSeconds = 60;
       var numberOfErrorsToStopLoggingAt = 10;
       var errorList = new List();
       ErrorLog.GetDefault(Context).GetErrors(0, numberOfErrorsToStopLoggingAt, errorList);
       if (errorList.Count > 0)
       {
          var win32ErrorsInPeriod = errorList.FindAll(x => x.Error.Type == "System.ComponentModel.Win32Exception" 
                                         && x.Error.Time > DateTime.Now.AddSeconds(-periodInSeconds));
          if (win32ErrorsInPeriod.Count == numberOfErrorsToStopLoggingAt)
              e.Dismiss();
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s