Introduction
This is a solution to trace from a web application in EventViewer.
Background
Sometime ago, I needed to trace some error messages from a web application. A good solution for me at that time was to send all output to the EventViewer. I wrote a simple class that worked fine during the development phase. After the first release, I noticed that the listener didn't work on the server machine. I started to find what was missing, and after more investigations, I discovered the following problem. On my computer, the web application runs using WebDev.WebServer.exe under my own account. Because I am an administrator on my machine, the web application inherits all rights to access all resources. The situation on the web server is different. Here, the web application is hosted by asp_net.exe which runs under the ASPNET account. This is a special user created by Microsoft for IIS because this service executes code based on external user request. It doesn't have enough privileges to access the Registry or other resources required to write in the EventViewer.
The solution was to execute the code that writes in the EventViewer under a powerful user. To implement this, I used a class called Impersonator. Because the processes of impersonate and unimpersonate is very slow, I have to use this class on a separate thread, and I do it only one time during the web application lifetime.
Using the code
How to use the code:
void Application_Start(object sender, EventArgs e)
{
Jhc.Diagnostics.EvListener listener =
new Jhc.Diagnostics.EvListener("WebApp");
System.Diagnostics.Trace.Listeners.Add(listener);
listener.Start();
}
void Application_End(object sender, EventArgs e)
{
try
{
if (System.Diagnostics.Trace.Listeners.Count > 0)
if (System.Diagnostics.Trace.Listeners[0] is Jhc.Diagnostics.EvListener)
{
Jhc.Diagnostics.EvListener listener =
(Jhc.Diagnostics.EvListener)System.Diagnostics.Trace.Listeners[0];
listener.Stop();
}
}
catch{ }
}
if (Environment.MachineName == "MACHINE1")
{
using (Impersonator impersonator = new Impersonator("USER1", "", "PASSWD1"))
{
Run();
}
}
else
Run();
I didn't use web.config because different users exist on different machines. Also, you can add more users inside of this class.
Links