Reading in the Event log

hese are two functions designed to demonstrate how to read the event log in VB.NET. The first outputs information about all entries in all logs to the debug window. The second gets the last entry for the specified event log (or the Application log if no log is specified). These functions read from the event logs on the local machine, but you can read from any machine on the network, if the logged on use has permission, by passing the machine name to EventLog.GetEventLogs



Imports System.Diagnostics

 Public Sub ListEventLog()
        'outputs info about all entries for all event logs

        Dim strValue As String
        Dim objLogs() As EventLog

        Dim objEntry As EventLogEntry
        Dim objLog As EventLog

        'this uses local machine
        'you can pass machine name to constrcutor
        'to use a different machine
        objLogs = EventLog.GetEventLogs()

        For Each objLog In objLogs
            Debug.WriteLine(objLog.LogDisplayName & " event log")
            For Each objEntry In objLog.Entries
                With objEntry
                    Debug.WriteLine("Source: " & .Source & " Time: " & .TimeGenerated.ToString & " Message: " & .Message)
                End With
            Next
        Next

    End Sub
    Public Function LastLogEntry(Optional ByVal LogName As String = "Application") As String
        'gets message for last entry in specified log
        Dim strValue As String
        Dim objLogs() As EventLog

        Dim objEntry As EventLogEntry
        Dim objLog As EventLog
        objLogs = EventLog.GetEventLogs()

        For Each objLog In objLogs
            If objLog.LogDisplayName = LogName Then Exit For

        Next
        If Not objLog Is Nothing Then Return objLog.Entries(objLog.Entries.Count - 1).Message

    End Function