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