Event Logging in a .NET Web Service
 
Published: 28 Aug 2006
Unedited - Community Contributed
Abstract
This article describes the logging mechanism in a .NET web service. It demonstrates how to write to the Event log from a .NET Web Service and explains how to resolve security issues related to event logging.
by Sandesh Meda
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 50758/ 53

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.



User Comments

Title: Where is the implementation   
Name: Enasr
Date: 2011-11-21 6:22:42 AM
Comment:
i read the article before but now its without any implementation why
Title: clarification   
Name: phani
Date: 2011-03-02 1:59:31 AM
Comment:
where should i write the code for the function WriteToEventLog which is being called by Catch Block
Title: Sample is very good   
Name: Rami
Date: 2009-11-02 10:17:57 AM
Comment:
Ran it successfully using Visual Studio 2008.
Installed the DLL on 2003 server.
Used the OS CMD window to run the InstallUtil found under FRAMEWORK directroy of .NET 2 installtion.
Title: Customer Installations   
Name: Dennis Jakobsen
Date: 2007-11-22 4:54:46 AM
Comment:
Hi,

Thanks for the example, i was running into that exact SecurityException for my Web Service. But how would i a customer install? I obviously can't take my Visual Studio Command Prompt!
Title: sample good   
Name: Lee Peace
Date: 2007-06-20 10:23:07 PM
Comment:
Thanks for this sample !

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


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