Working with Event Logs


Instrument and debug a Windows service, a serviced component, a .NET Remoting object, and an XML Web service.

Event logging is the standard way in Windows for applications to leave records of their activities. You can easily monitor the behavior of an application by using the Event Viewer utility to analyze its messages in the event log. You can also view events from within the Visual Studio .NET environment. You can access event logs through the Server Explorer.

The Framework Class Library provides a set of classes that are designed to work with event logs. With the help of these classes, you can programmatically read from or write to the event logs. Programmatic access might even allow you to automate some of the administrative tasks associated with an application.

By default, three event logs are available: Application, Security, and System. Other applications or operating system components , such as Active Directory, might include other event logs. Table 9.7 lists the important members of the EventLog class.

Table 9.7. Important Members of the EventLog Class






Opens an event source so that an application can write event information.



Deletes an event log.



Disconnects this object from the actual event log.



Specifies whether the EventLog object receives notifications for the EntryWritten event.



Retrieves a collection of all entries in the event log.



This event is raised whenever an event is written to the local computer if the EnableRaisingEvents property is set to True .



Returns True if the requested event log exists.



Returns an array of all event logs on the computer.



Specifies the name of the log to read from or write to.



Specifies an event log's friendly name.



Retrieves the underlying event log name for the specified source name.



Specifies the name of the computer on which to read or write events.



Specifies the source to register and use when writing to an event log.



Finds whether a given event source exists.



Creates a new entry in the event log.


Security Issues A program must have administrative privileges to create an event log. This is especially important in the case of ASP.NET because the ASP.NET worker process runs under a low-privilege account. The easiest way to ensure that the ASP.NET worker process has sufficient privilege is to configure ASP.NET to use the system account rather than the machine account. Alternatively, you can use the .NET Framework's security facilities to grant permissions on an assembly-by-assembly basis. For more details on these topics, see Chapter 11, "Security Issues."


The Log Property Only the first eight characters of a Log name are significant. So an event log with the name StepByStep9-11 is the same as one with the name StepByStep9-12 .

Each application that is interested in interacting with an event log must register an event source with the log. When an event source is registered, its information is stored in the system registry and is available across application restarts.

The CreateEventSource method allows you to register an application with an event log. If the event log does not already exist, this method will create it for you.

The WriteEntry method of the EventLog object allows you to write messages to the event log specified by the event source. If you haven't called CreateEventSource , WriteEntry will create the event source for you.

You can write different types of messages (information, error, and so on) to an event log. These types are specified by the values in the EventLogEntryType enumeration.

The sample application in Step by Step 9.11 demonstrates how to create an event log, register an application with the event log, unregister an application with an event log, write to an event log, and delete an event log.


9.11 Creating and Writing to an Event Log

  1. Add a Visual Basic .NET Windows application project to the solution. Name the project StepByStep9-11 .

  2. Rename the Form1.vb form StepByStep9-11.vb . Switch to the code view of the form and modify all references to Form1 so that they refer to StepByStep9_11 instead.

  3. Place two GroupBox controls, two Label controls, one TextBox control ( txtMessage , with its MultiLine property set to True ), four Button controls ( btnCreate , btnRemoveSource , btnRemoveLog , and btnWrite ), one ComboBox control ( cbEventLogs ), and five RadioButton controls ( rbError , rbInformation , rbFailureAudit , rbSuccessAudit , and rbWarning ) on the form. Arrange the controls as shown in Figure 9.35.

    Figure 9.35. The StepByStep9_11 form uses the EventLog class to create an event log and write entries to it.

  4. Switch to the code view. Add this code to the top of the form's module:

     Imports System.Diagnostics 
  5. Add the following code directly after the Windows Form Designer Generated Code section:

     ' Create a member to hold EventLogEntryType Private eletEntryType As EventLogEntryType = _  EventLogEntryType.Error 
  6. Add a new method named PopulateLogNames and an event handler for the form's Load event:

     Private Sub PopulateLogNames()     cbEventLogs.Items.Clear()     ' Add eventlogs in to the combo box.     Dim el As EventLog     For Each el In EventLog.GetEventLogs()         cbEventLogs.Items.Add(el.Log)     Next End Sub Private Sub StepByStep9_11_Load(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles MyBase.Load     PopulateLogNames() End Sub 
  7. Add handlers for the Click events of the Button controls:

     Private Sub btnCreate_Click(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles btnCreate.Click     If cbEventLogs.Text <> "" Then         Dim strSourceName As String = _          "StepByStep9-11_" & cbEventLogs.Text         ' Check whether the Source already exists         If Not EventLog.SourceExists(_          strSourceName) Then             Try                 ' Create event source                 ' and the event log                 EventLog.CreateEventSource(_                  strSourceName, _                  cbEventLogs.Text)                 PopulateLogNames()                 MessageBox.Show(_                  "Created EventSource for " & _                  "Selected EventLog")             Catch ex As Exception                 MessageBox.Show(ex.Message)             End Try         Else             MessageBox.Show(_              "You already have an " & _               "EventSource attached", _              "Cannot Create EventSource")         End If     End If End Sub Private Sub btnRemoveSource_Click(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles btnRemoveSource.Click     If cbEventLogs.Text <> "" Then         Dim strSourceName As String = _          "StepByStep9-11_" & cbEventLogs.Text         If EventLog.SourceExists(strSourceName) Then             ' Delete the Event Source             EventLog.DeleteEventSource(strSourceName)             MessageBox.Show("Deleted the EventSource")         Else             MessageBox.Show(_              "There is no EventSource " & _              "for the EventLog")         End If     End If End Sub Private Sub btnRemoveLog_Click(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles btnRemoveLog.Click     Dim strLogName As String = _      cbEventLogs.Text.ToUpper()     ' Do not delete system created logs     If strLogName = "APPLICATION" Or _      strLogName = "SECURITY" Or _      strLogName = "SYSTEM" Then         Dim strMessage As String = _          "This program does not allow " & _          "deleting system" & _          "created event logs"         MessageBox.Show(strMessage, _          "Dangerous Operation")         Exit Sub     End If     ' If the log exists     If EventLog.Exists(cbEventLogs.Text) Then         ' Confirm deletion from user         Dim strMessage As String = "Are you sure?"         If (MessageBox.Show(strMessage, _          "Confirm Deletion", _          MessageBoxButtons.YesNo) = _          DialogResult.Yes) Then             Try                 ' Delete the Event Log                 EventLog.Delete(cbEventLogs.Text)                 PopulateLogNames()             Catch ex As Exception                 MessageBox.Show(ex.Message, _                  "Error Deleting EventLog")             End Try         End If     Else         MessageBox.Show("Event log does not exist", _          "Cannot Delete EventLog")     End If End Sub Private Sub btnWrite_Click(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles btnWrite.Click     If cbEventLogs.Text <> "" Then         Dim strSourceName As String = _          "StepByStep9-11_" & _          cbEventLogs.Text         ' If Source exists         If EventLog.SourceExists(strSourceName) Then             Try                 ' Write an entry into event log                 EventLog.WriteEntry(strSourceName, _                  txtMessage.Text, _                  eletEntryType)                 MessageBox.Show(_                  "Entry Written to the " & _                  "log Successfully")             Catch ex As Exception                 MessageBox.Show(ex.Message, _                  "Cannot Write to selected EventLog")             End Try         Else             MessageBox.Show("No such event source", _              "Event logging Failed")         End If     Else         MessageBox.Show(_          "Please Select a log to write to.")     End If End Sub 


    Deleting an Event Log You should use the Delete method to delete an event log cautiously. When an event log is deleted, all event sources that are registered with it are also deleted, so no application can continue writing to that log. Do not attempt to delete an event log created by Windows or any other important application; if you do, those applications might crash or behave in unexpected ways.

  8. Add code to handle the CheckedChanged events of the RadioButton controls:

     Private Sub rbError_CheckedChanged(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles rbError.CheckedChanged     eletEntryType = EventLogEntryType.Error End Sub Private Sub rbInformation_CheckedChanged(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles rbInformation.CheckedChanged     eletEntryType = EventLogEntryType.Information End Sub Private Sub rbWarning_CheckedChanged(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles rbWarning.CheckedChanged     eletEntryType = EventLogEntryType.Warning End Sub Private Sub rbFailureAudit_CheckedChanged(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles rbFailureAudit.CheckedChanged     eletEntryType = EventLogEntryType.FailureAudit End Sub Private Sub rbSuccessAudit_CheckedChanged(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles rbSuccessAudit.CheckedChanged     eletEntryType = EventLogEntryType.SuccessAudit End Sub 
  9. Set the project StepByStep9-11 as the startup project, and set the form as the start object for the project.

  10. Run the project. Enter a name in the ComboBox control to create a new event source and to connect that source to the event log. Then, from the combo box, select the log that you just created, enter a message in the message text box, and select the type of the message from the radio button options. Click the Write to Log button to write to the event log.

  11. To view the logged messages, navigate to the Server Explorer, expand the Servers node, and then select and expand the node corresponding to your computer. Right-click the Event Logs node and select Launch Event Viewer from the shortcut menu. Figure 9.36 shows a custom event log created with this application.

    Figure 9.36. You can use the Windows Event Viewer to view the contents of the event logs.


Security Log The Security log is read-only for all users.


MCAD. MCSD Training Guide (Exam 70-310. Developing XML Web Services and Server Components with Visual Basic. NET and the. NET Framework)
MCAD/MCSD Training Guide (70-310): Developing XML Web Services and Server Components with Visual Basic(R) .NET and the .NET Framework
ISBN: 0789728206
EAN: 2147483647
Year: 2002
Pages: 166 © 2008-2017.
If you may any questions please contact us: