Write Entry to Eventlog using VB.NET


Are you a VB.NET programmer who’s ever looked through the windows eventlog (eventvwr.exe) thinking to yourself “How can I get my program to write events to the eventlog”? Here’s how:

Public Function WriteToEventLog(ByVal Entry As String, Optional ByVal AppName As String = "VB.NET Application", _
Optional ByVal EventType As EventLogEntryType = EventLogEntryType.Information, Optional ByVal LogName As String = _
"Application") As Boolean

Dim objEventLog As New EventLog

Try
'Register the App as an Event Source
If Not objEventLog.SourceExists(AppName) Then

objEventLog.CreateEventSource(AppName, LogName)
End If

objEventLog.Source = AppName

'WriteEntry is overloaded; this is one
'of 10 ways to call it
objEventLog.WriteEntry(Entry, EventType)
Return True
Catch Ex As Exception
Return False

End Try
End Function

The function WriteToEventLog has 1 parameter (entry to write to event log) with 3 other optional parameters specifying the Application Name, Event Type raised (Information, Warning, Critical) and the logname (whether the entry is written to Application, System, or other log within the event log).

I find this very useful especially in very large applications where writing an external log (besides .txt or .log files) becomes tedious. Writing entries into the event log is really create when you’re writing windows services also.

Hope this helps, please feel free to send me an email if you have any questions.

Advertisements

One thought on “Write Entry to Eventlog using VB.NET

  1. This Very Helpfull thread, but the problem that the compiler shows an worning when using this command:
    If Not objEventLog.SourceExists(AppName) Then
    objEventLog.CreateEventSource(AppName, LogName)
    End If

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s