.NET Tip: Searching System Event Logs for Valuable Info

One of the more tedious tasks a system administrator has to do is review the system event logs using the Event Viewer. These logs can provide valuable information, but manually finding the worthwhile details in them can be difficult. Luckily, .NET provides some easy, automated ways to read and search event logs.

This tip creates a console application that reads a log looking for this type of message:

Login failed for user 'sa'. [CLIENT: 255.255.255.255]

The 255.255.255.255 is a network address that is attempting to gain access to SQL Server. These events are logged as Failure Audit events in the Application log, and they seem to come from particular IP addresses. The goal is to detect when one of these occurs and to use the hardware firewall to blacklist the source IP address. However, scanning through the event log to find the addresses is a job better done by the computer.

Although the example application is a console application, you could change it into a service that monitors the log for particular entries on some set interval. You then could send the entry to an administrator via e-mail. Most administrators respond much better reactively than proactively, simply because there are too many things to watch in a large server farm.

The code for an application that reads the event log is simple:

using System;
using System.Diagnostics;
using System.Collections;

namespace LogScanner
{
   /// <summary>
   /// Application to scan system log for a particular message.
   /// </summary>
   class Executable
   {
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main(string[] args)
      {
         string address;
         int startPos, endPos;
         EventLog appLog = new EventLog("Application");
         Hashtable ipAddresses = new Hashtable();
         foreach (EventLogEntry e in appLog.Entries)
         {
            if (e.Message.IndexOf("Login failed for user 'sa'.")
                >= 0)
            {
               startPos = e.Message.IndexOf("[") + 9;
               endPos = e.Message.IndexOf("]", startPos);
               address = e.Message.Substring(startPos, endPos -
                                             startPos - 1);
               if (!ipAddresses.ContainsKey(address.ToString()))
               {
                  Console.WriteLine("Found " + address + ".");
                  ipAddresses.Add(address.ToString(),
                                  address.ToString());
               }
            }
         }
         appLog.Close();
      }
   }
}

First, the application creates an instance of System.Diagnostics.EventLog to read the built-in Application log. If you’ve created your own log, you can specify the name of that log as an argument. Next, the program creates a hashtable for the addresses it finds. In my case, I get a whole series of attempts from the same address, but I want only one instance of the address to be displayed. The hashtable lets me quickly store the address and add a new address only if it doesn’t match.

The application then loops through the Entries collection of the log and reads the Message property. You also can look at properties such as the error number, the date/time, and so forth to help you find the messages you’re looking for. In the case of a service, it would make sense to store the last event entry that your service read and then look for entries only after that time. Otherwise, you’ll duplicate your previous results.

Finally, the program looks at the Message property to see if it contains the target message. If so, it extracts the network address (between opening and closing square brackets) and adds it to the hashtable, if it’s not already there. It also dumps out the address to the console so that the user can see the address immediately. The application finishes up by closing the application log object. If you were doing this as a service, you might replace the Console.WriteLine with a block of code at the end that e-mails the administrator the addresses that were found.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read