WmiWebEventProvider Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Implementa um fornecedor de eventos que mapeia eventos de monitorização de saúde do ASP.NET para eventos do Windows Management Instrumentation (WMI).
public ref class WmiWebEventProvider : System::Web::Management::WebEventProvider
public class WmiWebEventProvider : System.Web.Management.WebEventProvider
type WmiWebEventProvider = class
inherit WebEventProvider
Public Class WmiWebEventProvider
Inherits WebEventProvider
- Herança
Exemplos
O exemplo seguinte mostra como criar um consumidor de eventos WMI emitidos pela monitorização de saúde do ASP.NET como resultado de eventos de saúde de aplicações Web.
Note
A WmiWebEventProvider classe e os tipos de eventos de saúde a monitorizar já estão configurados por defeito. A única coisa que precisa de fazer é definir a regra para todos os eventos de saúde. Lembre-se de que os eventos de saúde não são enviados ao WmiWebEventProvider prestador por defeito.
using System;
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)
{
// It contains the name of the WMI raised
// event. This is 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. The monitored application must also run
// on this computer.
string machine = Environment.MachineName;
// Define the Common Information Model (CIM) path
// for WIM 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 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.
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;
}
}
}
}
}
Imports System.Management
' Capture WMI events associated with
' ASP.NET health monitoring types.
Class SampleWmiWebEventListener
'Displays event related information.
Shared Sub DisplayEventInformation(ByVal ev _
As ManagementBaseObject)
' It contains the name of the WMI raised
' event. This is 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
' End DisplayEventInformation.
' The main entry point for the application.
Shared Sub Main(ByVal args() As String)
' Get the name of the computer on
' which this program runs.
' Note. The monitored application must also run
' on this computer.
Dim machine As String = Environment.MachineName
' Define the Common Information Model (CIM) path
' for WIM 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 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
End Class
O exemplo seguinte é um excerto de ficheiro de configuração que mostra uma secção de configuração <healthMonitoring> que permite ASP.NET usar o fornecedor WmiWebEventProvider para processar todos os eventos de monitorização de saúde.
<healthMonitoring>
<rules>
<add
name="Using Wmi"
eventName="All Events"
provider="WmiWebEventProvider"
profile="Critical"/>
</rules>
</healthMonitoring>
Observações
A monitorização do estado do ASP.NET permite que as equipas de produção e operações gerenciem aplicações Web implementadas. O System.Web.Management namespace contém os tipos de eventos de saúde responsáveis por empacotar os dados de estado de saúde da aplicação e os tipos de fornecedores responsáveis pelo processamento desses dados. Inclui também tipos de apoio que ajudam na gestão de eventos de saúde.
A ASP.NET utiliza esta classe para mapear eventos de monitorização de saúde para eventos WMI. Para permitir a entrega de eventos de monitorização de saúde ASP.NET ao subsistema WMI, deve configurar a classe WmiWebEventProvider adicionando as definições apropriadas na secção <healthMonitoring> do ficheiro de configuração.
A informação contida no ficheiro Aspnet.mof descreve os parâmetros dos eventos WMI levantados quando ASP.NET eventos de monitorização de saúde são encaminhados para a classe WmiWebEventProvider e mapeados para eventos WMI. O ficheiro Aspnet.mof está armazenado no diretório de build do .NET Framework, por exemplo %windir%\Microsoft.NET\Framework\BuildNumber. Para mais informações sobre o reporte de eventos de monitorização de saúde como eventos de WMI, consulte Using WMI to Deliver ASP.NET Health Monitoring Events.
Note
Na maioria dos casos, poderá usar os tipos de monitorização de saúde ASP.NET tal como implementados, e controlará o sistema de monitorização de saúde especificando valores na secção de configuração <healthMonitoring>. Também pode recorrer aos tipos de monitorização de saúde para criar os seus próprios eventos e prestadores personalizados. Para um exemplo de criação de um prestador personalizado, veja Como: Implementar o Exemplo de Prestador Personalizado de Monitorização de Saúde.
Construtores
| Name | Description |
|---|---|
| WmiWebEventProvider() |
Inicializa uma nova instância da WmiWebEventProvider classe. |
Propriedades
| Name | Description |
|---|---|
| Description |
Recebe uma descrição breve e amigável, adequada para exibição em ferramentas administrativas ou outras interfaces de utilizador (UIs). (Herdado de ProviderBase) |
| Name |
Recebe o nome amigável usado para se referir ao fornecedor durante a configuração. (Herdado de ProviderBase) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| Flush() |
Remove todos os eventos do buffer do fornecedor. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| Initialize(String, NameValueCollection) |
Define os valores iniciais deste objeto. |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ProcessEvent(WebBaseEvent) |
Processa o evento passado para o fornecedor. |
| Shutdown() |
Realiza tarefas associadas ao encerramento do fornecedor. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |