Event Logging Basics in .NET

Logging important events is something that any non-trivial application should do. Be it errors, authentication failures or anything else. Those of us used to Windows based systems will probably be familiar with event logs. For people who aren’t, there are numerous ways you can access a system’s event logs, the easiest way being to open up the run dialog and type ‘eventvwr.msc’. This will bring up the Event Viewer snap in, which shows your system’s event logs. Besides logging your events using your own custom system, you can also log events here, where system administrators can see them easily.

The main drawbacks to logging events in this manner are:

  • Writing to a system event log is quite costly in terms of processor time.
  • Each log has a specific capacity that cannot be changed.
  • Handling EventLog objects can be a security risk if using partially trusted assemblies.

Despite those drawbacks, you’ll be happy to hear that event logging in .NET is quite an easy task that can be accomplished in the following steps. First we create an EventLog instance giving the name of the log. Creating a new log is as simple as passing a name that does not exist. Passing a name that does exist will load that log. We then need to set the log’s Source property, assigning a string name to it. If we’ve just created a new log, we’ll need to create a new event source using the static method EventLog.CreateEventSource(). Once we’ve performed these steps, we can log entries to the event log.

In this example, we’ll create a new log and event source, write an entry, and then iterate through all the entries showing each one:

  1. // Uses System.Diagnostics
  2. EventLog el = new EventLog("MyLog");
  3.  
  4. if (!EventLog.SourceExists("MyLogSource"))
  5. {
  6.     EventLog.CreateEventSource("MyLogSource", "MyLog");
  7. }
  8.  
  9. el.Source = "MyLogSource";
  10. el.WriteEntry("Hello!", EventLogEntryType.Information);
  11.  
  12. foreach (EventLogEntry e in el.Entries)
  13. {
  14.     Console.WriteLine("{0}, {1}", e.Source, e.Message);
  15. }

It should be noted that the correct time to create an event log and event source is in the installation of the application. However, not all applications work that way, as we all know. The above code will work both when the log and source exist aswell as when they don’t exist already.

It is not possible to delete single entries using the classes above for security reasons, but you can clear an event log by using the instance method Clear() of an EventLog object:

  1. el.Clear()

There we have it, the basics of Windows event logging using .NET.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • LinkedIn
  • Technorati

Leave a Reply

Your email address will not be published. Required fields are marked *