Writing to the EventLog from a Web Application, Page 2
Listing 2: An installer that creates an event source "MyApp" in the Application log.
Imports System.Diagnostics Imports System.Configuration.Install Imports System.ComponentModel <RunInstaller(True)> _ Public Class MyEventLogInstaller Inherits Installer Public Sub New() Dim log As EventLogInstaller = New EventLogInstaller() log.Source = "MyApp" log.Log = "Application" Installers.Add(log) End Sub End Class
Running the Installer
The next thing you need to do is to run the installer. Installers are run with InstallUtil, passing the installer assembly to the InstallUtil.exe utility. To create the MyApp event source using the installer from Listing 2, complete these steps:
- Click Start|All Programs|Microsoft Visual Studio 2008|Visual Studio Tools.
- Right-click Visual Studio 2008 Command Prompt and select Run as administrator.
- In the command prompt, change to the folder containing MyEventLogInstaller and enter.
- InstallUtil MyEventLogInstaller.dll in the command prompt.
After completing the steps, you should see output that looks something like the output in Figure 2. If there is a problem with your installer, it will be indicated in the console output. Take corrective action and re-try the installer using the numbered steps above.
Figure 2: Console output from the installer.
Writing to the EventLog from a Web Application
You can write an event entry to the event log using the Application log and an existing source, but it is a common practice to isolate log entries by application-specific sources. The difficulty is that source names are stored in the Registry and have to be unique across logs. Hence, when you try to create an event source in a web application, the EventLog class will hang up on the Security log—it will check to see whether the source exists in the Security log.
To test the event source created by the installer, you can run the code in Listing 1. That code should run now. You also can check the Registry to see whether the source exists. The following key should reflect the source as created by the code in Listing 2.
Viewing the Written Event Entry in Visual Studio
After you re-run the code in Listing 1, there will be an EventLog entry for each time you run the code in Listing 1. You can press and hold the Windows key + R and enter Eventvwr to open the event viewer, or you can view the event in Visual Studio's Server Explorer (see Figure 3). To view the event in the Server Explorer, follow these steps:
- Open the Server Explorer.
- Expand the server node.
- Expand the Event Logs node.
- Expand the Application node.
- Scroll down to the MyApp source and expand that node (shown in Figure 3).
Figure 3: The entry written to the new event source.