ASP.NET 2.0 also provides full-featured application monitoring and health monitoring. The system is composed of a fully extensible event model and an event engine that can send events to a variety of receivers. For example, you can configure your ASP.NET application to send a daily email indicating that the server is running and including the amount of available memory. Likewise, you can create a health event linked to an unhandled exception. Exception content, request headers, and time and date can all be sent to an error logging database.
ASP.NET 2.0 includes built-in events, including heartbeats, application lifetime events (start/stop/compile), and error trap events (unhandled exceptions). However, you can easily build on top of these base classes to recreate and raise your own events from your application. For example, you might create a custom event to record when the hundredth user clicks a particular link.
The really powerful feature of the ASP.NET 2.0 health monitoring system is that it is fully configurable through the web.config and machine.config files. Using normal XML, you can define events, define providers (event receivers), and send specific events to specific providers.
Creating Events Events are similar in structure to exceptions. In other words, the event class itself has almost no functionality except as a message container. In terms of health monitoring, all events inherit from System.Web.Management.WebBaseEvent. However, you can also derive from high-level base classes that are used for specialized purposes, such as collecting HTTP request data or handling exceptions.
Listing 4. Custom events
using System;
using System.Web.Management;
public class CustomEvent : WebBaseEvent
{
public const int EventCode = WebEventCodes.WebExtendedBase + 10;
public MyEvent(string message, object eventSource)
: base(message, eventSource, EventCode)
{ }
}
The most important part of creating a custom event is to provide a unique EventCode. All built-in event codes are in the WebEventCodes enumeration. Custom events should have numbers starting from WebEventCodes.WebExtendedBase + 1. Other than that the only common task in creating custom events is to initialize the event correctly.
Using Events Although built-in events fire automatically, you can add code to your application to fire custom events at any time.
Listing 5. Raising an event
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{ // Raise a custom event MyEvent myEvent =
new MyEvent("loading webevent sample page", this); myEvent.Raise(); }
</script>
When you raise an event from an ASP.NET page, you simply create a new instance of the event and then execute the Raise() method. The Raise() method automatically delivers the event instance to the health monitoring engine. The engine then maps the event to profiles and providers and hands the event off to the correct provider. The provider ultimately delivers the event to the correct receiver.
Configuring Health Monitoring Health monitoring is configured in a new area in the machine.Config or Web.Config file. You can configure the section to set up a web heartbeat that periodically reports the status of the application. You can also configure your application to generate events and pass the events through various providers.
Configuring events must identify each event in the event mapping area. Events are identified by a unique name and complete type. The event name is used as a link in the rules area.
Listing 6. Event mapping area
<!-- Event mappings define the events that are monitored -->
<eventMappings>
<add name="SampleWebRequests"
type="Samples.AspNet.SampleWebRequestEvent, SampleWebRequestEvent,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=f0c63b9a560d5e5a"/>
</eventMappings>
ASP.NET 2.0 ships with several built-in events, configured with the following names:
• All events. All event names capture any WebBaseEvent. This event class is a broad catch-all for every event captured by the health monitoring system.
• Heartbeat. Heartbeat events use WebHeartBeatEvent to provide periodic notifications about the status of a Web application.
• Application lifetime events. Application lifetime events include starting and stopping the application, and recompiling part or all of the application. These events are based on WebApplicationLifetimeEvent and report the date, time and current status when the lifetime event occurs.
• All errors. The All Error category collects any anomalies or errors detected by the system. These events are based on WebBaseErrorEvent.
• Infrastructure errors. Use WebErrorEvent to catch errors related to the ASP.NET runtime or IIS. These events are subclasses of all error categories and are primarily relevant to system administrators rather than application developers.
• Request processing error. Any error or exception that occurs during the request triggers a WebRequestErrorEvent. This event logs the incoming request and the errors associated with processing the request. Request processing errors are also a subset of all error categories.
• All reviews. You can use a health monitoring system to provide audit attempts through WebAuditEvents. This event automatically records the actions of active users in a web application. If you are using impersonation, auditing events will help you keep track of who is using your application and how they are being used.
• Failure audit. WebFailureAuditEvent is a special audit event type that is triggered when a user attempts to log in to your Web site with an invalid username or password. This event also occurs when a user cannot be authenticated for the specified resource.
• Successful review. WebSuccessAuditEvent is the counterpart to a failure event that occurs whenever the user has authenticated or performed some other action that requires audit logging.
Custom events are easy to create, although you must add code to your application to raise the event.
Configuring Providers Each provider must be registered in a configuration file. Registering a provider requires the application's unique name and type. This type contains the full strong name of the actual provider class. The name of the provider is used as a link in the rules area.
Listing 7. Provider
<healthMonitoring Enabled="true" heartBeatInterval="0">
<!-- Providers link health events to various targets such as WMI or SMTP email -->
<providers>
<add name="WmiEventProvider" type="System.Web.Management.WebWmiEventProvider,
System.Web,Version=1.2.3400.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
ASP.NET 2.0 comes with providers for WMI, Windows Event Monitor, SMTP e-mail, and SQL Server databases. By extending the correct base class, you can create custom providers to connect to other event receivers.
Mapping events to providers
The final step in configuring health monitoring is to connect events to providers with rules. Rules provide a link between a good event name, event class, provider, and event profile or category. You can also use rules to define a minimum time interval for triggering specific events.
Listing 8. Rules
<!-- Rules link events to providers and profiles, and define intervals for event checking -->
<rules>
<add name="Custom Database Events" eventName="CustomDBEvents"
provider="WmiEventProvider" profile="Database" minInterval="00:01:00" />
<add name="Standard Web Requests" eventName="All Events"
provider="SqlEventProvider" profile="Default" minInterval="00:01:00" /> </rules>
</healthMonitoring>
Rules perform several different tasks configured by different properties:
• name. The rule name is the friendly name that appears when the event is sent to the receiver.
• eventName. eventName maps to an event configured in the zone.
• provider. Provider is a link to the provider configured in the zone. Any events matching this rule will be delivered through this provider to targets supported by this provider. For example, System.Web.Management.SqlWebEventProvider automatically writes events to a SQL Server database.
• profile. Different providers use profile properties as filters for displaying events. For example, an email provider might send an immediate message for any event with an "urgent" profile, but might also only send a daily email with a compilation of "routine" profile events for that day.
• minInterval. Some events, such as heartbeats, must fire within the shortest possible time interval. You can use this property to set the minimum event interval.
This configuration area allows you to set up various health-related events and map the events to various providers. For example, you might set up a heartbeat that sends a WMI event every 10 minutes. Likewise, you can set up an email alert for any uncaught exceptions.
Related articles:
http://support.microsoft.com/default.aspx?scid=kb%3Bzh-cn%3B893664
http://blog.csdn.net/dshpsky/archive/2006/06/18/810893.aspx