Health Monitoring

Keep the Health of ASP.NET Applications Under Strict Control

Dino Esposito

October 30, 2009

10 Min Read
ITPro Today logo in a gray background | ITPro Today

CoreCoder

LANGUAGES: C#

ASP.NETVERSIONS: 2.0

 

Health Monitoring

Keep the Health of ASP.NET Applications Under Strict Control

 

By Dino Esposito

 

In classic ASP and ASP.NET 1.x, it is difficult for Website administrators to diagnose problems and monitor Web applications. In caseof run-time errors, the richest source of information is simply HTTP errors. Insome cases, another helpful source of information can be trace messagesscattered throughout the code in places that the developer considerspotentially buggy or problematic. Classic ASP and ASP.NET 1.x feature a limitedset of event log messages that can be used to monitor the health of installedapplications. The bad thing about this form of event logging is that it worksin a reactive manner. Administrators receive messages and pass them on to thedevelopment team. The development team must analyze the cause of the error andmake a decision. All of this happens offline as, all the while, the connecteduser gets a more or less friendly error page.

 

In ASP.NET 2.0, a new subsystem known as the healthmonitoring system enables a proactive approach to application monitoring. Itworks by raising a number of application events that carry health-monitoringdata through various mechanisms and storage media. In this way, collecting andprocessing run-time information is easier than ever and can be doneprogrammatically through code incorporated in the body of the application.

 

Health Monitoring at a Glance

ASP.NET health-monitoring features can be used to performa number of tasks. You can monitor the health of live applications to ensurethat they are working properly. You can monitor applications individually, andeven across a Web farm. The health subsystem helps significantly in thediagnosis of applications that appear to be failing and to log any sort ofevents. It is important to notice that you can log and process not just errorsbut also events that signal particular situations that can be useful for you toexamine. More in detail, the ASP.NET health monitoring system instruments yourapplication for predefined and custom events related to performance, security,failures, and anomalies.

 

The subsystem works by sending events to registeredlisteners, named Web event providers. A Web event provider typically processesthe information associated with a health event by recording the event on apersistent medium. Each event contains information such as type, code, and adescriptive message. Not all events are of interest to all providers. Themapping between providers and fired events is set in the web.config file.

 

The health monitoring system takes advantage of theASP.NET provider model, meaning that it exposes some core functionality througha replaceable component, called the provider. The provider model allows ASP.NETdevelopers to become familiar with a single API to program a service,regardless of how that particular service interoperates with the rest of thesystem and data storage layers. The theory behind this behavior is codified inthe popular behavioral design pattern the pattern strategy.

 

The strategy pattern indicates an expected behavior thatcan be implemented through a variety of interchangeable algorithms. Eachapplication selects the algorithm that best fits, while keeping the public,observable behavior intact. Applied to an ASP.NET service such as healthmonitoring, the pattern isolates in the replaceable algorithm the code to saveand process run-time information and serve them to the developers through acommon and unchangeable API. Let s take a look at how to enable and configurethe health monitoring system.

 

The Section

The health monitoring system tracks significant events inthe lifetime of deployed applications and fires related events to providers.The event contains actual information about what happened; the providerprocesses the information. The system is configured through the section in the web.config file. The overall schema is shown below:

 

  enabled="true|false"   heartbeatInterval="HH:MM:SS">    ...    ...   ...    ...    ...   The attribute enabled indicates whether health monitoringis enabled or not. By default, health monitoring is turned on and must bedisabled explicitly if you don t want it on. The core element of the system isthe heart-beat event. The heart-beat event serves as a timer for the wholesubsystem and is raised at regular intervals to capture useful run-time stateinformation. The heartbeatInterval attribute indicates how often the heart-beatevent is raised. You can set it to a number and it will indicate the period inseconds. You can also use an HH:MM:SS schema to specify a period with themaximum flexibility. The default interval for the heart-beat event is set to 0,meaning that no heart-beat event is raised.   The heart-beat is only one of the events that the healthmonitoring system can detect. Other events track unhandled exceptions, requestprocessing, application lifetime, and success and failure audits. Childsections listed in Figure 1 allow you to configure the whole health subystem.   Element Description bufferModes Used with SQL Server and e-mail built-in Web event providers to determine how often to flush the various events to the provider and the size of the intermediate buffer. eventMappings Maps friendly event names to the event classes. profiles Defines parameter sets to use when configuring events. providers Defines the health monitoring providers that process events. rules Maps events to providers. Figure 1: Elementsto configure ASP.NET health monitoring.   The monitoring system pings the application to determinewhat s going bad and reports to listeners. You don t have to be a super-expertdeveloper to suspect that this practice may have a devastating impact onperformance. Depending on the selected Web event provider, the action performedby the provider can be quite costly, such as sending an e-mail to theadministrator or writing a record to a relational database. In this case, youcan turn on buffering through the section. If you enablebuffering, the provider buffers event information according to the specified modeand inserts the event information into the database in a batch. You cancustomize buffering behavior by selecting a predefined buffering mode: Analysis,Notification, or Critical Notification. Each mode has its own set of properties,such as the size of the buffer and frequency for flushing the buffer.Alternatively, you can create custom buffering modes and configure the providerto use one of the buffer modes you have defined.   Under the section you define eventsthat will be trapped and recorded. Each event is characterized by a class. Inthis section you give each event a friendly name and register new custom eventclasses:          type="System.Web.Management.WebFailureAuditEvent" />  :   Web events contain information about the current workerprocess, AppDomain, request and response data, and application andconfiguration errors. All event classes inherit from the WebBaseEvent baseclass. Event classes are listed in Figure 2.   Event Class Description WebApplicationLifetimeEvent Represents a significant event in the lifetime of an application, including start-up and shut-down events. WebAuthenticationFailureAuditEvent Provides information about authentication failures. WebAuthenticationSuccessAuditEvent Provides information about successful authentication events. WebErrorEvent Provides information about errors caused by problems with configuration or application code. WebFailureAuditEvent Provides information about security failures. WebHeartbeatEvent Serves as a timer for the ASP.NET health monitoring system. These events are raised at an interval defined by the heartbeatInterval attribute of the healthMonitoring configuration section. WebRequestErrorEvent Defines the event that carries information about Web request errors. WebSuccessAuditEvent Provides information about successful security events. WebViewStateFailureAuditEvent Provides Web application viewstate failure information. Figure 2: Health-monitoringevents.   Other configuration sections are defined to fine-tune thebehavior of the system. The section allows you to createprofiles; that is, sets of configuration attributes that can be collectivelyadded to a Web event provider. The section instead lists allregistered providers and allows you to define custom providers, as well.Finally, the section defines which events are processed by whichprovider.   ASP.NET 2.0 comes with a number of built-in eventproviders. Each provider writes event information to a distinct storage medium.Let s briefly analyze some of them (see Figure 3 for a quick list).   Provider Description EventLogWebEventProvider Records errors to the Windows Application Event Log. SimpleMailWebEventProvider Sends an e-mail message with a fixed text. TemplateMailWebEventProvider Sends a customizable e-mail message. SqlWebEventProvider Records errors to a SQL Server database. TraceWebEventProvider Records errors as ASP.NET trace messages. WmiWebEventProvider Records errors through the WMI system. Figure 3: Web eventproviders.  The Event Log Provider EventLogWebEventProvider works by logginghealth-monitoring events into the Windows Application Event Log. By default,the provider tracks failure audits and all other application errors. Thefollowing excerpt from the global web.config file illustrates the configurationof the provider:         provider="EventLogProvider" ... />      provider="EventLogProvider" ... />   SimpleMailWebEventProvider sends e-mail notifications ofan event to the specified recipient (see Figure 4).          type="System.Web.Management.SimpleMailWebEventProvider,..."       from="[email protected]"       to="[email protected]"       bodyHeader="..."       bodyFooter="..."       subjectPrefix="..." />        eventName="AllErrors"      provider="CriticalMailEventProvider" /> Figure 4: SimpleMailWebEventProvidersends e-mail notifications of an event to the specified recipient.   To use the mail provider you must have the mail SMTP hostproperly configured. Here s what you need in the web.config file:                                    The format of the message sent throughSimpleMailWebEventProvider can t be modified. If you want to build moresophisticated e-mail messages, opt for TemplatedMailWebEventProvider, which hasan additional property that references an ASP.NET page to be used as atemplate. TemplateMailWebEventProvider counts a static property through whichyou can access any event-related information and populate the template page.Any output in the page is used to prepare the message sent to the recipient.   SqlWebEventProvider writes event information to theconfigured SQL Server database. The default target database is aspnetdb.mdf, thesame local SQL Server 2005 that other ASP.NET providers use to persist data. The table where data is flushed is namedaspnet_WebEvent_Events. To start using this provider you need to add a section.   TraceWebEventProvider sends intercepted health events outas ASP.NET trace messages that can be seen through the trace.axd utility. Forthis provider to work, ASP.NET tracing must be enabled.   Finally, WmiWebEventProvider forwards the interceptedevents to the Windows Management Instrumentation (WMI) system. WMI is anoperating system component that administrators and developers use to query andprocess system information. You typically add the following sectionto start the WMI event provider:             provider="WmiWebEventProvider" />   The built-in set of event providers covers the most commonstorage media. Additional providers can be created, but the main reason fordoing so is to record events in a SQL Server database with a different schemaor in another DBMS system, such as Oracle or DB2. If you need to get output ina particular text format, it is preferable that you use the Event Log provider,then export the recorded information in a suitabletext format. Writing a custom provider is certainly possible, but exportingdata if functionally adequate is much simpler and faster.  Conclusion Health monitoring is an ASP.NET system feature that allowsthe production staff to monitor the status of a deployed application and tracksignificant events related to performance, behavior, and failures. The systemworks by firing events to ad hoc providers. The event delivers informationabout what happened, whereas the provider processes the information. Typically,the provider records the event and forwards information to a listener. ASP.NETcomes with a built-in set of event providers, but others can be defined to suitparticular storage needs you may have.  Dino Esposito is aSolid Quality Learning mentor and author of ProgrammingMicrosoft ASP.NET 2.0 Core Reference and ProgrammingMicrosoft ASP.NET 2.0 Applications-Advanced Topics, both from MicrosoftPress. Based in Italy,Dino is a frequent speaker at industry events worldwide. Join the blog at http://weblogs.asp.net/despos.      

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like