Category Archives: VB.NET

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

'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.