Writing To Windows Event Log in Visual Basic.NET
Written By: Kevin Jordan
- 09 Mar 2006 -
Description: This simple application uses the EventLog class to create a form for adding custom messages to the system and application log.
The WriteToEvent Function
The WriteToEvent function is the key to this program. It uses the built in class EventLog to handle our input and push the results to the Windows event logs.
Public Function WriteToEventLog(ByVal Entry As String, _ ByVal AppName As String, ByVal EventType As EventLogEntryType, _ ByVal LogName As String) As Boolean
Start out by declaring the function. Every parameter will be a string except EventType which will use the eventLogEntryType class. The function will also return a Boolean value, 0 if the function fails and 1 if it is successful.
Dim objEventLog As New EventLog Try Return True Catch Ex As Exception Return False End Try
This is the basic structure of the function. After declaring the object objEventLog, it will try to execute a few command, if successful, it will return True, otherwise False will be returned. Within the Try portion we have the following:
If Not objEventLog.SourceExists(AppName) Then objEventLog.CreateEventSource(AppName, LogName) End If
What this does is checks to see if the Application source specified already exists. An event cannot be logged unless the application is recognized. If it has not been previously created, this segment of the code will do so.
objEventLog.Source = AppName objEventLog.WriteEntry(Entry, EventType)
Finally, the objEventLog.Source is set and the objEventLog.WriteEntry function is used to actually post the log.