How To: Use Health Monitoring in ASP.NET 2.0

 

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

patterns & practices Developer Center

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

Microsoft Corporation

August 2005

Applies To

  • ASP.NET version 2.0
  • SQL Server 2000

Summary

This How To shows you how to use health monitoring to instrument your application for a custom event. To create a custom health monitoring event, you create a class that derives from System.Web.Management.WebBaseEvent, configure the <healthMonitoring> element in your application's Web.config file, and instrument your code to raise the event. Custom events are useful for recording security related events beyond those automatically recorded by ASP.NET health monitoring. For example, you could add an event that tracks successful and unsuccessful attempts to access restricted and sensitive business logic.

Contents

Objectives
Overview
Summary of Steps
Step 1. Create a Custom Web Event
Step 2. Create an ASP.NET Application for Monitoring
Step 3. Configure Health Monitoring
Step 4. Instrument Your Application
Step 5. Test Health Monitoring
More Information
Additional Resources

Objectives

  • Create a custom health monitoring event.
  • Configure health monitoring.
  • Instrument an application to raise a custom event.

Overview

ASP.NET version 2.0 health monitoring supports many standard events that you can use to monitor the health of your application. Examples of security related events that are automatically generated include logon failures and successes when using the ASP.NET membership system, attempts to tamper with or reuse forms authentication tickets, and infrastructure events such as disk access failures. This How To explains how to create custom events that use the same underlying infrastructure and raise them in your code to supplement the system-defined events.

Event Providers

ASP.NET version 2.0 health monitoring supports an event provider model. Event providers encapsulate the underlying event stores and provide a consistent API. You can configure event providers to log events to different event sinks. The following providers are supported:

  • SimpleMailWebEventProvider. This provider sends e-mail for event notifications.
  • TemplatedMailWebEventProvider. This provider uses templates to define and format e-mail messages sent for event notifications.
  • SqlWebEventProvider. This provider logs event details to a SQL Server database. If you use this provider, you should encrypt the connection string in your Web.config file by using the Aspnet_regiis.exe tool.
  • EventLogWebEventProvider. This provider logs events to the Windows application event log.
  • TraceWebEventProvider. This provider logs events as ASP.NET trace messages.
  • WmiWebEventProvider. This provider maps ASP.NET health monitoring events to Windows Management Instrumentation (WMI) events.

You can also create custom event providers to write events to custom stores by creating a class that inherits from System.Web.Management.WebEventProvider.

For more details about the standard events, and suggested security-related events you should consider reporting through custom events, see How To: Instrument ASP.NET 2.0 Applications for Security.

Summary of Steps

Perform the following steps to create a custom Web event and configure health monitoring to use that event in your ASP.NET application:

  • Step 1. Create a custom Web event.
  • Step 2. Create an ASP.NET Application for monitoring.
  • Step 3. Configure health monitoring.
  • Step 4. Instrument your application.
  • Step 5. Test health monitoring.

Step 1. Create a Custom Web Event

In this step, you create a custom Web event by creating a class that inherits from System.Web.Management.WebAuditEvent.

To create a custom Web Event

  1. Use Visual Studio .NET 2005 to create a new class library named MyWebEvents.

  2. Rename Class1.cs to MyCriticalEvent.cs.

  3. Add a reference to System.Web and add the following using statements to the top of the MyCriticalEvent.cs.

    using System.Web; // For the reference to HttpContext
    using System.Web.Management;
    
    
  4. Derive MyCriticalEvent from WebAuditEvent and create appropriate public constructors that call the protected equivalents in the parent WebAuditEvent class as shown in the following code. Notice how this code also obtains some custom details from the HttpContext inside the event's constructors.

    public class MyCriticalEvent : WebAuditEvent
    {
        private string userID;
        private string authType;
        private bool isAuthenticated;
    
        public MyCriticalEvent(string msg, object eventSource, int eventCode)
            : base(msg, eventSource, eventCode)
        {
            // Obtain the HTTP Context and store authentication details
            userID = HttpContext.Current.User.Identity.Name;
            authType = HttpContext.Current.User.Identity.AuthenticationType;
            isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
        }
    
        public MyCriticalEvent(string msg, object eventSource, int eventCode, 
                               int eventDetailCode)
                : base(msg, eventSource, eventCode, eventDetailCode)
        {
            // Obtain the HTTP Context and store authentication details
            userID = HttpContext.Current.User.Identity.Name;
            authType = HttpContext.Current.User.Identity.AuthenticationType;
            isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
        }
    } 
    
    
  5. If you want to log custom details, such as authentication details in this example, override the FormatCustomEventDetails method to augment the standard event output with custom data, as shown in the following code example.

    // Formats Web request event information.
    // This method is invoked indirectly by the provider using one of the
    // overloaded ToString methods. If buffering is enabled, this method is
    // called asynchronously on a non-Web request thread, where the 
    // HttpContext is not available.
    public override void FormatCustomEventDetails(WebEventFormatter formatter)
    {
        base.FormatCustomEventDetails(formatter);
        formatter.AppendLine("User ID: " + userID);
        formatter.AppendLine("Authentication Type: " + authType);
        formatter.AppendLine("User Authenticated: " + 
                              isAuthenticated.ToString());
        formatter.AppendLine("Activity Description: Critical Operation");
    }
    
    

    Note   With buffering enabled for the provider, the FormatCustomEventDetails method is called on a separate non-Web request thread, where the HttpContext is not available. If you need to access information from the HttpContext, access the context in the class' constructor, extract the required information (do not keep the pointer to the HttpContext object), and save the information in the event's private instance state.

  6. Compile the assembly. If you want to use the assembly in multiple applications, you should sign the assembly with a strong-name and install it in the global assembly cache.

Step 2. Create an ASP.NET Application for Monitoring

In this step, you create an ASP.NET application that you will monitor and instrument with a custom event.

To create an ASP.NET application

  1. Use Visual Studio .NET 2005 to create a new ASP.NET Web application.
  2. Add a reference to the assembly that contains your custom Web event that you created earlier.
  3. Add a Web.config file to your application so that you can configure health monitoring.

Step 3. Configure Health Monitoring

By default, health monitoring is enabled for ASP.NET applications. You can see the default configuration in the machine-level Web.config.comments file in the %windir%\Microsoft .NET\Framework\{version}\CONFIG configuration file directory.

The <healthMonitoring> element contains the following sub-elements.

<healthMonitoring heartbeatInterval="0" enabled="true">
  <bufferModes/>
  <providers/>
  <profiles/>
  <rules/>
  <eventMappings/>
</healthMonitoring>
  

To make further changes to health monitoring configuration, you can apply configuration settings to your application's specific Web.config file or to the machine-level Web.config file if you want to configure all Web applications on your server.

To configure health monitoring, configure the following elements:

  • <bufferModes>.
  • <providers>.
  • <profiles>.
  • <rules>.
  • <eventMappings>.

<bufferModes>

Buffer modes are used to define the buffering properties used by any provider that inherits from System.Web.Management.BufferedWebEventProvider. Currently, this includes MailWebEventProvider and SqlWebEventProvider. You can also derive custom Web event providers from that base class and use buffer modes.

You configure buffering to minimize the performance impact and overhead of recording events. You can use the <bufferModes> configuration to define how long events are buffered before they are written to the provider and you can distinguish between urgent or critical events and regular events.

You can use any of the default buffer modes (Critical Notification, Notification, Analysis or Logging) configured in the machine-level Web.config.default file or you can configure a custom buffer mode.

Note   For buffering to be enabled, you need to set buffer="true" on your provider configuration. You can reference the specific buffering configuration by using the bufferMode attribute on your provider definition as shown in the following code example.

<providers>
  <add name="providerName" buffer="true" bufferMode="bufferModeName" ... />
</providers>
  

To configure a custom buffer mode

  • Add the following configuration to your application's Web.config file.

    <healthMonitoring>
      <bufferModes>
        <add name="Extra Critical Notification"
          maxBufferSize="10"
          maxFlushSize="5"
          urgentFlushThreshold="1"
          regularFlushInterval="Infinite"
          urgentFlushInterval="00:01:00"
          maxBufferThreads="1"
        />
      </bufferModes>
    </healthMonitoring>
    
    

The attributes are as follows:

  • name. This is a name for the buffer mode used to reference it from other elements. For example, the <provider> element references the specific buffer mode configuration by referencing the name in its bufferMode attribute.
  • maxBufferSize. This is the maximum number of events that can be buffered by a provider before flushing them out and writing them to a store.
  • maxFlushSize. This is the maximum number of events per flush. Its value should be between 1 and maxBufferSize.
  • urgentFlushThreshold. This is the minimum number of events after which the events should be flushed. Its value should be less then or equal to maxBufferSize.
  • regularFlushInterval. This is the time interval per flush. Its value cannot be zero.
  • urgentFlushInterval. This is the minimum time between flushes. Its value must be between 0 and regularFlushInterval.
  • maxBufferThreads. This is the maximum number of threads used for flushing.

<providers>

You use the <providers> element to indicate what logging sinks are available for logged events. Note that any event providers you configure are not actually used for reporting events until you configure an event rule that specifies a configured provider. For more information, see "<rules>" later in this document.

The default configuration in the machine-level Web.config file defines the following providers:

  • EventLogWebEventProvider. This provider uses the EventLogWebEventProvider class to log to the Windows application event log.
  • SqlWebEventProvider. This provider uses the SqlWebEventProvider class for logging to a SQL Server or SQL Server Express instance.
  • WmiWebEventProvider. This provider uses the WmiWebEventProvider class for logging to WMI.

You can use any of these default event providers in your own health monitoring configuration, or you can configure new providers using any of the standard Web event provider classes. You can also use any custom Web event provider class that derives from the WebEventProvider base class.

To configure a SQL Server provider

If you want to configure an event provider that writes to a SQL Server instance, you must create the database used by the SqlWebEventProvider, configure a connection string, and configure a provider definition.

  1. Install the Web event database by running the following command from the Visual Studio 2005 command prompt:

    aspnet_regsql.exe -E -S <ServerName> -A w

    This command uses the following switches:

    • -E. This switch indicates to use Windows authentication to connect to the database.
    • -S <ServerName>. This switch indicates the name of the server where the database will be installed, or is already installed.
    • -A w. This switch indicates to add Web event support. This creates the relevant tables and stored procedures required by the SqlWebEventProvider.
  2. Create a SQL Server logon for your Web application's identity. For example, create a network service and then create a database user for this logon in the Aspnetdb database.

  3. Grant the database user execute permission on the aspnet_WebEvent_LogEvent stored procedure.

  4. Add the following connection string to your application's Web.config file.

    <connectionStrings> 
       <add name="MySqlConnection" connectionString=
      "Data Source=localhost;Initial Catalog=aspnetdb;Integrated Security=SSPI;" 
       /> 
    </connectionStrings>
    
    
  5. Add the following <providers> configuration within the <healthMonitoring> section in Web.config.

    <providers> 
      <add connectionStringName="MySqlConnection" 
         maxEventDetailsLength="1073741823" 
         buffer="true" 
         bufferMode="Extra Critical Notification"  
         name="MySqlWebEventProvider"  
         type="System.Web.Management.SqlWebEventProvider,System.Web,Version=2.0.0 .0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" /> 
    </providers> 
    
    

The following list describes the most important attributes you can set when configuring event providers:

  • name. This is a name for the buffer mode used to reference it from other elements.
  • type. This is a fully-qualified assembly reference to the provider class. This class should implement the System.Configuration.Provider.ProviderBase class.
  • buffer. If you are using the SqlWebEventProvider, use this attribute to enable event buffering. If this attribute is true, you must configure the bufferMode attribute. The default value is false.
  • bufferMode. If you are using the SqlWebEventProvider, use this attribute to specify the friendly name of the buffer mode to be used for buffering the events.
  • connectionStringName. If you are using the SqlWebEventProvider, use this attribute to specify the friendly name of the connection string used for connecting to the SQL Server database.
  • maxEventDetailsLength. This is the maximum length of the event details.

Note   If you want to use the SqlWebEventProvider to write to a local or remote SQL Server instance, use the Aspnet_regsql tool to configure the necessary database tables and roles as described in "Step 3. Configure Health Monitoring."

<profiles>

You use the <profiles> element to specify sets of parameters to use when configuring events. These parameters indicate the minimum number instances after which the event should be logged, the maximum number of instances, and the minimum interval between logging two similar events. This element can be critical in controlling the amount of information generated by defining when monitoring begins and when it ends by setting thresholds.

You can use this element to throttle the event occurrences. It can help prevent an attack against the eventing system itself or an event sink such as SQL Server or the event log. You can review the default settings in the machine-level Web.config file. The following code example shows the default settings from the machine-level Web.config.default file

<profiles>
  <add name="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00"
       custom="" />
  <add name="Critical" minInstances="1" maxLimit="Infinite" minInterval="00:00:00"
       custom="" />
</profiles>
  

You can use the default profiles in your own health monitoring configuration, and you can create new profiles.

To create a new profile

Add the following configuration to your application's Web.config file inside the existing <healthMonitoring> section, as shown in the following code example.

<profiles>
  <add name="Throttle"
    minInstances="1"
    maxLimit="1000"
    minInterval="00:00:01"/>
</profiles>
  

The <add> child element of the <profiles> element takes the following attributes:

  • name. This is a name for the buffer mode used to reference it from other elements.
  • minInstances. This is the minimum number of occurrences before an event is fired and logged.
  • maxLimit. If you want to set a maximum limit after which the specific events should stop firing and logging, use this attribute. The default setting is Infinite.
  • minInterval. If you want to set a minimum time interval between logging same event again, use this attribute. The format is "hh:mm:ss" and the default is 00:00:00.

<eventMappings>

Event mappings are named groups of events that you want to monitor. Note that you can include a particular event in more than one named group. The default event mappings name the most commonly required groupings of events. The default event mappings include two high-level groupings, All Events and All Audits, that include all events and all audits respectively. There are also subsets of each of those groupings. For example, All Errors includes all error events, and Failure Audits includes all audit failure events. You can review the default settings in the machine-level Web.config.default file.

You can use the default event mappings in your own health monitoring configuration or you can create new event mappings. You must create event mappings for any custom Web events you create.

To create an event mapping for a custom Web event

Add the following <eventMappings> element beneath the <healthMonitoring> section in your application's Web.config file. This references the custom event you created earlier.

<eventMappings> 
    <add name="My Critical Event" 
         type="MyWebEvents.MyCriticalEvent,MyWebEvents"/>        
</eventMappings>    
  

The <add> child element of the <eventMappings> element takes the following attributes:

  • name. This is the event name used to reference it from rules.
  • type. This is a fully-qualified assembly reference to the event class.
  • startEventCode. If you want to map events of a similar type in a specific range of event codes, use this attribute to set the starting event code for the range of events codes. The default setting is 0.
  • endEventCode. If you want to map events of a similar type in a specific range of event codes, use this attribute to set the top end of the range of event codes. The default setting is Infinite.

Step 4. Instrument Your Application

The ASP.NET runtime is instrumented to raise standard events at the appropriate time. You must instrument your application to raise custom events.

To create a test application for the MyCriticalEvent custom event

  1. Add the following using statements to your Default.aspx.cs file.

    using System.Web.Management;
    using MyWebEvents;  
    
    
  2. Add a button to your application's Default.aspx page and then add the following code to the button click event handler. The code creates a new custom event object of type MyCriticalEvent and calls its Raise method to fire the event.

    protected void Button1_Click(object sender, EventArgs e)
    {
      MyCriticalEvent testEvent = new MyCriticalEvent(
                                      "Critical Operation Performed", 
                                      this, 
                                      WebEventCodes.WebExtendedBase + 1);
      testEvent.Raise();
    }
    
    

    Note   When you raise a custom Web event, you must specify an event code that is greater than System.Web.Management.WebEventCodes.WebExtendedBase. Codes less than this value are reserved for system-generated events.

<rules>

Use the <rules> element to specify which events to log through which event provider. As an option, you can apply a profile to an event logging rule by specifying the name of a <profiles> entry, or you can apply the same attributes used in the <profiles> definition directly to a <rule> definition.

The default rule settings are defined in the machine-level Web.config.default file. The default rules cause the All Errors and Failure Audits event mappings to be logged to the Windows event log.

<rules>
 <add name="All Errors Default" eventName="All Errors" provider="EventLogProvider"
      profile="Default" minInstances="1" maxLimit="Infinite" 
      minInterval="00:01:00" custom="" />
 <add name="Failure Audits Default" eventName="Failure Audits"
      provider="EventLogProvider" profile="Default" minInstances="1"
      maxLimit="Infinite" minInterval="00:01:00" custom="" />
</rules>
  

You can disable the default rules mappings by using the <clear> child element inside the <rules> element, before adding your own rules.

To create a new event rule for a custom event

To create a new event rule for the custom event you created earlier, add the following <rules> element inside the <healthMonitoring> section in your application's Web.config, as shown in the following code example.

<rules> 
  <add name="Critical event" 
       eventName="My Critical Event" 
       provider="MySqlWebEventProvider" 
       profile="Throttle"/>
</rules>    
  

You can set the following attributes when defining rules:

  • name. This is a name for the buffer mode used to reference it from other elements.
  • eventName. This is the name of the event you want to monitor for which the rule is being configured.
  • provider. Use this attribute to specify the friendly name of the provider to use to log this event.
  • profile. If you want to use a preconfigured profile, specify the friendly name of the profile using this attribute. Note that if you specify a profile, the profile supplies the values for the minInstances, maxLimit and minInterval rules attributes.
  • minInstances. If you want to specify the minimum number of occurrences before an event is fired and logged, use this attribute. If you specify a profile attribute, this attribute overrides the minInstances value in the profile.
  • maxLimit. If you want to set a maximum limit after which the specific events should stop firing and logging, use this attribute. The default setting is Infinite. If you specify a profile attribute, this attribute overrides the maxLimit value in the profile.
  • minInterval. If you want to set a minimum time interval between logging the same event again, use this attribute. The format is "hh:mm:ss" and the default is 00:00:00. If you specify an equivalent profile attribute, this attribute overrides the minInterval value in the profile.

Step 5. Test Health Monitoring

In this step you test health monitoring and verify that your custom event works as expected.

To test health monitoring

  1. Build your Web application and browse to its Default.aspx page.

  2. Click the button to fire the custom event.

  3. Open the aspnet_WebEvent_Events table in the Aspnetdb database on your SQL Server. The Details column contains information similar to that shown in the following code example, including the custom event information.

    Event code: 100001
    Event message: Critical Operation Performed
    Event time: 7/11/2005 5:27:12 PM
    Event time (UTC): 7/12/2005 12:27:12 AM
    Event ID: 369ca7f9e5744234be2831aced671191
    Event sequence: 8
    Event occurrence: 1
    Event detail code: 0
    
    Application information:
        Application domain: /LM/w3svc/1/ROOT/HealthMonitoring-7-127656015969887178
        Trust level: Full
        Application Virtual Path: /HealthMonitoring
        Application Path: c:\inetpub\wwwroot\HealthMonitoring\
        Machine name: MACHINENAME
    Custom event details: 
        User ID: DomainName\UserName
        Authentication Type: Negotiate
        User Authenticated: True
        Activity Description: Critical Operation
    
    

Note   You can redirect the logged output to the event log by setting provider="EventLogProvider" instead of provider="MySqlWebEventProvider" as shown here:

<rules> 
  <add name="Critical event" 
       eventName="My Critical Event" 
       provider="EventLogProvider" 
       profile="Throttle"/>
</rules>
  
  

More Information

The following lists describe the optional attributes available while configuring various event logging providers that you can use to customize provider behavior.

SimpleMailWebEventProvider and TemplatedMailWebEventProvider

Use the SimpleMailWebEventProvider or TemplatedMailWebEventProvider to send an e-mail message when an event is raised. When you are configuring providers using these classes, set the following attributes to control the behavior of these providers.

  • from, to, bcc and cc. These specify the sender and receivers of the event notification mail.
  • maxEventLengthForSimpleMessage. Use this attribute to limit the number of characters of event details being mailed. This setting is potentially dangerous if the message size is not limited. The default value is 5,000 characters.
  • maxSizeForSimpleMessage. Use this attribute to limit the size of the notification message sent. The default value is 1,024 KB.
  • maxEventCountForTemplateMessage. Use this attribute to limit the number of events in each message notification.
  • maxMessagesPerNotification. Use this attribute to limit the number of messages per event.
  • priority. Use this attribute to set the priority of mail messages.

When you are using the SimpleMailWebEventProvider, use the following attributes to format the mail notification:

  • bodyFooter. Use this attribute to specify a message to be included at the bottom of the body of the notification e-mail message.
  • bodyHeader. Use this attribute to specify a message to be included at the top of the body of the e-mail notification.
  • separator. Use this attribute to include specific text between each event and after each section header in simple email format.
  • subjectPrefix. Use this attribute to prefix custom text to the mail subject. This helps you distinguish event-related e-mail messages.

When you use the TemplatedMailWebEventProvider, use the following attribute to format the mail notification:

  • template. Use this attribute to specify an .aspx page that is used to create the message body of the notification. This attribute cannot be specified along with bodyHeader, bodyFooter, or separator settings.

SQLEventProvider

Use the following attributes to restrict the event size:

  • maxEventDetailsLength. Use this attribute to specify the maximum event details size. Set this attribute to a suitable value to limit the maximum length of data that can be written to the database.
  • commandTimeout. Use this attribute to override the default ADO.NET command time out (30 seconds).

Additional Resources

Feedback

Provide feedback by using either a Wiki or e-mail:

We are particularly interested in feedback regarding the following:

  • Technical issues specific to recommendations
  • Usefulness and usability issues

Technical Support

Technical support for the Microsoft products and technologies referenced in this guidance is provided by Microsoft Support Services. For product support information, see the Microsoft Support Web site at https://support.microsoft.com.

Community and Newsgroups

Community support is provided in the forums and newsgroups:

To get the most benefit, find the newsgroup that corresponds to your technology or problem. For example, if you have a problem with ASP.NET security features, you would use the ASP.NET Security forum.

Contributors and Reviewers

  • ExternalContributors and Reviewers: Brian Cowan; Rudolph Araujo, Foundstone Professional Services; Jason Taylor, Security Innovation; Eric Marvets, Dunn Training and Consulting; Anil John, John Hopkins University – Applied Physics Laboratory
  • Microsoft Consulting Services and PSS Contributors and Reviewers: Adam Semel, Tom Christian, Wade Mascia
  • Microsoft Product Group Contributors and Reviewers: Eric Deil
  • Test team: Larry Brader, Microsoft Corporation; Nadupalli Venkata Surya Sateesh, Infosys Technologies Ltd; Sivanthapatham Shanmugasundaram, Infosys Technologies Ltd
  • Edit team: Nelly Delgado, Microsoft Corporation; Tina Burden McGrayne, TinaTech Inc.
  • Release Management: Sanjeev Garg, Microsoft Corporation

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.