How to subscribe to Windows Event Logs?

When writing Windows applications or services, Windows have a nice built-in tool called Event Viewer or Event Logs that can be used for logging purpose and helps greatly in debugging and tracing the applications’ critical logs.

One can log the critical and major events that are happening inside your application code, like, when the application started, when the application reached some threshold, and when the application got some error and it can log error details in event viewer.

Windows itself stores the events happening in Windows’ internal services.

Windows event viewer is a great way to log critical Information, Warning, and Error logs.

Sometimes the need is to read from the event viewer, these situations might include Monitoring windows events, Monitoring some custom applications’ events.

We can leverage EventLogWatcher.EventLogWritten to subscribe to the event viewer logs.

Following is the code snippet showing its usage.

void Main(string[] args)
{
  var logQuery = new EventLogQuery("Application", PathType.LogName);
  EventLogWatcher watcher = new EventLogWatcher(logQuery);

  watcher.EventRecordWritten += NewEventEntryWritten;

  watcher.Enabled = true;

  //just to make the app wait to see the event hit
  System.Threading.Thread.Sleep(10000);

}

private void NewEventEntryWritten(object sender, EventRecordWrittenEventArgs e)
{
  String message = e.EventRecord.FormatDescription();
  //here it is...
  //make decision based on the contents of the message
}