65.9K
CodeProject 正在变化。 阅读更多。
Home

从 IIS 中的 EventViewer 进行跟踪

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.38/5 (4投票s)

2008 年 3 月 7 日

CPOL

1分钟阅读

viewsIcon

26385

downloadIcon

113

一个允许您从 IIS 进程在事件查看器中追踪的类。

引言

这是一个在事件查看器中追踪 Web 应用程序输出的解决方案。

背景

以前,我需要从 Web 应用程序中追踪一些错误消息。当时一个好的解决方案是将所有输出发送到事件查看器。我编写了一个简单的类,在开发阶段工作良好。在第一次发布后,我注意到该侦听器在服务器机器上不起作用。我开始寻找缺失的部分,经过进一步调查,我发现了以下问题。在我的计算机上,Web 应用程序使用我的帐户下的 WebDev.WebServer.exe 运行。由于我是在我的机器上是管理员,Web 应用程序继承了访问所有资源的全部权限。Web 服务器上的情况不同。在这里,Web 应用程序由运行在 ASPNET 帐户下的 asp_net.exe 托管。这是微软为 IIS 创建的一个特殊用户,因为该服务执行基于外部用户请求的代码。它没有足够的权限来访问注册表或其他写入事件查看器所需的资源。

解决方案是以具有更高权限的用户身份执行写入事件查看器的代码。为了实现这一点,我使用了一个名为 Impersonator 的类。由于 impersonate 和 unimpersonate 过程非常慢,我必须在单独的线程中使用这个类,并且仅在 Web 应用程序的生命周期内执行一次。

使用代码

如何使用代码

//
// In Global.asax add the following lines :
// WebApp - can be your application name
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{ }
 }


// Inside of the EventListener class replace MACHINE1 with
// a valid computer name and USER1/PASSWD1 with a powerfull user from that machine
// otherwise the code will be executed under the process account
if (Environment.MachineName == "MACHINE1")
{
   using (Impersonator impersonator = new Impersonator("USER1", "", "PASSWD1"))
   {  
     Run();
   }
}
else
   Run(); // run without impersonate,
          // you have to have enough rights
          // to write in EventViewer

我没有使用 web.config,因为不同机器上存在不同的用户。此外,您可以在这个类中添加更多用户。

链接

© . All rights reserved.