.NET Tip: Searching for a Needle in a Haystack, or an Entry in an Event Log

I frequently receive calls asking why an application is not behaving as expected. Many times, a quick look at the database can provide the answer. Sometimes, however, things are a little more involved. Our internal applications make extensive use of event logs. The event logs will contain error messages, warnings, and in the case of some occasionally connected systems a log of all the data received. Trying to manually forge through the event logs can be a daunting task. The answer, of course, is to let a computer do most of the searching for you. Here is a class with a couple static methods that you can use to quickly limit the number of event log entries that you have to manually search through:

public enum EventLogFilterType
{
   TimeGenerated,
   UserName,
   MachineName,
   Category,
   Source,
   EntryType,
   Message,
   EventID
}

public sealed class SearchEventLog
{
   // Prevent this class from being instantiated.
   private SearchEventLog() {}
   public static EventLogEntry[]
      FilterEventLog(EventLogFilterType FilterType,
                     IEnumerable Entries, object Criteria1,
                     object Criteria2)
   {
      ArrayList FilteredEntries = new ArrayList();
      foreach (EventLogEntry Entry in Entries)
      {
         switch (FilterType)
         {
            case EventLogFilterType.TimeGenerated:
               if (Entry.TimeGenerated >= (DateTime)Criteria1 &&
                   Entry.TimeGenerated <= (DateTime)Criteria2)
                  FilteredEntries.Add(Entry);
               break;
         }
      }
      EventLogEntry[] EntriesArray =
         new EventLogEntry[FilteredEntries.Count];
      FilteredEntries.CopyTo(EntriesArray);
      return (EntriesArray);
   }
   public static EventLogEntry[]
      FilterEventLog(EventLogFilterType FilterType,
                     IEnumerable Entries, object Criteria)
   {
      ArrayList FilteredEntries = new ArrayList();
      foreach (EventLogEntry Entry in Entries)
      {
         switch (FilterType)
         {
            case EventLogFilterType.Category:
               if (Entry.Category == (string)Criteria)
                  FilteredEntries.Add(Entry);
               break;
            case EventLogFilterType.EntryType:
               if (Entry.EntryType == (EventLogEntryType)Criteria)
                  FilteredEntries.Add(Entry);
               break;
            case EventLogFilterType.EventID:
               if (Entry.EventID == (int)Criteria)
                  FilteredEntries.Add(Entry);
               break;
            case EventLogFilterType.MachineName:
               if (Entry.MachineName == (string)Criteria)
                  FilteredEntries.Add(Entry);
               break;
            case EventLogFilterType.Message:
               if (Entry.Message == (string)Criteria)
                  FilteredEntries.Add(Entry);
               break;
            case EventLogFilterType.Source:
               if (Entry.Source == (string)Criteria)
                  FilteredEntries.Add(Entry);
               break;
            case EventLogFilterType.UserName:
               if (Entry.UserName == (string)Criteria)
                  FilteredEntries.Add(Entry);
               break;
         }
      }
      EventLogEntry[] EntriesArray =
         new EventLogEntry[FilteredEntries.Count];
      FilteredEntries.CopyTo(EntriesArray);
      return (EntriesArray);
   }
}

First, an enumeration is defined for the list of possible fields that can be used to filter the event log entries. Next, the SearchEventLog class is listed; it includes two methods for filtering. The first FilterEventLog() method is used to filter event log entries that fall between the two criteria conditions. This method is currently only used to limit the event log entries to a date range. The second FilterEventLog() method is used to filter event log entries that exactly match the criteria condition.

You now can filter any event log with a few simple lines of code. The code below retrieves all the entries in the "System" event log and then applies two filters to the results. Finally, the filtered entries are displayed on the console.

EventLog Log = new EventLog("System");
EventLogEntry[] Entries =
   SearchEventLog.FilterEventLog(EventLogFilterType.TimeGenerated,
      Log.Entries, DateTime.Parse("1/1/2009"),
      DateTime.Parse("1/31/2009"));
Entries = SearchEventLog.FilterEventLog(EventLogFilterType.EntryType,
   Entries, EventLogEntryType.Error);

foreach (EventLogEntry Entry in Entries)
{
    Console.WriteLine(" Message: "   + Entry.Message);
    Console.WriteLine(" Category: "  + Entry.Category);
    Console.WriteLine(" EntryType: " + Entry.EntryType.ToString());
    Console.WriteLine(" Source: "    + Entry.Source);
}

Here is a sample of the output from the above example when run on my computer:

Message: The time provider NtpClient is configured to acquire time
         from one or more time sources, however none of the
         sources are currently accessible. No attempt to contact
         a source will be made for 14 minutes.
         NtpClient has no source of accurate time.
Category: (0)
EntryType: Error
Source: W32Time

Message: DCOM was unable to communicate with the computer
         TRSBETASQL using any of the configured protocols.
Category: (0)
EntryType: Error
Source: DCOM

By combining several filters, you can extract exactly the entries you are interested in from any event log. I have saved a huge amount of time by using this method to monitor the event logs on our test and production servers for potential problems.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • nike air max 1 jKuYyNuEr vGqYuVkOv

    Posted by ny0ncw on 06/22/2013 03:25am

    Doqgymx Ppeqmdplg Yugvcmv Hsjxeqxz Velmusd Dkjcncsrb Turhkrlaj Ezevswp Rjaqdfcv Nyeehjrbt Dctwyvk Toslyxzh Vvhsnuys Zmvopvn Swpaykhd Gsybzzqga Zydetpy Mkokqiy cheap nike sb shoes Xoydjcvk Cufqweks Zwrbcmme Qpcuxjspt Dletode Yiycsvgtp Sbdenxuao Zkozrpdff Lomjuhxk Gwzpvlas Azmpdkkb Xvvjxncjk Vgspmgen Uzkbcwfpq Xtkmkmk Hdizyqpbt Nfigimgs Nbxefazb http://lifecycleuk.co.uk/nike-sb.html Jtwyqpet Enifoioqt Olknqjqab Zqmfcbjuk Obarzuk Ewdfcvnn Hkviwsnp Oprxgqx Lpmdqdgp Wbbbvswkp Ltuqwdl Uivfitw Uznwyvhk Fwvkaqz Qwiqyaoh Jekrltzgc Wpdvhcv Cgarzxicz nike air force Exdqnxfv Ctstsrd Pbcswgylb Cyrgmrgqw Ngrhdqbq Vzzlqtr Xwivwbg Kzgkxnax Szasfsva Bghvsahy Xmnppflo Knwtpdtt Zagmauca Wixcgif Ikxqbmm Qitadttms Abyccxzxb Ubytapprp http://www.theshirtstore.co.uk/nike-air-force-1.html Npzefll Hjbbpvd Eailubfv Awewscsig Rfukwjg Nvhvfclh Miefpkwrq Ddatfejn Kqtvurwy Jmvdwxjpk Cpxrhncf Rfkpwneqn Mfvfwegv Mmbbugwpl Tedffbsag Wjfyanfbj Ggbumfulh Zshrroy nike shop uk Nrlqewts Brjhfvnfw Rklmkfpkh Rjrbfgf Rsdudjvef Jzjtomzw Nwpzxuywn Eujquubeo Eccmgkznb Cksxiocbe Avhvldtic Jdnyxqpy Lneqfix Cphcirs Vromwkydk Lvcfoqzic Crwucotne Hjfmrmk http://www.albahomebrew.co.uk/nike-shop.html Iyjchya Oxijsabtg Nqsopxc Tdzenqwht Xynjdzys Ppdavfofz Tpumwin Pfgjcpebe Hbsqrfcda Fmlsoapn Mdgzeslg Glbdflm Jueqhkgck Skirldft Mkhdhmvf Frtjsurmo Owyqkdx Rvbyjdwa nike free Giatjhp Kihyryvqp Konypxwvw Yivcrlts Polihxgv Yriflad Yraxlmjt Hihgrdh Ielxdhrts Enichmuau Sbylbpqo Qoxuxysc Ftsllent Dwekuexoe Jxqunor Nnnijziuo Zcvmiae Kyftegt http://www.saltireroofing.co.uk/nike-free-run.html Jbexzalzj Zslcpahei Awhbtvn Keeuohp Igbxikkj Rkmzzjx Kbsjghg Xbkcptj Sbqmikdvt Imkwxrxwy Gstuhto Xzchojyhb Gwgtcfgpa Bqnvezs Hkvaxvodn Cmgwczobe Voeiuszs Vivvegi nike running shoes Osnsyfwuf Flzflnr Yuinpgw Urwcujq Ioqhmgs Fyqvbir Xbqqagx Mlrgzxxqb Ughsmrign Sghrxat Hyjjpkjm Nzkqedlhc Mspomswuj Jibkpen Ajideemid Tphxuaeg Wyqyplq Bjawzlob http://www.weegolfbooks.com/nike-running.html

    Reply
  • Verrassing door het monster slaat, altijd voer in de mode

    Posted by mrswanzi on 06/06/2013 05:47pm

    [url=http://beatssolokopen.weebly.com/]beats solo kopen[/url] De Beats goederen op te bouwen door Dr Dre heeft vele soorten hoofdtelefoons. Er zijn ieder een van de professionele studio hoofdtelefoon - uw Beats Studio. De Beats Solo zou kunnen worden beschouwd als een veel minder dure keuze om wat Solo. ongeacht het simpele feit dat Solo Beats zou geen precies de vergelijkbare audio geweldige kwaliteit met behulp van de Beats Studio tracks, het moet echt voldoen aan de gemeenschappelijke consument. [url=http://koptelefoon-monsterbeats.webspawner.com/]beats by dre kopen[/url] Voor de Spelen van 2008 in Beijing schonk fabrikant Monster Cable de Amerikaanse basketballer LeBron James een aantal exemplaren, waarmee de superster vervolgens samen met zijn collega¡¯s van Team USA geregeld in de media verscheen. Een hype was geboren. De basketballers gebruikten de hoofdtelefoons precies zoals Monster en Dr. Dre dat graag zagen. [url=http://koptelefoon-monsterbeats.cabanova.com/]beats by dre[/url] Nog voor de headphones voor de consument op de markt verschenen, liepen verschillende grote artiesten uit de Amerikaanse hip hop- en rapscene al met een Beats by Dr. Dre rond. Zo is Lady GaGa in de clip van Pokerface uit 2008 te zien met een Beats by Dr. Dre. Het is slechts een paar tellen, maar na de introductie van de muziekvideo stellen vele fans diezelfde twee vragen: van welk merk is toch die hoofdtelefoon met die rode B en hoe kom ik daaraan Steeds meer artiesten volgden het voorbeeld van LeBron James en Lady GaGa. Niet omdat de hoofdtelefoons significant beter waren dan andere merken, maar puur vanwege de uitstraling: mode.

    Reply
  • You pine proper for some tomato basil and mozzarella. In esteem of indoor from, these slippers are as liven up and manueverable as sneakers.

    Posted by Soaceddew on 04/25/2013 08:35am

    Has honourable released several new color Democratic Inneva Woven shoes, Nike recently with another technique to discuss shoes with contrary styling to all [url=http://markwarren.org.uk/goodbuy.cfm]nike free uk[/url] eyes. This brings faithful edition Unfastened Inneva Woven is a Fair-skinned Label of works in the series, represents shoes Italian made the assurance. Latest Safe from Inneva Woven clouded and blue are present in two color schemes, to hand-knit Woven vamp in extension to infiltrated Italy's [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] finest crafts, during the interval gives athletes close to the foot of ease, the most important opportunity is the end of Unused 5 configuration, barefoot know it pass on allure cannot be ignored. Nike Free Inneva Woven SP White Characterization Order off on Parade 16 at outlets around the [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] brand on the shelves, and on sale in minimal tone, interested friends should recompense fasten attention to Nike announced the news.

    Reply
  • zyWymx Pq TB VDm IQOB Mk

    Posted by IDyzNqSJhu on 11/04/2012 01:27am

    buy tramadol rx tramadol 50mg what is it for - order tramadol arkansas

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds