Logging Exceptions in Window’s Event Log   Leave a comment

When we develop an application we do the exception logging using various ways. For example, logging exceptions in database, writing in text files, sending emails and etc.

In this article we will see how we can log the exceptions in window’s event logs and how to read the same.

To log exception in windows event log, you first need to import the System.Diagnostics name space to get the access of classes required to log the exceptions.

Below is the simple code which is logging the “divide by zero” exception.

            decimal a, b, result;
            a = "10.0";
            b = "0.0";
            result = a / b;
        catch (Exception err)
            // Write the information to the event log.
            // Register the event source if needed.
            if (!EventLog.SourceExists("DivideByZeroApp"))
                // This registers the event source and creates the custom log,
                // if needed.
                EventLog.CreateEventSource("DivideByZeroApp", "ProseTech");

            // Open the log. If the log doesn't exist,
            // it will be created automatically.
            EventLog log = new EventLog("ProseTech");
            log.Source = "DivideByZeroApp";
            log.WriteEntry(err.Message, EventLogEntryType.Error);


When you open the Windows event log you will get the exception source as “DivideByZeroApp” and on double click of that exception actual exception logged using Exception.Message property.

To read the exception from windows event log, below is the code.

 // For maximum performance, join all the event
 // information into one large string using the
 // StringBuilder.
 System.Text.StringBuilder sb = new System.Text.StringBuilder();
 EventLog log = new EventLog("ProseTech");
 foreach (EventLogEntry entry in log.Entries)
 // Write the event entries to the StringBuilder.
 if (entry.Source == "DivideByZeroApp")
   sb.Append("Entry Type:");
   sb.Append("Time Generated:");

Posted June 13, 2015 by Izharuddin Shaikh in C#

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: