AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=987&pId=-1
Event Logging in a .NET Web Service
page
by Sandesh Meda
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 54723/ 41

Introduction

A well-written piece of code should theoretically not throw any exceptions.  However, in practice it is almost impossible to test if an application works under every situation.  When errors occur, there are different ways to handle them.  This article discusses how to log exceptions in the Event Log.

What is an Event Viewer?

Event Viewer is a Windows component that logs program, security and system events on your computer.  You can use the Event viewer to manage the event logs, gather information about the software problems and monitor system events.  To open the Event Viewer, go to Start -> Run -> eventvwr.

What are the different types of Logs?

There are typically 3 different types of logs.

·         Application Log - Applications running under Windows log their events in the Application Log.

·         Security Log - Windows logs security related events in the Security Log.

·         System Log - The Operating System logs in the System Log.

What are the different Event types?

The Event types are classified into the following different types.

·         Information - This type indicates a successful operation of an application.  An example is a successful loading of a new virus definition file by antivirus software.

·         Warning - This type indicates that there could be a potential problem in the future.  The entries help in taking preventive measures.

·         Error - This type indicates a significant problem.  It lets us know if there was a failure in a critical task.

·         Success Audit - This type indicates that an audited security event is successfully completed. For example, when a user authenticates successfully, there may be an entry of this type.

·         Failure Audit - This type indicates that there was a failure of an audited security event.

Implementing Event Logging in .NET

Now that we have covered the basics of Event Logging, let us go into the details of implementing the Event Logging mechanism in a .NET Web Service.  To demonstrate this, consider a simple Web Service that divides to integers.  If the denominator is zero, it raises the Divide by zero exception.

First, import the necessary namespace.

Listing 1

using System.Diagnostics;
Let us examine a WebMethod that potentially thows an exception.
/// <summary>
/// A Web method that divides two integers
/// </summary>
/// <param name="intNumerator">Numerator</param>
/// <param name="intDenominator">Denominator</param>
[WebMethod]
public void DivideNumbers(int intNumerator, int intDenominator)
{
  double dResult;
  try
  {
    dResult = intNumerator / intDenominator;
  }
  catch (Exception e)
  {
//Write to Event Log
    WriteToEventLog(e.Message, EventLogEntryType.Error);
  }
}

When an exception occurs, it calls the WriteToEventLog method to write to the Event Log.

Listing 2

/// <summary>
/// Method to write to the Event Log
/// </summary>
/// <param name="strLogEntry">The message to be logged</param>
/// <param name="eType">Event Log Type</param>
 
private void WriteToEventLog(string strLogEntry, EventLogEntryType eType)
{
  string strSource = "Division Web Service"//name of the source
  string strLogType = "Application"; //type of the log
  string strMachine = "."//machine name
 
  if (!EventLog.SourceExists(strSource, strMachine))
  {
    EventLog.CreateEventSource(strSource, strLogType, strMachine);
  }
 
  EventLog eLog = new EventLog(strLogType, strMachine, strSource);
  eLog.WriteEntry(strLogEntry, eType, 1000);
 
}

The WriteToEventLog method takes two arguments.  The strLogEntry is the description of the error message that you want to log and the eType is the Event Type.  This could be the following.

EventLogEntryType.Error

EventLogEntryType.FailureAudit

EventLogEntryType.Information

EventLogEntryType.SuccessAudit

EventLogEntryType.Warning

Please refer to the section above for details on what the different event types mean.

The EventLog constructor accepts three arguments.  The strLogType denotes the type of log and the strMachine denotes the name of the machine where the Event Source exists.  A period (.) is used to denote localhost.  The strSource denotes the name of the Event Source.

The WriteEntry constructor accepts three arguments.  The strLogEntry denotes the message to be logged, the eType is the Event entry log type and the third argument is the EventID (here I have used 1000) which is an application specific identifier for the event.

Let us open the WebService in a browser and invoke the DivideNumbers web method.  We can simulate the Divide By Zero exception by entering 0 for the Denominator as shown.

Figure 1

When you invoke the web method, you get the following message

Figure 2

When the application attempts to make an entry in the log, it encounters the System.Security.SecurityException.  It complains about not being able to find the Event Source.  It fails to create the "Division Web Service" Event Source because by default ASPNET does not have the correct user rights to create an event source.

There are 2 approaches to solve this problem.

The first approach is to create the event source using the Registry Editor.  Please be warned that incorrect use of the Registry Editor may result in serious problems and you may have to reinstall the Operating System.  You must have administrator rights before attempting to create the Event Source.  Use regedit at your own risk!

To create an event source under the Application Log:

1. Click Start -> Run, type regedit.

2. Locate the registry subkey HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application.

3. Right-click the Application subkey, point to New and then click Key.

4. Type Division Web Service for the key name.

5. Close Registry Editor.

The second recommended approach involves using the EventLogInstaller class in the System.Diagnostics namespace.  This article uses C# in demonstrating how to use the EventLogInstaller class to create an Event source.

Create a new Class Library using Visual Studio .NET named EventLogSourceInstaller.  The Class1.cs file is created by default.

Using the Solution Explorer, add a reference to System.Configuration.Install.dll and click OK.

Rename the Class1.cs file created in Step 1 to MyEventLogInstaller.cs.

Replace the code by the sample code below.

Listing 3

using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Configuration.Install;
namespace EventLogSourceInstaller
{
  [RunInstaller(true)]
  public class MyEventLogInstaller: Installer
  {
    private EventLogInstaller myEventLogInstaller;
 
    public MyEventLogInstaller()
    {
//Create Instance of EventLogInstaller
      myEventLogInstaller = new EventLogInstaller();
 
// Set the Source of Event Log, to be created.
      myEventLogInstaller.Source = "Division Web Service";
 
// Set the Log that source is created in
      myEventLogInstaller.Log = "Application";
 
// Add myEventLogInstaller to the Installers Collection.
      Installers.Add(myEventLogInstaller);
    }
  }
}

Build the solution to create the EventLogSourceInstaller.dll in the bin directory.

Open the Visual Studio .NET command prompt by going to Start -> All Programs -> Microsoft Visual Studio .NET 2003 -> Visual Studio .NET Tools -> Visual Studio .NET 2003 Command Prompt.

Change to the bin directory where the EventLogSourceInstaller.dll is located.

Then execute the following command:

Listing 4

InstallUtil EventLogSourceInstaller.dll

InstallUtil displays the progress of creating a new Event Source.  It also logs the progress in the EventLogSourceInstaller.InstallLog file that is created in the same location as the EventLogSourceInstaller.dll.  After the commit phase, it displays the message:

The Commit phase completed successfully.

The transacted install has completed.

Now that the Event Source is successfully created, we can modify the Webmethod to remove the line that checks to see if the Event Source is exists.

Listing 5

//  if (!EventLog.SourceExists(strSource, strMachine))
//  {
//  EventLog.CreateEventSource(strSource, strLogType, strMachine);
//  }

Rebuild the webservice and invoke the WebMethod again.  Open the Event viewer by going to Control Panel -> Administrative Tools -> Event Viewer.  Expand the Application Log.

You will now see an entry under the Division Web Service Event Source.  Double click the entry to get the details of the event.  The dialog shows the Source, Description of the error, Type of the error and the date and time when the event occurred.

Figure 3

Conclusion

This article explains the importance of logging events to an Event Viewer.  It describes the different types of Event Logs and different types of Event types.  It concludes with an explanation of how the Event Logging can be implemented in a Web Service.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 10:16:05 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search