Search code examples
vb.netoperating-systemevent-log

Reading Applications and services log


I want to read a custom event log which is stored under Applications and services log section in Windows Eventlog.

Unfortunately when calling the Log according to its naming properties I receive an error message that the log cannot be found.

Ulitmately I try read event details from events with a specific ID but first I need to able to access the log.

This is the code that I have so far:

Imports System
Imports System.Diagnostics.Eventing.Reader

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim query As New EventLog("Logname as per Properties", System.Environment.MachineName)
        Dim elEventEntry As System.Diagnostics.EventLogEntry

        Dim nmbr As Integer = query.Entries.Count

        MsgBox(nmbr)

    End Sub
End Class

This is the structure in the eventlog (I want to read the blue highlighted part)

enter image description here

Anybody any idea how to determine the correct log name?

Thx & BR Daniel


Solution

  • For many of the event logs, you need to use an EventLogQuery.

    As an example, if you wanted to query the "Setup" event log to count the number of entries with an EventID of 1, you could do this:

    Imports System.Diagnostics.Eventing.Reader
    
    Module Module1
    
        Sub Main()
            Dim query As New EventLogQuery("Setup", PathType.LogName, "*[System/EventID=1]")
            Dim nEvents = 0
    
            Using logReader = New EventLogReader(query)
                Dim eventInstance As EventRecord = logReader.ReadEvent()
                While Not eventInstance Is Nothing
                    nEvents += 1
                    eventInstance = logReader.ReadEvent()
                End While
    
            End Using
    
            Console.WriteLine(nEvents)
    
            Console.ReadLine()
    
        End Sub
    
    End Module
    

    You can see the names of the items to query by looking at the XML for an event in Windows Event Viewer.

    The Using construct makes sure that the EventLogReader is properly disposed of after it's been used.

    Further information: How to: Access and Read Event Information (from Microsoft).