Reading and clearing a Windows Event Log with C# .NET
November 8, 2014 5 Comments
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.
Thanks….It was very helpful to me for my work related stuff. Made my job easier.
Thanks for your comment, great to hear that. //Andras
sir i want to clear windows logs files using C# code..??
Hello, you mean like with EventLog.Clear() ?
https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.clear(v=vs.110).aspx
//Andras
hello, I want to make event viewer connection for asp.net /c#. I want to connect to the Event Viewer on the server. What should I do for it ? I want to receive information log on and log off.