Microsoft KB Archive/814564

= How to manage event logs by using Visual Basic .NET or Visual Basic 2005 =

Article ID: 814564

Article Last Modified on 11/14/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-





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



IN THIS TASK
 * Summary
 * Requirements
 * Find the Existing Logs on a Computer
 * Read and Write Logs to and from the Local and the Remote System
 * Clear Logs
 * Create and Delete Custom Logs
 * Receive Event Notifications
 * Complete Code Listing
 * Verify Results
 * References



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(&quot;Number of logs on computer: &quot; & remoteEventLogs.Length)

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

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 = &quot;Application&quot;

' 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(&quot;There are no event logs in the log : &quot; & 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(&quot;Event Id is : &quot; & currentEntry.EventID) Console.WriteLine(&quot;Entry type is : &quot; & currentEntry.EntryType.ToString) Console.WriteLine(&quot;Message is : &quot; & 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://msdn2.microsoft.com/en-us/library/4xz6w79h(vs.71).aspx

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(&quot;MySystemSource&quot;, System.Environment.MachineName) Then EventLog.CreateEventSource(&quot;MySystemSource&quot;, &quot;System&quot;, System.Environment.MachineName) End If

Dim evtLog As New EventLog(&quot;System&quot;, System.Environment.MachineName, &quot;MySystemSource&quot;)

'writing to system log, in the similar way you can write to other 'logs for which you have appropriate permissions to write evtLog.WriteEntry(&quot;warning is written to system log&quot;, EventLogEntryType.Warning, CInt(10001)) Console.WriteLine(&quot;Log written to the system log.&quot;) 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(&quot;Security&quot;, System.Environment.MachineName) evtLog.Clear evtLog.Close back to the top

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(&quot;MyOldSource&quot;, System.Environment.MachineName) Then ' Creating a new log EventLog.CreateEventSource(&quot;MyOldSource&quot;, &quot;MyNewLog&quot;, System.Environment.MachineName) Console.WriteLine(&quot;New event log created successfully.&quot;) 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 = &quot;MyNewLog&quot;

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

Console.WriteLine(logName & &quot; deleted.&quot;) 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(&quot;MySource&quot;, System.Environment.MachineName) Then EventLog1.CreateEventSource(&quot;MySource&quot;, &quot;Application&quot;, System.Environment.MachineName) Console.WriteLine(&quot;CreatingEventSource&quot;) End If

'Enable EnableRaisingEvents to true EventLog1.Log = &quot;Application&quot; EventLog1.EnableRaisingEvents = True EventLog1.WriteEntry(&quot;MySource&quot;, &quot;EntryWritten event is fired&quot;, 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


 * 1) Region &quot; Windows Form Designer generated code &quot;

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  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 = &quot;btnReadLog&quot; Me.btnReadLog.Size = New System.Drawing.Size(152, 24) Me.btnReadLog.TabIndex = 0 Me.btnReadLog.Text = &quot;Read Event Logs&quot; '     'btnWriteLog '     Me.btnWriteLog.Location = New System.Drawing.Point(48, 86) Me.btnWriteLog.Name = &quot;btnWriteLog&quot; Me.btnWriteLog.Size = New System.Drawing.Size(152, 24) Me.btnWriteLog.TabIndex = 1 Me.btnWriteLog.Text = &quot;Write Event Logs&quot; '     'btnClearLog '     Me.btnClearLog.Location = New System.Drawing.Point(48, 118) Me.btnClearLog.Name = &quot;btnClearLog&quot; Me.btnClearLog.Size = New System.Drawing.Size(152, 24) Me.btnClearLog.TabIndex = 2 Me.btnClearLog.Text = &quot;Clear Logs&quot; '     'btnCreateLog '     Me.btnCreateLog.Location = New System.Drawing.Point(48, 150) Me.btnCreateLog.Name = &quot;btnCreateLog&quot; Me.btnCreateLog.Size = New System.Drawing.Size(152, 24) Me.btnCreateLog.TabIndex = 3 Me.btnCreateLog.Text = &quot;Create Custom Log&quot; '     'btnDeleteLog '     Me.btnDeleteLog.Location = New System.Drawing.Point(48, 182) Me.btnDeleteLog.Name = &quot;btnDeleteLog&quot; Me.btnDeleteLog.Size = New System.Drawing.Size(152, 24) Me.btnDeleteLog.TabIndex = 4 Me.btnDeleteLog.Text = &quot;Delete Custom Log&quot; '     'btnRecNotice '     Me.btnRecNotice.Location = New System.Drawing.Point(48, 214) Me.btnRecNotice.Name = &quot;btnRecNotice&quot; Me.btnRecNotice.Size = New System.Drawing.Size(152, 24) Me.btnRecNotice.TabIndex = 5 Me.btnRecNotice.Text = &quot;Receive Event Notifications&quot; '     'EventLog1 '     Me.EventLog1.EnableRaisingEvents = True Me.EventLog1.Log = &quot;Application&quot; Me.EventLog1.MachineName = System.Environment.MachineName Me.EventLog1.SynchronizingObject = Me     ' 'btnListLog '     Me.btnListLog.Location = New System.Drawing.Point(48, 22) Me.btnListLog.Name = &quot;btnListLog&quot; Me.btnListLog.Size = New System.Drawing.Size(152, 24) Me.btnListLog.TabIndex = 6 Me.btnListLog.Text = &quot;List Event Logs&quot; '     '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 = &quot;Form1&quot; Me.Text = &quot;Form1&quot; CType(Me.EventLog1, System.ComponentModel.ISupportInitialize).EndInit Me.ResumeLayout(False)

End Sub


 * 1) 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 = &quot;Application&quot;

'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(&quot;No Event Logs in the Log :&quot; & 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(&quot;Event ID : &quot; & CurrentEntry.EventID) Console.WriteLine(&quot;Entry Type : &quot; & CurrentEntry.EntryType.ToString) Console.WriteLine(&quot;Message : &quot; & 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(&quot;MySystemSource&quot;, System.Environment.MachineName) Then EventLog.CreateEventSource(&quot;MySystemSource&quot;, &quot;System&quot;, System.Environment.MachineName) End If     Dim ev As New EventLog(&quot;System&quot;, System.Environment.MachineName, &quot;MySystemSource&quot;)

'Writing to system log, in the similar way you can write to other 'logs that you have appropriate permissions to write to     ev.WriteEntry(&quot;Warning is written to system Log&quot;, EventLogEntryType.Warning, CInt(10001)) MessageBox.Show(&quot;Warning is written to System Log&quot;) 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(&quot;Security&quot;, 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(&quot;MyOldSource&quot;, System.Environment.MachineName) Then 'Creating a new log EventLog.CreateEventSource(&quot;MyOldSource&quot;, &quot;MyNewLog&quot;, System.Environment.MachineName) Console.WriteLine(&quot;CreatingEventSource&quot;) 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 = &quot;MyNewLog&quot;

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

Console.WriteLine(logName & &quot; deleted.&quot;) 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(&quot;MySource&quot;, System.Environment.MachineName) Then EventLog1.CreateEventSource(&quot;MySource&quot;, &quot;Application&quot;, System.Environment.MachineName) Console.WriteLine(&quot;CreatingEventSource&quot;) End If

'Enable EnableRaisingEvents to true EventLog1.Log = &quot;Application&quot; EventLog1.EnableRaisingEvents = True EventLog1.WriteEntry(&quot;MySource&quot;, &quot;EntryWritten event is fired&quot;, 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 = &quot;MySource&quot; Then Console.WriteLine(&quot;Entry written by my app. Message: &quot; & 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(&quot;Number of logs on computer: &quot; & remoteEventLogs.Length)

Dim log As EventLog For Each log In remoteEventLogs Console.WriteLine(&quot;Log: &quot; & 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:

http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx

For more information about partial classes and the Windows Forms Designer, visit the following MSDN Web site:

http://msdn2.microsoft.com/en-us/library/ms171843.aspx

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.
 * 1) Replace the code in Form1.vb with the code in the &quot;Complete Code Listing&quot; section of this article.
 * 2) On the Debug menu, click Start to run the application.
 * 3) Perform actions on Form1.vb.
 * 4) To verify the result, open Server Explorer. To do this, click Server Explorer on the View menu.
 * 5) Expand the Servers node, and then expand Your Computer Name.
 * 6) 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.
 * 1) Use Server Explorer to verify that all the steps in this procedure are performed correctly.

back to the top

