Reading and clearing a Windows Event Log with C# .NET
October 14, 2017 Leave a comment
In this post we saw how to create a custom event log and here how to the write to the event log. We’ll briefly look at how to read the entries from an event log and how to clear them.
First let’s create an event log and put some messages to it:
string source = "DemoTestApplication"; string log = "DemoEventLog"; EventLog demoLog = new EventLog(log); demoLog.Source = source; demoLog.WriteEntry("First message", EventLogEntryType.Information, 101); demoLog.WriteEntry("Hello!!", EventLogEntryType.Error, 980); demoLog.WriteEntry("Bye", EventLogEntryType.Warning); demoLog.WriteEntry("Long live Mondays", EventLogEntryType.Information, 200); demoLog.WriteEntry("This is a demo", EventLogEntryType.Information, 250);
This is what it looks like in the Event Viewer:
Reading from a log is also straightforward:
string log = "DemoEventLog"; EventLog demoLog = new EventLog(log); EventLogEntryCollection entries = demoLog.Entries; foreach (EventLogEntry entry in entries) { Console.WriteLine("Level: {0}", entry.EntryType); Console.WriteLine("Event id: {0}", entry.InstanceId); Console.WriteLine("Message: {0}", entry.Message); Console.WriteLine("Source: {0}", entry.Source); Console.WriteLine("Date: {0}", entry.TimeGenerated); Console.WriteLine("--------------------------------"); }
…which gives the following output:
Clearing a log is very easy:
demoLog.Clear();
…and the log entries are gone:
You can view all posts related to Diagnostics here.