Reader Level:

Event and Error Logging

By Scott Lysle on December 15, 2006
This article describes an approach to writing to a custom error log and to writing events into the system event log.
  • 0
  • 0
  • 58529
Download Files:


This article describes an approach to writing to a custom error log and to writing events into the system event log. 
Error logs are a useful method for collecting all error data generated by an application; this often includes trapped errors that you may not need to or care to show to the end user.   Error logs are most useful during an early or beta release of a product where you have a limited set of users and you have an opportunity to capture the error logs back from these users.  The error log class included with this example creates time stamped entries showing the exact method and line of code where the error occurred as well as the error message generated.

The event log is a system construct used to capture different types of information regarding the operational status of applications running on that system.  Such log entries are categorized and made visible through the system event viewer console.  Event logging is probably a better alternative to error logging in fully fielded systems.

The Code:

Unzip the attached project; in it you will find a class library project entitled, "EventsAndErrors" and a separate test project that subsequently uses the EventsAndErrors class library.  If you take a look at the class library project, you will note that it contains two classes: ErrorLogger.cs and EventLogger.cs.  As you can probably guess, ErrorLogger.cs creates and writes to an error log while EventLogger.cs writes to the system event log.

Open up the ErrorLogger.cs class and examine the code.  At the beginning you will see the following:

using System.Windows.Forms;

using System.IO;

using System.Text;


public class ErrorLogger




public ErrorLogger()





The class is again pretty trivial, the imports at the beginning of the class are needed to read and write to a file, and to derive information about the application (namely its path).  You will note that this is a class rather than a module and for that reason it has an empty default constructor.  This, in C#, does not really need to be explicitly stated, however, it would be a nice improvement to add an additional constructor to allow you pass in all of the required arguments in the initialization and to create the log entry without subsequently evoking the classes' method used to write to the error log.  Further both this class and the EventLogger.cs class could be written as modules which would eliminate the need to instance the class if you prefer that approach.

Looking on, the rest of the code looks like this: (modified to fit on this page)

    // *************************************************************

    //NAME:          WriteToErrorLog

    //PURPOSE:       Open or create an error log and submit error message

    //PARAMETERS:    msg - message to be written to error file

    //               stkTrace - stack trace from error message

    //               title - title of the error file entry

    //RETURNS:       Nothing



public void WriteToErrorLog(string msg, string stkTrace, string title)


            if (!(System.IO.Directory.Exists(Application.StartupPath + "\\Errors\\")))


                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\Errors\\");


            FileStream fs = new FileStream(Application.StartupPath + "\\Errors\\errlog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);

            StreamWriter s = new StreamWriter(fs);



            FileStream fs1 = new FileStream(Application.StartupPath + "\\Errors\\errlog.txt", FileMode.Append, FileAccess.Write);

            StreamWriter s1 = new StreamWriter(fs1);

            s1.Write("Title: " + title + vbCrLf);

            s1.Write("Message: " + msg + vbCrLf);

            s1.Write("StackTrace: " + stkTrace + vbCrLf);

            s1.Write("Date/Time: " + DateTime.Now.ToString() + vbCrLf);


("============================================" + vbCrLf);






Where the subroutine it declared, you will note that it excepts three arguments:  The message you wish to record (typically I would use the exception's message here but it could be any string), the stack trace which is the exception's stack trace, and the error's title which could be any string  you wish to use as an error entry's title.

The next section of the code checks for the existence of the directory where the error will be written and if it does not exist, it creates it.  Since the directory in the example is the applications startup path, when you look for your error log in debug mode, it will appear in the TestProject\bin\Debug folder and a subordinate folder called "Errors".

After checking on the directory, the next section checks on the file itself; in this case I have named the error log "errlog.txt" so this methods looks for that file and creates it if it does not exist.  Notice that I have closed the file stream after making this check and that, in the next section, I reopen the file stream in file mode "append" and with file access set to "write".  After opening the stream in this manner, the method writes out the formatted error message and, at end of the message, marks it with a date and time stamp before closing the file stream.

That is it for the error logging class, if you were to take a look at the output from this class, you would see something like this in the error log:


Title: Error

Message: Arithmetic operation resulted in an overflow.

StackTrace:    at TestProject.Form1.btnErrorLog_Click(Object sender, EventArgs e) in C:\Scott\Authoring\Code\ErrorsAndEvents\TestProject\Form1.cs:line 23

Date/Time: 8/12/2006 4:09:52 PM


This can of course be pretty useful when you are debugging an installation on a user's machine because you can look at this log and see that the user experienced a failure in the "btnErrorLog_Click" event on line 23 and that error was "Arithmetic operation resulted in an overflow".  At least I find this more helpful than a phone call from a user saying something like, "I hit a button and it quit working".

Now open up the EventLogger.cs class and take a look at it.  The class begins similarly to the ErrorLogger.cs class but has only a single import statement as it does not directly read from or write to a file:

using System.Diagnostics;


public class EventLogger



    public  New()


        //default constructor



Like the ErrorLogger.cs class, this class contains only a single function  used to write directly to the event log:  (modified to fit on this page)


    //NAME:          WriteToEventLog

    //PURPOSE:       Write to Event Log

    //PARAMETERS:    Entry - Value to Write

    //               AppName - Name of Client Application. Needed

    //               because before writing to event log, you must

    //               have a named EventLog source.

    //               EventType - Entry Type, from EventLogEntryType

    //               Structure e.g., EventLogEntryType.Warning,

    //               EventLogEntryType.Error

    //               LogNam1e: Name of Log (System, Application;

    //               Security is read-only) If you

    //               specify a non-existent log, the log will be

    //               created

    //RETURNS:       True if successful



public bool WriteToEventLog(string entry, string appName, EventLogEntryType eventType, string logName)


            EventLog objEventLog = new EventLog();



                if (!(EventLog.SourceExists(appName)))


                    EventLog.CreateEventSource(appName, LogName);


                objEventLog.Source = appName;

                objEventLog.WriteEntry(entry, eventType);

                return true;


            catch (Exception Ex)


                return false;




This function is pretty easy to follow; the arguments passed to the function are described in the commented section.  The code checks to see if the application name exists in the error log and if it does not, it adds it to the log.  Notice also that this method was defined as function and that it returns a Boolean which is set to true if it successfully writes to the log or to false if it does not; this will allow you to check the returned value to see if the operation were successful within your code.

Having accomplished that, it populates the newly instanced log entry with the entry information and event type and adds the event to the log.

Executing this function will result in an addition to the log file that will look something like this:

Figure 1:  Event Log Showing Entry Generated by Test Project

If you were to open the event log entry from the system event log viewer, you would see that the demo project generated an entry like this:

Figure 2:  Event Properties from Event Log Entry

Whilst this is useful information, it is less useful than what was placed into the error log, of course we can concatenate the message and stack trace to push similar data into the event log and in so doing make it a little more useful when debugging an application error on a end user's machine.


Scott Lysle

Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the... Read more


Trending up