Tracking the Big Event: Part I

Interacting with the Event Log Is Easier than Ever

Class Act

Languages: VB

Technologies: .NET Framework | Event Logging

 

Tracking the Big Event: Part I

Interacting with the Event Log Is Easier than Ever

 

By Ken Getz

 

Learning about ASP.NET isn t enough to make you a master site developer you must also dig into the capabilities of the .NET Framework to take advantage of all that .NET has to offer. This column will poke and prod at various corners of the .NET Framework, and will attempt to both point out classes that you ll need every day, as well as those you aren t likely to notice unless someone points them out to you. The .NET Framework contains tons of useful classes, and this column will point out and discuss interesting and sometimes obscure tools and techniques.

 

Windows provides an event log that allows applications to keep track of events that occur as your system runs. Applications write information into the event log so you (or a system administrator) can investigate what s going on as the applications run and can trouble-shoot problems as they occur.

 

Interacting with the event log was probably quite difficult in previous versions of the development environments you used. In VB6, for example, you could write to the event log but couldn t read events from it. Even the writing functionality was limited. It s always been possible to use the Windows API to interact with the event log, but that s been a daunting task. In this two-part article, you ll learn how to read and write entries in the Windows event log, and even how to determine if some other application has written to the event log.

 

The .NET Framework makes working with the event log simple. By using members of the EventLog class, you can read and write entries by creating your own application logs or by working with the standard Application, System, and Security event logs. This first installment of Class Act demonstrates how simple it is to use the EventLog class and take advantage of the .NET Framework s support for working with event logs.

 

Note that the sample code-behind files provided with this article include code that imports the System.Diagnostics namespace:

 

Imports System.Diagnostics

 

If you want to avoid using full name references (such as System.Diagnostics.EventLog), you ll need to add this Imports statement to your own code, as well. If you re working with combined layout and code in the same aspx file, rather than with code-behind files, you ll need to include the appropriate directive at the top of the file, like this:

 

<%@ Import Namespace="System.Diagnostics" %>

 

Introducing Event Sources

If you look at the Event Viewer application (see FIGURE 1), you ll see that every item in every event log has an event source associated with it (the fourth column from the left, in the right-hand pane). Some application had to send the event log that information, and each entry keeps track of it. Often, the event source is the name of the application, but it can be any string, and the developer of the application chooses the string. When you create your own event-log entries, you ll need to supply your own event source, as well.

 


FIGURE 1: The Event Viewer application displays the event source for each event.

 

As shown in FIGURE 1, the Event Viewer application displays the event source for each event. You can t write to the event log without specifying the event source for each entry you write, and a specific event source is tied to a specific event log.

 

There are two ways you can register an event source: You can do it explicitly, by using the shared CreateEventSource method of the EventLog class; or implicitly, by writing an entry to an event log and specifying the source name at that time. No matter how you create the event source, you can delete it later by using the shared DeleteEventSource method of the EventLog class.

 

When you register an event source, the computer on which you ve created the event source registers it with the event log on that machine as a valid source of event log entries. The computer maintains that information in the system registry. Each event source can write to a single event log only, but an event log might have multiple sources writing to it. If you attempt to create multiple sources explicitly, on the same machine with the same name, you ll raise an exception even if they re writing to different logs. If you attempt to specify an event source and then write to an event log for which that event source hasn t been registered, you ll also trigger an exception. The tricky part of all this is that the event manager, under the covers, will register an event source with a particular event log the first time you attempt to write an entry to that log with the specific source. From then on, unless you delete the event source, you won t be able to write to any other event log using that source name. (Confused? I studied all this information for quite a while before it all made sense. The documentation is somewhat obtuse about all this.)

 

For example, imagine you write code like this (just about the simplest code you could write to add a new entry to the Application event log):

 

Dim el As New EventLog("Application")

el.Source = "Event Log Source"

el.WriteEntry("This is a new event log entry")

 

After running this code, the source name Event Log Source has been registered with the Application event log. Attempting to write to a different log using the same source name will fail and trigger an exception.

 

Managing Event Logs and Sources

The EventLog class provides a number of static (shared) methods you can use to manage event logs and sources. You ll generally use these shared methods (as opposed to the few instance methods) when working with event logs. As mentioned earlier, you can use the CreateEventSource method to create an event source and the DeleteEventSource method to delete one. Use the Exists method to determine if a particular event log exists, and the Delete method to delete an event log. Because multiple applications might be writing to the event log, you ll want to make sure no other sources are writing to the log before you delete it. If you need to determine whether an event source exists already, use the shared SourceExists method.

 

To create a new user-defined event log, call the CreateEventSource method again. When you call this method and specify the names of the event source and new event log, Windows will create the new log for you as it creates the new event source. Remember that every event source name must be associated with an event log. When Windows attempts to register the event source you specify and sees the associated event log doesn t exist, Windows creates the log for you. It is somewhat confusing that there s no method named CreateEventLog or any explicit way to create an event log.

 

Because each event source is associated with exactly one event log, you can use the shared LogNameFromSourceName method to retrieve the name of the log associated with an event source. To write an entry to the event log, you can use the WriteEntry method. (You ll find both a shared and an instance WriteEntry method. You can use the shared method when you don t need to create an EventLog object instance first. Perhaps you simply want to write an entry to the event log and move on to other tasks. If you find you need to work extensively with an event log, to perform more than one task, you may want to create your own EventLog class instance and work with it instead.) Finally, you can use the GetEventLogs method to retrieve an array of EventLog objects, each referring to one of the event logs.

 

Each of these methods allows you to specify a machine name as one of the parameters. If you don t specify, the method assumes you want to work with the event log on the current machine ( . ). If you do specify a machine name, the method will attempt to connect with the event log on the specified machine.

 


FIGURE 2: Use the ManageEventLogs.aspx page to test the shared methods of the EventLog class.

 

The sample page, ManageEventLogs.aspx (see FIGURE 2), allows you to interact with all the shared methods of the EventLog class. To retrieve a list of all existing logs on a specific machine, the page includes the following procedure:

 

Private Sub RefillListOfLogs( _

 ByVal lc As ListControl, _

 ByVal MachineName As String)

  ' Fill lc with a list of

  ' all the existing event logs.

  Dim log As EventLog

  Dim strLog As String

 

  lc.Items.Clear()

  For Each log In EventLog.GetEventLogs(MachineName)

    lc.Items.Add(log.LogDisplayName)

  Next

End Sub

 

Code called from the Fill List button calls the procedure, like this:

 

RefillListOfLogs(ddlLogList, txtMachine.Text)

 

The sample page allows you to specify an event source. Clicking the Check Source button displays whether the source exists (calling the SourceExists method) and the associated log if the source does exist (calling the LogNameFromSourceName method). This code is a modified version of the code in the sample page:

 

If EventLog.SourceExists(txtSource.Text, _

   txtMachine.Text) Then

  Dim strLogName As String

 

  strLogName = _

   EventLog.LogNameFromSourceName( _

   txtSource.Text, txtMachine.Text)

  lblSourceExists.Text = _

   String.Format("Source exists ({0})", strLogName)

Else

  lblSourceExists.Text = "Source doesn't exist."

End If

 

If the event source you specified does exist, you can click the Delete Source button to delete the event source, with code like this:

 

If EventLog.SourceExists(txtSource.Text, _

   txtMachine.Text) Then

  ' Delete the event source.

  EventLog.DeleteEventSource(txtSource.Text, _

  txtMachine.Text)

End If

 

Deleting an existing source can t really hurt because the next time any application calls WriteEntry to write an entry into the event log, the system will recreate the event source for you. Of course, it s possible that an application will make assumptions about the existence of an event source. It s probably best that you only delete event sources you ve created, just to be safe.

 

The sample page allows you to create a new event source and event log, via the following code:

 

Private Sub btnCreateSource_Click( _

 ByVal sender As System.Object, _

 ByVal e As System.EventArgs) _

 Handles btnCreateSource.Click

  EventLog.CreateEventSource( _

   txtCreateSourceName.Text, _

   txtCreateLogName.Text, txtMachine.Text)

End Sub

 

You can delete an existing event log, after selecting from the list of existing event logs in the DropDownList control, ddlEventLogsDelete, using code like this:

 

Private Sub btnDeleteLog_Click( _

 ByVal sender As System.Object, _

 ByVal e As System.EventArgs) _

 Handles btnDeleteLog.Click

  Dim strMachine As String = txtMachine.Text

  Dim strLog As String = _

   ddlEventLogsDelete.SelectedItem.Text

 

  If EventLog.Exists(strLog, strMachine) Then

    EventLog.Delete(strLog, strMachine)

  End If

End Sub

 

This procedure uses the Exists method of the EventLog class to check for the existence of the log before deleting it.

 

Properties of the EventLog Class

Besides the properties the EventLog class inherits from its base classes, you ll find it provides several useful properties as well. The Entries property returns a collection of EventLogEntry objects. The Log property allows you to set or retrieve the name of the event log associated with the EventLog object, and the LogDisplayName allows you to retrieve the friendly name associated with the event log. The MachineName property allows you to set or retrieve the machine on which to read or write events. By default, if you don t specify a machine name, you ll always be referring to the local computer, or . Finally, the Source property allows you to set or retrieve the event source associated with this log. If the source name isn t registered, Windows will register the event source as being associated with the particular event log when you first write to the event log.

 

The EventLog class also provides three instance methods (besides the ones it inherits from its parent objects): Clear, Close, and WriteEntry. The Clear method allows you to clear all the items from an event log. The Close method closes your connection with the event log and flushes any pending reads and writes. The WriteEntry method works just like the shared version of the same method, except for one thing: Because this method is a member of a particular instance, WriteEntry can write only to the log associated with the particular EventLog instance. (You ll see more about writing to the event log in Part II.)

 

The sample page, LogEntries.aspx (shown in FIGURE 3), retrieves the log entries from a specific log on a specific machine. Using the following code to retrieve the list of entries, the page fills a grid with log entries:

 

Private Sub RetrieveLogEntries()

  Dim el As New EventLog()

  el.Log = ddlEventLogs.SelectedItem.Text

  el.MachineName = txtMachine.Text

  dgdEntries.DataSource = el.Entries

  dgdEntries.DataBind()

End Sub

 

The code uses the Entries property of an EventLog instance to retrieve its list. Beware that you probably won t have the rights to retrieve the security log from a remote machine.

 


FIGURE 3: Retrieve log entries from any log on any machine.

 

Each EventLogEntry item returned by the Entries property of the EventLog instance provides a number of interesting properties, including the Source, TimeWritten, and Message properties shown in FIGURE 3. You ll want to investigate the documentation to check out the other properties, including EventID, Index, and MachineName.

 

In Part II, the conclusion of this article takes a look at writing to the event log, handling localized text, and reacting to events that occur as text gets written to the event log.

 

This article is the first of many such articles digging into classes in the .NET Framework. In each installment I hope to find a class that s interesting and useful and poke around in it enough to create an example and describe the important bits. If there s a class in which you re interested, or some functionality you can t find but are certain must exist, please let me know. I ll do what I can to figure it out and present it here. It s a big .NET world out there, and there are thousands of classes to investigate. We won t get to all of them within our lifetimes, but I hope you ll find this excavation useful and interesting.

 

The files referenced in this article are available for download.

 

Ken Getz is a senior consultant with MCW Technologies and splits his time between programming, writing, and training. He specializes in tools and applications written in Visual Studio .NET and Visual Basic. Ken is co-author of several books, including Access 2002 Developer s Handbook with Paul Litwin and Mike Gunderloy, Visual Basic Language Developer s Handbook with Mike Gilbert, and VBA Developer s Handbook with Mike Gilbert. Ken co-wrote the training materials for AppDev s ASP.NET, Access 97 and 2000, Visual Basic 5.0, and Visual Basic 6.0 classes. He frequently speaks at technical conferences and is a contributing editor for Microsoft Office Solutions magazine. You can reach Ken at mailto:[email protected].

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish