When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs

ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
 
Print this Page!
Published: Wednesday, March 14, 2007

Health Monitoring in ASP.NET 2.0: The Basics

By Scott Mitchell


A Multipart Series on ASP.NET 2.0's Health Monitoring System
The Health Monitoring system in ASP.NET 2.0 is designed to monitor the health of a running ASP.NET application in a production environment. This article is one of an ongoing series on the Health Monitoring system.

  • Health Monitoring Basics - explores the concepts and advantages of the Health Monitoring system and looks at logging events to a Microsoft SQL Server database.
  • Notifications via Email - looks at security-related events and shows how to alert an administrator to failed authentication attempts by "logging" events to email.
  • Raising Custom Events - learn how to create and raise custom Health Monitoring events.
  • (Subscribe to this Article Series! )

    Introduction


    Software engineering involves a number of important stages that occur before the application is deployed, such as requirements analysis, design, coding, and testing. The software engineering process, however, does not end once an application has been deployed and is being used. Regardless of how well designed, coded, and tested a web application may have been, there will invariably be hiccups. The database server may go offline, the website might be experiencing an unexpected heavy load, or there may be a hardware failure on the web server itself. And, unless the application is trivial or you are a programming god, there are bound to be bugs that will weild their nasty little heads every now and then.

    To help detect and diagnose problems, it is important that key web application metrics and information are monitored and logged. There are a number of open-source and Microsoft-created libraries to help with with logging unhandled exceptions and notifying developers. See Gracefully Responding to Unhandled Exceptions - Processing Unhandled Exceptions for information on how to log unhandled exceptions.

    ASP.NET version 1.x did not include any built-in logging and notification system and therefore required a little bit of code or configuration effort from the developer. ASP.NET 2.0, however, provides built-in Health Monitoring facilities that make it a snap to configure a website to record events to the event log, a database, via WMI, in an email, or to the ASP.NET page tracing system. Moreover, the Health Monitoring system was created using the provider design pattern, making it possible to implement our own logging logic.

    This is the start of a series that explores the ASP.NET 2.0 Health Monitoring system. In this article we will examine the basics of Health Monitoring and see how to setup Health Monitoring to log events to a SQL Server database. Read on to learn more!

    - continued -

    An Overview of Health Monitoring


    The ASP.NET 2.0 Health Monitoring system is designed to monitor the health of a running ASP.NET application in a production environment. The Health Monitoring system works by recording event information to a specified log source. For example, it can log events like application starts and stops, successful and failed logins, and unhandled exceptions to log sources like the Windows event log or a SQL Server database. Setting up the Health Monitoring system is as easy as adding some configuration information to Web.config specifying the events to monitor and the log source to send them to.

    While the .NET 2.0 Framework provides a number of built-in Health Monitoring events and log sources, there will invariably be times when you need to add custom events or use an alternate log source. New events can be created as classes that extend the WebBaseEvent class, and custom log sources can be created as classes that extend the WebEventProvider class. The Health Monitoring system was designed with the provider design pattern, allowing custom events and log sources to be plugged into an application with just a few changes to the configuration information.

    Future articles in this series will examine creating custom events and log sources. In this article, we will constrain the examples to using built-in events and log sources.

    Configuring Health Monitoring


    Health Monitoring is configured through a <healthMonitoring> element in Web.config that specifies the event mappings, the event subscription rules, and log sources. Each of these items is defined as a child element of the <healthMonitoring> element. Let's look at each of these children elements individually:
    • Event Mappings (<eventMappings>) - associates a human-friendly name with a set of events. The name used here is referenced in other sections.
    • Log Sources (<providers>) - associates a human-friendly name with those types that can function as log sources.
    • Event Subscription Rules (<rules>) - ties an event set defined in the <eventMappings> section with a log source defined in the <providers> section.
    The following example illustrates how these three sections are tied together. Here we have defined a single event mapping named "All Errors" that is denoted by any event class that derives from the WebBaseErrorEvent class. A single log source named "EventLogProvider" is defined, which maps to the EventLogWebEventProvider class, which, as its name implies, logs event information to the Windows event log. Finally, the event subscription rule named "All Errors Default" associates the "All Errors" event set with the "EventLogProvider" log source. With the following configuration defined in Web.config, all unhandled exceptions or error events explicitly raised will result in a record being written to the Windows event log:

    <configuration>
        <system.web>
          <healthMonitoring enabled="true">
           <eventMappings>
              <clear />
              <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent"
                       startEventCode="0" endEventCode="2147483647" />
           </eventMappings>

           <providers>
              <clear />
              <add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider" />
           </providers>

           <rules>
              <clear />
              <add name="All Errors Default" eventName="All Errors" provider="EventLogProvider"
                       profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
           </rules>
          </healthMonitoring>

        </system.web>
    </configuration>

    With the following configuration in place, when an unhandled exception is encountered, the Health Monitoring system automatically records the error's details to the Windows event log. Note the minInterval setting in the <rules> section. This value specifies a window that must elapse before a particular event will be logged again. I've set the minInterval value above to "00:00:00", which means even if the same event happens, say, five times over the course of ten seconds, five events will be logged. Alternatively, you might care to have this event logged at most once every 30 seconds. If you set the minInterval value to "00:00:30", the first time the event fired it would be logged. If the same event fired 10 seconds later, that instance would not be logged since the 30 second window has not yet elapsed. For critical events, be sure to use an appropriate minInterval value ("00:00:00", perhaps). For non-critical events, a higher minInterval may be appropriate.

    The download at the end of this article includes a web application that includes a page with a Button control that, when clicked, raises an ApplicationException. When visiting this page and clicking that Button, the "Yellow Screen of Death" appears, indicating that an unhandled exception has occurred. Behind the scenes, this information was recorded to the Windows event log's Application section.

    The "Yellow Screen of Death" is Displayed in the Face of an Unhandled Exception


    The Yellow Screen of Death


    The Unhandled Exception's Details are Logged to the Windows Event Log
    The exception is logged to the Windows Event Log

    The Default Health Monitoring System Configuration


    By default, ASP.NET 2.0 applications have Health Monitoring enabled and log all error events and failed audits to the Windows Event log. You can view or modify this default functionality for the entire web server through the machine-level Web.config file in the %WINDOWS%\Microsoft.NET\Framework\version\CONFIG folder. In the sample configuration above, I used the <clear /> statement in each section to remove the default settings before specifying my own.

    In addition to including the "EventLogProvider" log source, the default configuration includes two other providers with the following names:

    There are additional log source providers in the .NET Framework, but they are not included in the <providers> section by default. To add these or to customize those providers specified by default, you will need to add a <providers> element in Web.config like we did in the above example.

    There are also a number of pre-defined event sets specified in the <eventMappings> section. See the machine-level Web.config file for a full list. For a full list of the events built into the .NET Framework, check out the System.Web.Management namespace. All of these events are derived from the WebBaseEvent. They are further grouped into categories by their type hierarchy. For example, all request events are derived from the WebRequestEvent class (which is derived from WebBaseEvent).

    The remainder of this article explores how to use the "SqlWebEventProvider" log source to log particular errors to a SQL Server database.

    Logging Events to SQL Server


    In order to have the Health Monitoring system log errors to a SQL Server database, we need to do two things:
    • Configure the web application's Health Monitoring settings to log the events to a SQL Server database, and
    • Add the necessary schema information to the database that will be used as the log source
    If you use the default data store for the "SqlWebEventProvider" log source (the ASPNETDB.MDF database in the App_Data folder), the database will automatically be created the first time the Health Monitoring system records an event. If you want to use an alternate database, you need to use the ASP.NET SQL Server Registration Tool (aspnet_regsql.exe). You can run this from the command line using the following arguments:

    -- For a trusted connection...
    aspnet_regsql.exe -E -S serverName -d database -A w

    -- When using SQL authentication...
    aspnet_regsql.exe -U userID -P password -S serverName -d database -A w

    The aspnet_regsql.exe program is found in the %WINDOWS%\Microsoft.NET\Framework\version directory. You'll also find a file named InstallWebEventSqlProvider.sql in that same folder that contains the T-SQL script used to install the Health Monitoring schema.

    The Health Monitoring schema is very straightforward - it includes a table, aspnet_WebEvent_Events, and a stored procedure, aspnet_WebEvent_LogEvent. That's it! When an event occurs that the Health Monitoring system is monitoring and configured to log to the "SqlWebEventProvider" log source, the aspnet_WebEvent_LogEvent stored procedure will be executed, adding a new record to the aspnet_WebEvent_Events table.

    Once the SQL Server schema has been applied (again, you won't need to do a thing if you opt to use the ASPNETDB.MDF database in App_Data), add the following <healthMonitoring> section to Web.config. This configuration information instructs the Health Monitoring system to log all error events and all application events using the "SqlWebEventProvider" log source. The configuration settings re-register the "SqlWebEventProvider" provider in the <providers> section. I am using the default connection string name here ("LocalSqlServer"), but you can change this to be the name of a connection string registered in Web.config's <connectionStrings> section if you want to use a logging database other than ASPNETDB.MDF.

    <configuration>
        <system.web>
          <healthMonitoring enabled="true">
           <eventMappings>
              <clear />
             
              <!-- Log ALL error events -->
              <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent"
                   startEventCode="0" endEventCode="2147483647" />
             
              <!-- Log application startup/shutdown events -->
              <add name="Application Events" type="System.Web.Management.WebApplicationLifetimeEvent"
                   startEventCode="0" endEventCode="2147483647"/>
           </eventMappings>

           <providers>
              <clear />
             
              <!-- Provide any customized SqlWebEventProvider information here (such as a different connection string name value -->
              <add connectionStringName="LocalSqlServer" maxEventDetailsLength="1073741823"
                       buffer="false" name="SqlWebEventProvider"
                       type="System.Web.Management.SqlWebEventProvider" />
           </providers>

           <rules>
              <clear />

              <add name="All Errors Default" eventName="All Errors" provider="SqlWebEventProvider"
                       profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
             
              <add name="Application Events Default" eventName="Application Events"
                 provider="SqlWebEventProvider" profile="Default" minInstances="1"
                 maxLimit="Infinite" minInterval="00:00:00" />
           </rules>
          </healthMonitoring>
        </system.web>
    </configuration>

    With this configuration information in place, whenever the application starts or stops or whenever there is an error event, the event information will be logged to the ASPNETDB.MDF database in the App_Data folder. (If this database does not exist, it will be automatically created.)

    The download available at the end of this article includes a simple website application demoing this functionality. It consists of two pages, Default.aspx and Log.aspx. Default.aspx contains a Button control that, when clicked, raises an ApplicationException. Log.aspx uses a GridView, DetailsView, two SqlDataSource controls to display the current events information in the aspnet_WebEvent_Events table.

    The events are displayed in a GridView

    The details for a particular event are shown in a DetailsView

    Note that each event has an associated EventCode value. See Erik Reitan's FAQ - Health Monitoring in ASP.NET 2.0 blog entry, which includes (among other useful information) a table mapping event codes to event types.

    Conclusion


    ASP.NET 2.0's built-in Health Monitoring support makes it easy to automatically log specified events to specified log sources. In this article we examined two of the built-in log sources, "EventLogProvider" and "SqlWebEventProvider", which log event information to the Windows Event log and a SQL Server database table, respectively. The Health Monitoring system can also capture custom events and use other log sources. In future articles we will explore more log sources and even see how to create our own log sources. We will also look at creating our own events, as well as how to programmatically raise an event.

    Until then... Happy Programming!

  • By Scott Mitchell


    Attachments


  • Download the code used in this article
  • Further Readings


  • How To: Use Health Monitoring in ASP.NET 2.0
  • FAQ - Health Monitoring in ASP.NET 2.0
  • The ASP.NET 2.0 Quickstart Tutorials :: Web Events
  • How To: Instrument ASP.NET Applications for Security
  • A Multipart Series on ASP.NET 2.0's Health Monitoring System
    The Health Monitoring system in ASP.NET 2.0 is designed to monitor the health of a running ASP.NET application in a production environment. This article is one of an ongoing series on the Health Monitoring system.

  • Health Monitoring Basics - explores the concepts and advantages of the Health Monitoring system and looks at logging events to a Microsoft SQL Server database.
  • Notifications via Email - looks at security-related events and shows how to alert an administrator to failed authentication attempts by "logging" events to email.
  • Raising Custom Events - learn how to create and raise custom Health Monitoring events.
  • (Subscribe to this Article Series! )



    ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article