- 1 year ago
How do i get windows event log list by specific source C#
To retrieve a list of Windows Event Logs filtered by a specific source using C#, you can use the EventLogQuery
and EventLogReader
classes from the System.Diagnostics.Eventing.Reader
namespace. Here's an example code snippet:
csharpusing System;
using System.Diagnostics.Eventing.Reader;
public class EventLogReaderExample
{
public static void Main()
{
string eventLogSource = "YourEventLogSource";
// Create an event log query to filter events by source
string queryString = $"*[System[Provider[@Name='{eventLogSource}']]]";
EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
try
{
// Create an event log reader and iterate through the events
using (EventLogReader reader = new EventLogReader(query))
{
EventRecord record;
while ((record = reader.ReadEvent()) != null)
{
// Process the event record
Console.WriteLine($"Event ID: {record.Id}");
Console.WriteLine($"Level: {record.LevelDisplayName}");
Console.WriteLine($"Time Created: {record.TimeCreated}");
Console.WriteLine($"Message: {record.FormatDescription()}");
Console.WriteLine();
}
}
}
catch (EventLogNotFoundException ex)
{
Console.WriteLine($"Event log 'Application' not found: {ex.Message}");
}
catch (EventLogReadingException ex)
{
Console.WriteLine($"Error reading the event log: {ex.Message}");
}
}
}
In the code above, replace "YourEventLogSource"
with the specific source you want to filter the event logs by. The example queries the "Application" event log and retrieves events where the provider (source) matches the specified value.
The code reads the event records one by one and prints some information like Event ID, Level, Time Created, and Message for each event.
Make sure to include the System.Diagnostics.Eventing.Reader
namespace in your code file. You may need to add a reference to the System.Core
assembly in your project.
Compile and run the code to retrieve a list of Windows Event Logs filtered by the specified source.