Using .Net classes to access Windows Event Log

It is desirable for an admin/developer to be able to view event logs related to certain application remotely. .Net provides easy accessibility to custom event logs through the framework. Coding event logs has never been easier. This article will showcase codes for a practical .NET event log access. As with just any .Net programming topic, we start by introducing the simple but elegant .Net application event logging object model. The center of event logging is the EventLog class in the System.Diagnostics namespace. Using this class, we can read from existing logs, write entries to logs, create and delete event sources, delete logs, respond to log entries, and create new logs while creating event source. Event source is the application that is generating the event. It is the application where you call EventLog.CreateEventSource method from. Since event log access the registry, your application must have the necessary rights to be able to do that. This is just another aspect of .Net framework - security is everywhere and granular. The method and property you most likely will use for writing event logs will be 1. EventLog.SourceExists, which verifies the existence of an event source 2. EventLog.Exists(string logname), which verifies the existence of an event log. 3. EventLog.WriteEntry 4. EventLog.Source property, the source application or log you want to use for subsequent operations We will illustrate the use of EventLog using a small Windows application which creates a custom event log upon button click, then writes an informational entry into the event log just created. Here is the important codes involved: private void button1_Click(object sender, System.EventArgs e) { if(System.Diagnostics.EventLog.SourceExists("MyApp")) { System.Diagnostics.EventLog evLog = new System.Diagnostics.EventLog(); evLog.Source = "MyApp"; evLog.WriteEntry("New B", System.Diagnostics.EventLogEntryType.Information, 123); } else { System.Diagnostics.EventLog.CreateEventSource("MyApp", "MyAppLog"); System.Diagnostics.EventLog evLog = new System.Diagnostics.EventLog(); evLog.Source = "MyAppLog"; evLog.WriteEntry("New B", System.Diagnostics.EventLogEntryType.Information, 123); } } You can verify the creation of the new custom event log by checking Programs->Administrative Tools->Event Viewer. Here is a screenshot of what we get after two button clicks.

And once you click the entry, you will see the familar event properties dialog like this. Note the description is the same as we write to.

EventLog is not only limited to logging windows application, you can also use it to log web application and windows services and more.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish