Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET and Web » Event and Error Logging

Event and Error Logging


This article describes an approach to writing to a custom error log and to writing events into the system event log.

Author Rank:
Total page views :  13815
Total downloads :  294
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ErrorsAndEvents.zip
 
Become a Sponsor

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

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

 

End Class

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.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 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 import statement as it does not directly read from or write to a file:

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)

'*************************************************************

'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

End Class

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.


Login to add your contents and source code to this article
 About the author
 
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 cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
viagra by watches On July 11, 2010
Until and unless you place yourself under proper medical care, your Generic Viagra usage will not yield any results and there is no respite from erectile dysfunction. Moreover, to avoid the occasional side-effects of cheap Viagra , a safe and proper usage of Viagra sale is a necessity which can happen only under the instructions of a qualified medical practitioner.
Reply | Email | Delete | Modify | 
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.