The System.Diagnostics.EventLog class allows you to programmatically read and write to the Windows Event log. This functionality allows you to read and write your application logs to the Windows Event Log rather than writing these log entries to a text-based file. This logging methodology provides a quick, easy, and performance friendly way to log any type of event. The EventLog class extends beyond simply writing log entries (reading from logs, creating/deleting event sources, deleting logs, etc.) but this article is geared specifically toward writing to the Windows Event Log.
Example Class Used to Write to the Windows Event Log:
| using System; |
| using System.Diagnostics; |
| |
| namespace DT.Event |
| { |
| public class EventLogger |
| { |
| static EventLog el; |
| static EventLogger() |
| { |
| if (!EventLog.SourceExists("EVENT_LOG_NAME")) |
| { |
| //Create New Log |
| EventLog.CreateEventSource("EVENT_LOG_NAME", "NewLog"); |
| el = new EventLog(); |
| el.Source = "EVENT_LOG_NAME"; |
| } |
| } |
| |
| public static void addEvent(string message) |
| { |
| //Log Information |
| el.WriteEntry(message, EventLogEntryType.Information); |
| } |
| |
| public static void addException(string message) |
| { |
| //Log Exception |
| el.WriteEntry(message, EventLogEntryType.Error); |
| } |
| |
| public static void addWarning(string message) |
| { |
| //Log Warning |
| el.WriteEntry(message, EventLogEntryType.Warning); |
| } |
| } |
| } |
| |
| |
Example Usage of the DT.Event Class:
| using System; |
| using System.Collections.Generic; |
| using System.Text; |
| using DT.Event; |
| |
| namespace DT.EventLogExample |
| { |
| class Program |
| { |
| static void Main(string[] args) |
| { |
| //Log Information |
| Event.EventLogger.addEvent("Information Event Logged!"); |
| //Log Warning |
| Event.EventLogger.addWarning("Warning Event Logged!"); |
| //Log Exception |
| Event.EventLogger.addException("Exception Event Logged!"); |
| } |
| } |
| } |