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 a 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.
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.vb and EventLogger.vb. As you can probably guess, ErrorLogger.vb creates and writes to an error log while EventLogger.vb writes to the system event log.
Open up the ErrorLogger.vb class and examine the code. At the beginning, you will see the following:
Public Class ErrorLogger
Public Sub New()
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 VB.NET, does not really need to be explicitly stated; however, it would be a nice improvement to add an additional constructor to allow you to pass in all of the required arguments in the initialization and to create the log entry without subsequently evoking the class’ method used to write to the error log. Further, both this class and the EventLogger.vb class could be written as modules which would eliminate the need to instantiate the class if you prefer that approach.
Looking on, the rest of the code looks like this: (modified to fit on this page)
Public Sub WriteToErrorLog(ByVal msg As String, _
ByVal stkTrace As String, ByVal title As String)
the application folder, you may wish to place the error log in
another location depending upon the user different areas of the file system
If Not System.IO.Directory.Exists(Application.StartupPath &
Dim fs As FileStream = New FileStream(Application.StartupPath &
"\Errors\errlog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim s As StreamWriter = New StreamWriter(fs)
Dim fs1 As FileStream = New FileStream(Application.StartupPath &
"\Errors\errlog.txt", FileMode.Append, FileAccess.Write)
Dim s1 As StreamWriter = 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)
s1.Write("================================================" & vbCrLf)
Where the subroutine it is declared, you will note that it accepts 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 application's 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 method 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:
Message: Arithmetic operation resulted in an overflow.
StackTrace: at TestProject.Form1.btnErrorLog_Click(Object sender,
EventArgs e) in C:\Scott\Authoring\Code\ErrorsAndEvents\
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 the 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.vb class and take a look at it. The class begins similarly to the ErrorLogger.vb class but has only a single
Imports statement as it does not directly read from or write to a file:
Public Class EventLogger
Public Sub New()
Like the ErrorLogger.vb class, this class contains only a single function used to write directly to the event log: (modified to fit on this page)
Public Function WriteToEventLog(ByVal entry As String, _
Optional ByVal appName As String = "CompanyName", _
Optional ByVal eventType As _
EventLogEntryType = EventLogEntryType.Information, _
Optional ByVal logName As String = "ProductName") As
Dim objEventLog As New EventLog
If Not EventLog.SourceExists(appName) Then
objEventLog.Source = appName
Catch Ex As Exception
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 a 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 instantiated 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.