다음을 통해 공유


연습: ASP.NET 상태 모니터링에서 WMI 이벤트 수신

업데이트: 2007년 11월

이 연습에서는 ASP.NET 상태 모니터링 이벤트에 매핑된 WMI(Windows Management Instrumentation) 이벤트를 수신하는 방법을 보여 줍니다. 이 연습에서 수행할 작업은 다음과 같습니다.

  • 상태 모니터링 이벤트를 수신하는 콘솔 응용 프로그램 빌드

  • 모니터링할 웹 응용 프로그램 구성

  • 콘솔 응용 프로그램 테스트

WMI를 사용하여 상태 모니터링 이벤트를 전달하는 방법에 대한 자세한 내용은 WMI를 사용하여 ASP.NET 상태 모니터링 이벤트 전달을 참조하십시오.

사전 요구 사항

이 연습을 완료하려면 다음과 같은 요건을 갖추어야 합니다.

  • Microsoft IIS(인터넷 정보 서비스) 및 .NET Framework 버전 2.0이 설치된 서버에 액세스할 수 있어야 합니다.

  • 서버에 ASP.NET 웹 사이트를 만들 수 있는 권한이 있어야 합니다.

  • 웹 이벤트 정보에 액세스하기 위해 관리자 권한으로 응용 프로그램을 실행할 수 있는 권한이 있어야 합니다.

ASP.NET 상태 모니터링 프로세스

다음 목록에서는 WMI를 통해 이벤트 데이터 전달을 처리하도록 구성된 경우 ASP.NET 상태 모니터링 중에 발생하는 주요 단계에 대해 설명합니다.

  1. 구성 설정에 따라 ASP.NET에서 상태 이벤트를 발생시킵니다.

  2. 구성 설정에 따라 ASP.NET 상태 모니터링에서 이벤트를 WmiWebEventProvider 공급자에 디스패치합니다.

  3. ASP.NET의 WMI MOF(Managed Object Format) 파일, 즉 Aspnet.mof에 포함된 정보에 따라 WmiWebEventProvider 공급자가 관리되지 않는 호출을 통해 WMI 시스템에 이벤트 정보를 전달합니다.

  4. 마지막으로 WMI에서 관련 데이터를 사용자 지정 응용 프로그램에 전달합니다. 이 응용 프로그램은 System.Management 형식을 사용하여 ASP.NET의 관리되는 API와 WMI의 관리되지 않는 API 간을 상호 운용합니다.

다음 예제에서는 이 프로세스를 보여 줍니다.

WMI를 사용한 ASP.NET 상태 모니터링 프로세스

WMI를 사용하여 ASP.NET 상태 모니터링 이벤트를 수신하는 단계

WMI를 사용하여 ASP.NET 상태 모니터링 이벤트를 수신하는 단계는 일반적으로 다음과 같습니다.

  1. 사용자 지정 수신기 응용 프로그램을 만들고 빌드합니다. 이 연습에서 수신기 응용 프로그램은 콘솔 응용 프로그램입니다.

  2. 상태 모니터링을 사용하도록 설정하고 공급자를 지정하여 사용자 지정 공급자가 상태 이벤트를 처리할 수 있도록 웹 응용 프로그램을 구성합니다. 이 연습에서 공급자는 기본 WMI 공급자입니다.

  3. 웹 응용 프로그램이 실행되는 서버에서 수신기를 활성화합니다. 이 연습에서는 수신기가 콘솔 응용 프로그램이므로 명령줄에서 응용 프로그램을 실행해야 합니다.

  4. 웹 브라우저에서 모니터링 대상 웹 사이트의 페이지에 액세스합니다.

  5. 웹 사이트에서 발생된 상태 이벤트가 수신기에 의해 캡처되었는지 확인합니다.

WMI 이벤트 수신기 만들기

WMI 이벤트 수신기는 WMI에 전달된 ASP.NET 상태 이벤트를 처리합니다.

다음 절차에서는 ASP.NET 상태 이벤트와 연결된 WMI 개체에 액세스하는 WMI 이벤트 수신기 콘솔 응용 프로그램에 대한 코드 예제를 보여 줍니다. 다음 목록에서는 이 응용 프로그램에서 수행하는 주요 단계에 대해 설명합니다.

  • 수신기와 웹 응용 프로그램이 실행되는 컴퓨터의 이름 가져오기

  • ASP.NET 엔터티에 WMI 경로 설정

  • System.Management 네임스페이스에 정의된 대로 관리되는 개체 감시자 만들기

  • 감시할 이벤트의 범위를 이전 WMI 경로와 같도록 설정

  • WMI 이벤트 catch 작업 무한 반복

ASP.NET 상태 이벤트에 대한 WMI 이벤트 수신기를 만들려면

  1. 콘솔 응용 프로그램에 대한 소스 파일을 만든 후 다음 코드를 붙여넣습니다. 이 코드는 로컬 컴퓨터, 즉 모니터링 대상 웹 응용 프로그램이 실행되는 동일한 컴퓨터에서 ASP.NET 상태 모니터링 이벤트와 연결된 WMI 이벤트를 수신합니다.

    Imports System
    Imports System.Text
    Imports System.Management
    
    Namespace SamplesAspNet
    
        Class SampleWmiWebEventListener
            ' Displays event-related information.
    
            Public Shared Sub DisplayEventInformation(ByVal ev As ManagementBaseObject)
    
                ' This will hold the name of the 
                ' event class as defined in the 
                ' Aspnet.mof file.
                Dim eventTypeName As String
    
                ' Get the name of the WMI-raised event.
                eventTypeName = ev.ClassPath.ToString()
    
                ' Process the raised event.
                Select Case eventTypeName
                    ' Process the heartbeat event.  
                    Case "HeartBeatEvent"
                        Console.WriteLine("HeartBeat")
                        Console.WriteLine(vbTab + _
                        "Process: {0}", ev("ProcessName"))
                        Console.WriteLine(vbTab + "App: {0}", _
                        ev("ApplicationUrl"))
                        Console.WriteLine(vbTab + "WorkingSet: {0}", _
                        ev("WorkingSet"))
                        Console.WriteLine(vbTab + "Threads: {0}", _
                        ev("ThreadCount"))
                        Console.WriteLine(vbTab + "ManagedHeap: {0}", _
                        ev("ManagedHeapSize"))
                        Console.WriteLine(vbTab + "AppDomainCount: {0}", _
                        ev("AppDomainCount"))
    
                        ' Process the request error event. 
                    Case "RequestErrorEvent"
                        Console.WriteLine("Error")
                        Console.WriteLine("Url: {0}", _
                        ev("RequestUrl"))
                        Console.WriteLine("Path: {0}", _
                        ev("RequestPath"))
                        Console.WriteLine("Message: {0}", _
                        ev("EventMessage"))
                        Console.WriteLine("Stack: {0}", _
                        ev("StackTrace"))
                        Console.WriteLine("UserName: {0}", _
                        ev("UserName"))
                        Console.WriteLine("ThreadID: {0}", _
                        ev("ThreadAccountName"))
    
                        ' Process the application lifetime event. 
                    Case "ApplicationLifetimeEvent"
                        Console.WriteLine("App Lifetime Event {0}", _
                        ev("EventMessage"))
    
                        ' Handle events for which processing is not
                        ' provided.
                    Case Else
                        Console.WriteLine("ASP.NET Event {0}", _
                        ev("EventMessage"))
                End Select
    
            End Sub 'DisplayEventInformation .
    
            ' The main entry point for the application.
            Public Shared Sub Main(ByVal args() As String)
                ' Get the name of the computer on 
                ' which this program runs.
                ' Note that the monitored application must also run 
                ' on this computer.
                Dim machine As String = Environment.MachineName
    
                ' Define the Common Information Model (CIM) path 
                ' for WMI monitoring. 
                Dim path As String = _
                String.Format("\\{0}\root\aspnet", machine)
    
                ' Create a managed object watcher as 
                ' defined in System.Management.
                Dim query As String = "select * from BaseEvent"
                Dim watcher As New ManagementEventWatcher(query)
    
                ' Set the watcher options.
                Dim timeInterval As New TimeSpan(0, 1, 30)
                watcher.Options = _
                New EventWatcherOptions(Nothing, timeInterval, 1)
    
                ' Set the scope of the WMI events to 
                ' watch to be ASP.NET applications.
                watcher.Scope = _
                New ManagementScope(New ManagementPath(path))
    
                ' Set the console background.
                Console.BackgroundColor = ConsoleColor.Blue
                ' Set the foreground color.
                Console.ForegroundColor = ConsoleColor.Yellow
                ' Clear the console.
                Console.Clear()
    
                ' Loop indefinitely to catch the events.
                Console.WriteLine( _
                "Listener started. Enter CntlC to terminate.")
    
                While True
                    Try
                        ' Capture the WMI event related to 
                        ' the Web event.
                        Dim ev As ManagementBaseObject = _
                        watcher.WaitForNextEvent()
                        ' Display the Web event information.
                        DisplayEventInformation(ev)
    
                        ' Prompt the user.
                        Console.Beep()
    
                    Catch e As Exception
                        Console.WriteLine("Error: {0}", e)
                        Exit While
                    End Try
                End While
    
            End Sub 'Main 
    
        End Class 'SampleWmiWebEventListener 
    
    End Namespace
    
    using System;
    using System.Text;
    using System.Management;
    
    namespace SamplesAspNet
    {
        // Capture WMI events associated with 
        // ASP.NET health monitoring types. 
        class SampleWmiWebEventListener
        {
            // Displays event-related information.
            static void DisplayEventInformation(
                ManagementBaseObject ev)
            {
    
                // This will hold the name of the 
                // event class as defined in the 
                // Aspnet.mof file.
                string eventTypeName;
    
                // Get the name of the WMI-raised event.
                eventTypeName = ev.ClassPath.ToString();
    
                // Process the raised event.
                switch (eventTypeName)
                {
                    // Process the heartbeat event.  
                    case "HeartBeatEvent":
                        Console.WriteLine("HeartBeat");
                        Console.WriteLine("\tProcess: {0}",
                            ev["ProcessName"]);
                        Console.WriteLine("\tApp: {0}",
                            ev["ApplicationUrl"]);
                        Console.WriteLine("\tWorkingSet: {0}",
                            ev["WorkingSet"]);
                        Console.WriteLine("\tThreads: {0}",
                            ev["ThreadCount"]);
                        Console.WriteLine("\tManagedHeap: {0}",
                            ev["ManagedHeapSize"]);
                        Console.WriteLine("\tAppDomainCount: {0}",
                            ev["AppDomainCount"]);
                        break;
    
                    // Process the request error event. 
                    case "RequestErrorEvent":
                        Console.WriteLine("Error");
                        Console.WriteLine("Url: {0}",
                            ev["RequestUrl"]);
                        Console.WriteLine("Path: {0}",
                            ev["RequestPath"]);
                        Console.WriteLine("Message: {0}",
                            ev["EventMessage"]);
                        Console.WriteLine("Stack: {0}",
                            ev["StackTrace"]);
                        Console.WriteLine("UserName: {0}",
                            ev["UserName"]);
                        Console.WriteLine("ThreadID: {0}",
                            ev["ThreadAccountName"]);
                        break;
    
                    // Process the application lifetime event. 
                    case "ApplicationLifetimeEvent":
                        Console.WriteLine("App Lifetime Event {0}",
                            ev["EventMessage"]);
    
                        break;
    
                    // Handle events for which processing is not
                    // provided.
                    default:
                        Console.WriteLine("ASP.NET Event {0}",
                            ev["EventMessage"]);
                        break;
                }
            } // End DisplayEventInformation.
    
            // The main entry point for the application.
            static void Main(string[] args)
            {
                // Get the name of the computer on 
                // which this program runs.
                // Note that the monitored application must also run 
                // on this computer.
                string machine = Environment.MachineName;
    
                // Define the Common Information Model (CIM) path 
                // for WMI monitoring. 
                string path = String.Format("\\\\{0}\\root\\aspnet", machine);
    
                // Create a managed object watcher as 
                // defined in System.Management.
                string query = "select * from BaseEvent";
                ManagementEventWatcher watcher =
                    new ManagementEventWatcher(query);
    
                // Set the watcher options.
                TimeSpan timeInterval = new TimeSpan(0, 1, 30);
                watcher.Options =
                    new EventWatcherOptions(null,
                    timeInterval, 1);
    
                // Set the scope of the WMI events to 
                // watch to be ASP.NET applications.
                watcher.Scope =
                    new ManagementScope(new ManagementPath(path));
    
                // Set the console background.
                Console.BackgroundColor = ConsoleColor.Blue;
                // Set the foreground color.
                Console.ForegroundColor = ConsoleColor.Yellow;
                // Clear the console.
                Console.Clear();
    
                // Loop indefinitely to catch the events.
                Console.WriteLine(
                    "Listener started. Enter Cntl-C to terminate");
    
    
                while (true)
                {
                    try
                    {
                        // Capture the WMI event related to 
                        // the Web event.
                        ManagementBaseObject ev =
                            watcher.WaitForNextEvent();
                        // Display the Web event information.
                        DisplayEventInformation(ev);
    
                        // Prompt the user.
                        Console.Beep();
    
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: {0}", e);
                        break;
                    }
                }
            }
        }
    }
    
  2. 콘솔 응용 프로그램을 빌드합니다. System.Management 네임스페이스에 대한 참조를 포함해야 할 수도 있습니다.

WMI 이벤트에 대한 응용 프로그램 구성

표준 WmiWebEventProvider 공급자에는 ASP.NET 상태 이벤트와 연결된 WMI 이벤트를 생성할 논리가 포함되어 있습니다.

WMI를 사용하여 ASP.NET 상태 모니터링 이벤트를 수신하도록 ASP.NET 응용 프로그램을 구성하려면

  1. 응용 프로그램 루트에서 Web.config 파일을 만들거나 엽니다.

    기본 Web.config 파일은 다음 코드 예제와 같습니다.

    <?xml version="1.0"?>
    <configuration xmlns="https://schemas.microsoft.com/.NetConfiguration/v2.0">
        <appSettings/>
        <connectionStrings/>
        <system.web>
        </system.web>
    </configuration>
    
  2. system.web 섹션 내에 다음 코드 줄을 추가하여 상태 모니터링을 사용하도록 설정합니다.

            <healthMonitoring enabled="true">
            </healthMonitoring>
    
  3. healthMonitoring 섹션 내에 다음 코드 줄을 추가하여 WmiWebEventProvider 공급자를 통해 상태 모니터링 데이터를 전달하도록 응용 프로그램을 구성합니다. WmiWebEventProvider 공급자는 이미 구성되어 있습니다. 웹 이벤트가 처리되도록 하려면 규칙만 다음과 같이 정의하면 됩니다.

               <rules>
                  <add 
                     name="Wmi Listener"
                     eventName="All Events" 
                     provider="WmiWebEventProvider" 
                     profile="Critical"/>
               </rules>
    

    추가된 규칙의 eventName 특성은 모든 웹 이벤트가 WmiWebEventProvider 공급자에 디스패치될 수 있도록 합니다.

수신기 응용 프로그램 테스트

수신기 응용 프로그램을 만든 다음 빌드하고 WMI 이벤트를 통해 상태 모니터링을 사용하도록 웹 사이트를 구성한 후에는 웹 사이트에서 페이지를 요청하는 동안 수신기 응용 프로그램을 실행하여 상태 이벤트가 캡처되는지 확인할 수 있습니다.

수신기 콘솔 응용 프로그램을 테스트하려면

  1. 상태 모니터링을 사용하도록 설정한 웹 응용 프로그램에 ASP.NET 페이지를 만듭니다.

  2. 명령줄에서 수신기 응용 프로그램을 실행합니다.

    명령 창의 색이 다음과 같은 노란색 텍스트가 표시된 파란색 배경으로 바뀝니다.

    Listener started. Enter CntlC to terminate
    
  3. 웹 브라우저를 연 다음 웹 응용 프로그램에서 페이지를 요청합니다.

    페이지 렌더링이 끝나기 전에 수신기 응용 프로그램이 실행 중인 명령 창에 다음 텍스트가 표시됩니다.

    ASP.NET Event URL authorization succeeded for the request.
    ASP.NET Event File authorization succeeded for the request.
    

    이를 통해 수신기가 ASP.NET에서 URL 권한 부여 이벤트와 파일 권한 부여 이벤트를 catch했음을 확인할 수 있습니다.

다음 단계

표시된 WMI 수신기는 간단한 콘솔 응용 프로그램이지만 WMI 수신기를 빌드하고, 상태 이벤트를 디스패치하도록 응용 프로그램을 구성하는 데 필요한 기본 단계를 보여 줍니다. 이제부터는 웹 응용 프로그램을 모니터링하는 여러 가지 다른 방법을 배울 수 있습니다. 다음과 같은 제안을 따르는 것이 좋습니다.

  • Windows 응용 프로그램을 사용하여 WMI 이벤트를 수집할 수 있는 방법을 조사합니다.

  • 이벤트 형식에 따라 좀 더 복잡한 처리 기능의 사용 방법을 조사합니다.

  • WMI에 대한 내용 및 .NET Framework에서 WMI 기능을 통합하는 방법에 대해 배웁니다. 자세한 내용은 System.Management, System.Management.Instrumentation을 참조하십시오.

  • MSDN Library에서 WMI(Windows Management Instrumentation)와 MOF(Managed Object Format)를 검색합니다.

참고 항목

참조

healthMonitoring 요소(ASP.NET 설정 스키마)

WmiWebEventProvider

System.Management

System.Management.Instrumentation

기타 리소스

WMI를 사용하여 ASP.NET 상태 모니터링 이벤트 전달