Blue Theme Orange Theme Green Theme Red Theme
 
HeaderAd
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Web Forms » 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:
Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 657
Total page views :  21013
Rating :
 2.5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ErrorsAndEvents.zip
 
ArticleAd
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.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);

            s.Close();

            fs.Close();

            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);

            s1.Write("===========================================================================================" + vbCrLf);

            s1.Close();

            fs1.Close();

        }

}

 

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();

            try

            {

                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.

NOTE: THIS ARTICLE IS CONVERTED FROM VB.NET TO C# USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON VB.NET Heaven (http://www.vbdotnetheaven.com/).


Login to add your contents and source code to this article
 [Top] Rate 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.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
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.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ErrorsAndEvents.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Indeed a nice article tariq6/7/2007
It is very helpful . Since you have converted it from VB.NET to C# with the help of a converter you just need to change a few things before it will run .
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved