Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / Visual Basic
Article

Error and Event Logging in VB.NET

Rate me:
Please Sign up or sign in to vote.
3.88/5 (28 votes)
23 Aug 20065 min read 267.4K   7.1K   89   18
This article describes an approach to writing to a custom error log and to writing events into the system event log.

Sample Image - screenshot.jpg

Introduction

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.

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.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:

VB
Imports System.IO
Imports System.Text
Imports System.Windows.Forms

<CLSCompliant(True)> _
Public Class ErrorLogger

    Public Sub New()

        'default constructor

    End Sub

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)

VB
'*************************************************************
'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 Sub WriteToErrorLog(ByVal msg As String, _
       ByVal stkTrace As String, ByVal title As String)

   'check and make the directory if necessary; this is set to look in 
   the application folder, you may wish to place the error log in 
   another location depending upon the user's role and write access to 
   different areas of the file system
    If Not System.IO.Directory.Exists(Application.StartupPath & 
    "\Errors\") Then
        System.IO.Directory.CreateDirectory(Application.StartupPath & 
        "\Errors\")
    End If

    'check the file
    Dim fs As FileStream = New FileStream(Application.StartupPath & 
    "\Errors\errlog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
    Dim s As StreamWriter = New StreamWriter(fs)
    s.Close()
    fs.Close()

    'log it
    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)
    s1.Close()
    fs1.Close()

End Sub

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:

====================================================================
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.vb: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 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:

VB
Imports System.Diagnostics

<CLSCompliant(True)> _
Public Class EventLogger

    Public Sub New()
        'default constructor
    End Sub

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)

VB
'*************************************************************
'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 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 
                    Boolean

    Dim objEventLog As New EventLog

    Try

        'Register the Application as an Event Source
        If Not EventLog.SourceExists(appName) Then
            EventLog.CreateEventSource(appName, LogName)
        End If

        'log the entry
        objEventLog.Source = appName
        objEventLog.WriteEntry(entry, eventType)

        Return True

    Catch Ex As Exception

        Return False

    End Try

End Function

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:

Image 2

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:

Image 3

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUse My.Application.Log instead Pin
Jonas Nordlund18-May-15 21:43
Jonas Nordlund18-May-15 21:43 
QuestionThanks! Pin
siko20128-Mar-14 21:21
siko20128-Mar-14 21:21 
QuestionMy vote is 10 Pin
alllaudhin30-Sep-13 3:26
alllaudhin30-Sep-13 3:26 
GeneralMy Vote of 10 Pin
Alanzo Cam5-Aug-13 23:42
Alanzo Cam5-Aug-13 23:42 
QuestionGood base Pin
Walter V. Williams, Jr.23-Mar-13 0:26
Walter V. Williams, Jr.23-Mar-13 0:26 
GeneralPlease add more Comments Pin
Milad Rk30-Jan-13 15:56
Milad Rk30-Jan-13 15:56 
QuestionI know this is old post but very useful!!! Pin
JohnnyLewellen11-Nov-12 3:42
JohnnyLewellen11-Nov-12 3:42 
GeneralMy vote of 5 Pin
kace1kooki8-May-11 19:59
kace1kooki8-May-11 19:59 
Questioncan u tell me about System event logging and Theft induced check poing Pin
azar00727-Feb-11 5:35
azar00727-Feb-11 5:35 
Questionhow to change the EventID? Pin
Guizzardi18-Feb-10 4:44
Guizzardi18-Feb-10 4:44 
GeneralPlease help me! Pin
zhenshan155-Mar-09 14:56
zhenshan155-Mar-09 14:56 
GeneralRe: Please help me! Pin
afrias15-Apr-10 17:15
afrias15-Apr-10 17:15 
QuestionHow about Vista Pin
pyro3k17-Sep-08 22:47
pyro3k17-Sep-08 22:47 
AnswerRe: How about Vista Pin
Cgaens24-Sep-08 3:36
Cgaens24-Sep-08 3:36 
Generalsource line numbers are not always in stacktrace Pin
Ron37-Sep-06 4:03
Ron37-Sep-06 4:03 
GeneralNice Code - Quick Note Pin
michaelwtaylor4-Sep-06 12:23
michaelwtaylor4-Sep-06 12:23 
GeneralRe: Nice Code - Quick Note Pin
salysle4-Sep-06 12:50
salysle4-Sep-06 12:50 
GeneralUse Health monitoring API for ASP.NET 2.0 Pin
vik2028-Aug-06 19:22
vik2028-Aug-06 19:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.