How to manage event logs by using Visual Basic .NET or Visual Basic 2005 (814564)



The information in this article applies to:

  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

For a Microsoft Visual C# .NET version of this article, see 815314.

SUMMARY

This step-by-step article describes how to access and customize Windows event logs by using Microsoft .NET Framework. You can interact with Windows event logs by using the EventLog class. You can use the EventLog class to do the following things:
  • Read from the existing logs.
  • Write entries to the event logs.
  • Create or delete event sources.
  • Delete logs.
  • Respond to log entries.
This article also describes how to create new logs while you create an event source.

back to the top

Requirements


The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
  • Microsoft .NET Framework
  • Microsoft Visual Basic .NET or Microsoft Visual Basic 2005

This article assumes that you are familiar with the following topics:
  • Microsoft Visual Basic .NET or Microsoft Visual Basic 2005 Syntax
  • Microsoft Visual Studio .NET or Microsoft Visual Studio 2005 Environment
  • Error handling in .NET Framework
back to the top

Find the Existing Logs on a Computer


You can find the existing logs on a computer by using the GetEventLogs shared method of the EventLog class. The GetEventLogs method searches for all event logs on the local computer, and then it creates an array of EventLog objects that contain the list. The following code example retrieves a list of logs on the local computer, and then displays the names of the logs in a console window:
      Dim remoteEventLogs() As EventLog

      'Gets logs on the local machine, give remote machine name to get the logs on the remote machine
      remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName)

      Console.WriteLine("Number of logs on computer: " & remoteEventLogs.Length)

      'Display the list of event logs
      Dim log As EventLog
      For Each log In remoteEventLogs
         Console.WriteLine("Log: " & log.Log)
      Next log
back to the top

Read and Write Logs to and from the Local and the Remote System


Read logs


To read an event log, use the Entries property of the EventLog class. The Entries property of the EventLog class is a collection of all the entries in the event log. The following code example demonstrates how to iterate through this collection, and how to read all the entries in the specified log:
      ' Log type can be Application, Security, System or any other custom log
      ' Select the log type you want to read
      Dim logtype As String = "Application"

      ' In the constructor of the eventlog, pass the log type and the computer name 
      ' from which you want to read the logs 
      Dim evtLog As New EventLog(logtype, System.Environment.MachineName)

      Dim lastlogtoshow As Integer = evtLog.Entries.Count
      If lastlogtoshow <= 0 Then
         Console.WriteLine("There are no event logs in the log : " & logtype)
         Exit Sub
      End If

      ' Read the last record in the specified log 
      Dim currentEntry As EventLogEntry
      Dim i As Integer
      ' Show Last 2 entries. You can similarly write the log to a file.
      For i = evtLog.Entries.Count - 1 To lastlogtoshow - 2 Step -1
         currentEntry = evtLog.Entries(i)
         Console.WriteLine("Event Id is : " & currentEntry.EventID)
         Console.WriteLine("Entry type is : " & currentEntry.EntryType.ToString())
         Console.WriteLine("Message is :  " & currentEntry.Message & vbCrLf)
      Next
      evtLog.Close()

Write Logs


To write an event log, use the WriteEntry method of the EventLog class. To write the event log successfully, make sure your application has write access for the log that it is writing to. For more information about the permissions that you must have to read and write in event logs, visit the following Microsoft Web site.

Security Ramification of Event Logs
http://msdn.microsoft.com/library/en-us/vbcon/html/vbconSecurityRamificationsOfEventLogs.asp
You must set the Source property on your EventLog component instance before you write entries to a log. When your component writes an entry, the system automatically verifies that the source you specified is registered with the event log that the component is writing to. The system then calls CreateEventSource if necessary. To write an event log, you must pass the machine name where the log resides. In the following code example, the MachineName property of the Environment class determines the name of the local machine:
      
  ' Check if the source exists 
      If Not EventLog.SourceExists("MySystemSource", System.Environment.MachineName) Then
         EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName)
      End If

      Dim evtLog As New EventLog("System", System.Environment.MachineName, "MySystemSource")

      'writing to system log, in the similar way you can write to other 
      'logs for which you have appropriate permissions to write
      evtLog.WriteEntry("warning is written to system log", EventLogEntryType.Warning, CInt(10001))
      Console.WriteLine("Log written to the system log.")
      evtLog.Close()
back to the top

Clear Logs


When an event log is full, it stops recording new event information or it begins to overwrite previous entries. If event recording stops, you can clear the log of existing entries and allow it to start recording events again. To clear event log entries, you must have administrator permissions for the computer that the log resides on. Call the Clear method on the EventLog component instance.

The following code example domonstrates how to clear a log:
      ' Create an EventLog instance and pass log name and MachineName on which the log resides
      Dim evtLog As New EventLog("Security", System.Environment.MachineName)
      evtLog.Clear()
      evtLog.Close()
back to the top

Create and Delete Custom Logs

Create the Custom Log

Use the CreateEventSource method to create your own custom event handler. Before you create the event log, use the SourceExists method to verify that the source you are using does not already exist, and then call CreateEventSource. If you try to create an event log that already exists, a System.ArgumentException error is thrown.

The following code example demonstrates how to create a custom log:
      ' Check if the log already exist
      If Not EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         ' Creating a new log
         EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName)
         Console.WriteLine("New event log created successfully.")
      End If

Delete the Custom Log

Use the Delete method of the EventLog class to delete the event log. More than one source may write to an event log. Therefore, before you delete a custom log, make sure that there are no other sources writing to that log.

The following code example demonstrates how to delete a custom log:
      Dim logName As String = "MyNewLog"

      If EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName)
         EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName)
         EventLog.Delete(logName, System.Environment.MachineName)

         Console.WriteLine(logName & " deleted.")
      End If
back to the top

Receive Event Notifications

You can receive an event notification when an entry is written to a particular log. To do this, implement the EntryWritten event handler for the EventLog instance. Also, set the EnableRaisingEvents property to true.

The following code example demonstrates how to receive event notifications:
      If Not EventLog1.SourceExists("MySource", System.Environment.MachineName) Then
         EventLog1.CreateEventSource("MySource", "Application", System.Environment.MachineName)
         Console.WriteLine("CreatingEventSource")
      End If

      'Enable EnableRaisingEvents to true
      EventLog1.Log = "Application"
						EventLog1.EnableRaisingEvents = True
      EventLog1.WriteEntry("MySource", "EntryWritten event is fired", EventLogEntryType.Information)
   End Sub
Note You can only receive event notifications when entries are written on the local computer. You cannot receive notifications for entries written on remote computers.

back to the top

Complete Code Listing

Imports System.Diagnostics
Imports System.Security
Imports System.ComponentModel
Imports System.IO

Public Class Form1
   Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

   Public Sub New()
      MyBase.New()

      'The Windows Form Designer requires this call.
      InitializeComponent()

      'Add any initialization after the InitializeComponent() call

   End Sub

   'Form overrides dispose to clean up the component list.
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      MyBase.Dispose(disposing)
   End Sub

   'Required by the Windows Form Designer
   Private components As System.ComponentModel.IContainer

   'NOTE: The Windows Form Designer requires the following procedure
   'It can be modified using the Windows Form Designer.  
   'Do not modify it using the code editor.
   Friend WithEvents EventLog1 As System.Diagnostics.EventLog
   Friend WithEvents btnListLog As System.Windows.Forms.Button
   Friend WithEvents btnReadLog As System.Windows.Forms.Button
   Friend WithEvents btnWriteLog As System.Windows.Forms.Button
   Friend WithEvents btnClearLog As System.Windows.Forms.Button
   Friend WithEvents btnCreateLog As System.Windows.Forms.Button
   Friend WithEvents btnDeleteLog As System.Windows.Forms.Button
   Friend WithEvents btnRecNotice As System.Windows.Forms.Button
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
      Me.btnReadLog = New System.Windows.Forms.Button()
      Me.btnWriteLog = New System.Windows.Forms.Button()
      Me.btnClearLog = New System.Windows.Forms.Button()
      Me.btnCreateLog = New System.Windows.Forms.Button()
      Me.btnDeleteLog = New System.Windows.Forms.Button()
      Me.btnRecNotice = New System.Windows.Forms.Button()
      Me.EventLog1 = New System.Diagnostics.EventLog()
      Me.btnListLog = New System.Windows.Forms.Button()
      CType(Me.EventLog1, System.ComponentModel.ISupportInitialize).BeginInit()
      Me.SuspendLayout()
      '
      'btnReadLog
      '
      Me.btnReadLog.Location = New System.Drawing.Point(48, 54)
      Me.btnReadLog.Name = "btnReadLog"
      Me.btnReadLog.Size = New System.Drawing.Size(152, 24)
      Me.btnReadLog.TabIndex = 0
      Me.btnReadLog.Text = "Read Event Logs"
      '
      'btnWriteLog
      '
      Me.btnWriteLog.Location = New System.Drawing.Point(48, 86)
      Me.btnWriteLog.Name = "btnWriteLog"
      Me.btnWriteLog.Size = New System.Drawing.Size(152, 24)
      Me.btnWriteLog.TabIndex = 1
      Me.btnWriteLog.Text = "Write Event Logs"
      '
      'btnClearLog
      '
      Me.btnClearLog.Location = New System.Drawing.Point(48, 118)
      Me.btnClearLog.Name = "btnClearLog"
      Me.btnClearLog.Size = New System.Drawing.Size(152, 24)
      Me.btnClearLog.TabIndex = 2
      Me.btnClearLog.Text = "Clear Logs"
      '
      'btnCreateLog
      '
      Me.btnCreateLog.Location = New System.Drawing.Point(48, 150)
      Me.btnCreateLog.Name = "btnCreateLog"
      Me.btnCreateLog.Size = New System.Drawing.Size(152, 24)
      Me.btnCreateLog.TabIndex = 3
      Me.btnCreateLog.Text = "Create Custom Log"
      '
      'btnDeleteLog
      '
      Me.btnDeleteLog.Location = New System.Drawing.Point(48, 182)
      Me.btnDeleteLog.Name = "btnDeleteLog"
      Me.btnDeleteLog.Size = New System.Drawing.Size(152, 24)
      Me.btnDeleteLog.TabIndex = 4
      Me.btnDeleteLog.Text = "Delete Custom Log"
      '
      'btnRecNotice
      '
      Me.btnRecNotice.Location = New System.Drawing.Point(48, 214)
      Me.btnRecNotice.Name = "btnRecNotice"
      Me.btnRecNotice.Size = New System.Drawing.Size(152, 24)
      Me.btnRecNotice.TabIndex = 5
      Me.btnRecNotice.Text = "Receive Event Notifications"
      '
      'EventLog1
      '
      Me.EventLog1.EnableRaisingEvents = True
      Me.EventLog1.Log = "Application"
      Me.EventLog1.MachineName = System.Environment.MachineName
      Me.EventLog1.SynchronizingObject = Me
      '
      'btnListLog
      '
      Me.btnListLog.Location = New System.Drawing.Point(48, 22)
      Me.btnListLog.Name = "btnListLog"
      Me.btnListLog.Size = New System.Drawing.Size(152, 24)
      Me.btnListLog.TabIndex = 6
      Me.btnListLog.Text = "List Event Logs"
      '
      'Form1
      '
      Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
      Me.ClientSize = New System.Drawing.Size(256, 266)
      Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnListLog, Me.btnRecNotice, Me.btnDeleteLog, Me.btnCreateLog, Me.btnClearLog, Me.btnWriteLog, Me.btnReadLog})
      Me.Name = "Form1"
      Me.Text = "Form1"
      CType(Me.EventLog1, System.ComponentModel.ISupportInitialize).EndInit()
      Me.ResumeLayout(False)

   End Sub

#End Region

   Private Sub btnReadLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadLog.Click

      'logType can be Application, Security, System or any other Custom Log
      Dim logType As String = "Application"


      'In this case the EventLog constructor is passed a string variable for the log name and 
      'second argument mention the computer name from which you want to read the logs 
      'that you have appropriate permissions for
      Dim ev As New EventLog(logType, System.Environment.MachineName)

      Dim LastLogToShow As Integer = ev.Entries.Count
      If LastLogToShow <= 0 Then
         Console.WriteLine("No Event Logs in the Log :" & logType)
         Exit Sub
      End If

      ' read the last 2 records in the specified log 
      Dim i As Integer
      For i = ev.Entries.Count - 1 To LastLogToShow - 2 Step -1
         Dim CurrentEntry As EventLogEntry = ev.Entries(i)

         Console.WriteLine("Event ID : " & CurrentEntry.EventID)
         Console.WriteLine("Entry Type : " & CurrentEntry.EntryType.ToString())
         Console.WriteLine("Message :  " & CurrentEntry.Message & vbCrLf)
      Next

      ev.Close()

      ' Similarly, you can loop through all the entries in the log by using
      ' the entries collection, as shown in the following commented code.
      ' For Each entry In ev.Entries

      ' Next
   End Sub

   Private Sub btnWriteLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWriteLog.Click
      ' When writing to an event log, you must pass the machine name where 
      ' the log resides.  Here the MachineName Property of the Environment class 
      ' is used to determine the name of the local machine.  Assuming you have 
      ' the appropriate permissions, it is also easy to write to event logs on 
      ' other machines.

      'Check if the Source exists 
      If Not EventLog.SourceExists("MySystemSource", System.Environment.MachineName) Then
         EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName)
      End If
      Dim ev As New EventLog("System", System.Environment.MachineName, "MySystemSource")

      'Writing to system log, in the similar way you can write to other 
      'logs that you have appropriate permissions to write to
      ev.WriteEntry("Warning is written to system Log", EventLogEntryType.Warning, CInt(10001))
      MessageBox.Show("Warning is written to System Log")
      ev.Close()

   End Sub

   Private Sub btnClearLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearLog.Click
      ' Create an EventLog instance and pass the log name and MachineName on which the log resides.
      Dim ev As New EventLog("Security", System.Environment.MachineName)
      ev.Clear()
      ev.Close()
   End Sub

   Private Sub btnCreateLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateLog.Click
      'Create the source, if it does not already exist.
      If Not EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         'Creating a new log
         EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName)
         Console.WriteLine("CreatingEventSource")
      End If
   End Sub

   Private Sub btnDeleteLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteLog.Click
      Dim logName As String = "MyNewLog"

      If EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName)
         EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName)
         EventLog.Delete(logName, System.Environment.MachineName)

         Console.WriteLine(logName & " deleted.")
      End If

   End Sub


   Private Sub btnRecNotice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecNotice.Click
      ' Create the source if it does not already exist.
      If Not EventLog1.SourceExists("MySource", System.Environment.MachineName) Then
         EventLog1.CreateEventSource("MySource", "Application", System.Environment.MachineName)
         Console.WriteLine("CreatingEventSource")
      End If

      'Enable EnableRaisingEvents to true
      EventLog1.Log = "Application"
						EventLog1.EnableRaisingEvents = True
      EventLog1.WriteEntry("MySource", "EntryWritten event is fired", EventLogEntryType.Information)
   End Sub

   Private Sub EventLog1_EntryWritten(ByVal sender As Object, ByVal e As System.Diagnostics.EntryWrittenEventArgs) Handles EventLog1.EntryWritten
      If e.Entry.Source = "MySource" Then
         Console.WriteLine("Entry written by my app. Message: " & e.Entry.Message)
      End If
   End Sub

   Private Sub btnListLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListLog.Click
      Dim remoteEventLogs() As EventLog
      'Gets logs on the local machine, give remote machine name to get the logs on the remote machine
      remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName)

      Console.WriteLine("Number of logs on computer: " & remoteEventLogs.Length)

      Dim log As EventLog
      For Each log In remoteEventLogs
         Console.WriteLine("Log: " & log.Log)
      Next log
   End Sub
End Class

Note You must change the code in Visual Basic 2005. By default, Visual Basic creates two files for the project when you create a Windows Forms project. If the form is named Form1, the two files that represent the form are named Form1.vb and Form1.Designer.vb. You write the code in the Form1.vb file. The Windows Forms Designer writes the code in the Form1.Designer.vb file. The Windows Forms Designer uses the partial keyword to divide the implementation of Form1 into two separate files. This behavior prevents the designer-generated code from being interspersed with your code.

For more information about the new Visual Basic 2005 language enhancements, visit the following Microsoft Developer Network (MSDN) Web site: For more information about partial classes and the Windows Forms Designer, visit the following MSDN Web site: back to the top

Verify Results

To verfiy your results, follow these steps:
  1. Create a new Windows Application by using Visual Basic .NET or Visual Basic 2005.

    By default, Form1.vb is created.
  2. Replace the code in Form1.vb with the code in the "Complete Code Listing" section of this article.
  3. On the Debug menu, click Start to run the application.
  4. Perform actions on Form1.vb.
  5. To verify the result, open Server Explorer. To do this, click Server Explorer on the View menu.
  6. Expand the Servers node, and then expand Your Computer Name.
  7. Under Your Computer Name, expand Event Logs.

    Note The Servers node of Server Explorer is not available in Visual Basic .NET Academic Edition. You can use Windows Event Viewer to view the results of your application.
  8. Use Server Explorer to verify that all the steps in this procedure are performed correctly.
back to the top

REFERENCES

For more information, visit the following Microsoft Web site:

EventLog Class
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemDiagnosticsEventLogClassTopic.asp

back to the top

Modification Type:MinorLast Reviewed:10/3/2006
Keywords:kbvs2005swept kbvs2005applies kbEventService kbnetwork kbManaged kbProgramming kbEventLog kbHOWTOmaster KB814564 kbAudDeveloper