Published: 14 May 2007
By: Brian Mains

Health monitoring is a new feature of the .NET 2.0 framework that allows you to monitor what is going on in your system. Events raised within an ASP.NET application are logged to a provider, such as the event log, ASP.NET database, tracing, email, or any custom provider you create. Health monitoring provides an excellent way to capture what is happening in your system.

Introduction

Health monitoring is a new way to evaluate errors in or collect general information about your applications. It uses event classes that raise events to a provider, which logs the event in a data store of the provider’s choosing. The beauty of health monitoring is that it is completely configurable through the configuration file, meaning it logs the events you want to log. By default, the .NET framework has providers to log events to the ASP.NET standard database, the event log, the tracing mechanism, an email message, and any other source you desire through creating custom event providers. All of this we shall see in an upcoming example.

Health Monitoring Terms

The health monitoring terms that are used are summarized below:

  • Events - Events are the objects that are raised in the application using the Raise() method. When the event is raised, it is raised to the provider and logged based on whether the event code is within the range specified in the configuration file.
  • Event Providers - These are the event providers within the system that will capture events. Events can be captured to many existing sources, or you have the ability to create your own. The two main event provider classes are WebEventProvider and BufferedWebEventProvider.
  • Buffer Modes - These are buffering settings for writing events to the system. Providers that inherit from the BufferedWebEventProvider class can make use of buffering, and buffer modes specifies the buffer settings for that provider.
  • Event Mappings - These are the events that will be logged. By default, there are many events capable of being logged. Custom events can be created with more detailed information about your application, as we shall see.
  • Rules - Rules map the provider to the event, and specify the range of event codes that are logged, and the profile to use for capturing events. Every event registered shouldn’t be used, so rules determine which events map to which providers.
  • Profiles - A set of parameters that can be predefine settings for events. Profiles setup properties for throttling events. Throttling is similar to buffering, meaning it doesn’t send events to the provider the instant they occur. However, throttling can lose events as we will see.

Configuration Setup

The healthMonitoring element has five sub-elements (bufferModes, profiles, providers, eventMappings, and rules) that define the events and providers the framework uses. If you take a look at your machine's web.config file (not machine.config) in Windows\Microsoft.NET\Framework\\Config folder, you will see the default setup for health monitoring. By default, health monitoring comes with several providers and events already registered; however, only the event log is setup to capture errors and auditing failures. Some of the events already defined are events for Request Processing, Auditing, and general error information. In addition, there are some default buffer mode/profile settings already available as well. Lastly, there is a heartbeat event that is raised in accordance to the setting of the heartbeatInterval property.

So what does the configuration file setup look like? First, the healthMonitoring element must be defined. The element has two primary attributes: enabled and heartbeatInterval. Enabled is obvious, and heartbeatInterval specifies the interval that the heartbeat will run in seconds. The following example will raise a heartbeat event every 10 minutes (60 sec. * 10).

Next, I created a profile and buffer mode as an example. I normally use the default settings if I use any, but in this case I wanted to show how these two are setup:

Next, below are event mappings defintions, mapping the appropriate event class to a friendly event mapping name. This name will be used to map the events to the appropriate provider in the rules section. As you see, events defined below define an event code. These event codes will be sent to the provider, meaning that only Web Error Events with a code of 100100 or 100101 will be provided; everything else is ignored.

Providers map a friendly name to the provider that will receive calls. The friendly name will be used to reference the provider later on. If the event provider is a buffered event provider, add the buffer and bufferMode attributes to the declaration. The bufferMode attribute must be a valid name in the bufferModes section. Notice some providers have additional properties, like xmlDataFile for the XmlProvider provider. These values are collected through the Initialize method of the provider, like any other provider. See more information about creating custom providers for more information.

Lastly, rules map event mappings to providers, so that only certain events are raised to the providers; all others are ignored. By default, the event log receives errors and audit failures. Since this article features custom events (shown later), we will register those in the section below. This web site now has additional error/event detection for custom events raised in the application, as well as logging for pre-defined events.

Using Health Monitoring in ASP.NET

The configuration above is what is needed to use health monitoring. These events will register the source to the XML file, event log, and tracing mechanism wherever those providers are specified. Let’s take a look at what was rendered to the XML provider for the heartbeat event:

I created a test page that raises custom events in my Nucleo framework, which I was capturing. The following events were captured in the XML:

It did log the errors; however, I raised multiple events at one time, but only one was logged at a time. I assume this was an issue with the profile, and to test I changed the profile of Critical (which does not throttle events), and the following results occurred whenever I clicked through the events.

It definitely appears that the profile setting highly affects the amount of event log entries being logged, so be aware of that.

Creating Custom Events

You’ve seen a couple of event objects that aren’t defined in the framework, which you may be interested in. It’s not hard at all to create your own custom events. Below is a base class that I defined for all of my custom events. Custom web events inherit from WebBaseEvent, which you can do so yourself. However, there is good reason to create your own custom base event class. Let's take a look at the definition below first:

Because all of our custom events inherit from this custom base class, it makes it easier to register your events in the configuration file. To include events for monitoring, the configuration file references them by object type. Because all of the events inherit from WebMonitoringEventBase class, all events can be referenced through the WebMonitoringEventBase type in bulk, instead of registering each one separately. If you look back to the eventMappings section, you will see that WebMonitoringEventBase has been defined.

Below is a custom event that is used for raising error events in a web application. This is a custom application with the event code of 100100, well over the event codes for user-defined events (custom events start at 100000). Instead of exposing the message directly, a prefabricated message defined as a constant is used instead. More pertinent information is passed in through the constructor, like the page name and the Exception that occurred.

For your information, there is a WebEventCodes object that contains an enumerated list of code values; however, I used a constant so I could provide the value in the constructor, and so the value was static. Instead of providing an event code manually, I wanted to provide it in the class so the user of the event didn’t need to worry about it. WebExtendedBase is a value of 100000, so I start my event numbering from there.

It's simple to create custom events because the parameters are passed through the constructor, so the definition of the event is relatively simple to implement. You don’t need to define any other properties, methods, or events to do anything with them.

Creating Custom Event Providers

In addition to custom events, we can create custom providers by inheriting from the WebEventProvider class in the System.Web.Management namespace. This class defines three methods: Flush(), ProcessEvent(), and Shutdown(). Shutdown is called whenever the web application's application domain is terminated, and therefore any resources can be saved that are not yet flushed. Some providers have the ability to buffer the information, and flush it all at once. This method performs that action. Lastly, ProcessEvent handles the processing of the event, which usually means writing it to the underlying data store.

If you inherit from BufferedWebEventProvider, this class takes care of those three methods for you, but forces you to override the ProcessEventFlush method, which when buffering, flushes all of the events at a single time. That is what this article will focus on, by creating an XmlEventProvider that flushes events to an XML file.

The following code definition is the XmlEventProvider class. This class uses an XmlDocument collection to modify and save the changes to the XML file. The Initialize method gets the path of the XML data file and stores it in a variable.

As you see in ProcessEventFlush, it’s easy to flush a series of events because the flushInfo object contains an events collection. There are several helper methods used to assist with the rendering of the XML and referencing the path; because the file checking code is in the Initialize method, I was having an error when compiling.

About the Code

Some of the code is featured in the Nucleo framework on the CodePlex web site. You can download it and check it out for yourself. The code used above is in the Nucleo.Web project, under the Monitoring and Providers folders. I tried to include the code directly in the example project attached; however, there was a problem and it didn’t work correctly.

However, the project attached with this article comes with a test web site and the Nucleo assemblies a referenced in the bin folder, so you could use a tool like Reflector to check out the source.

Using the web application, select the type to raise and click the button. The event will eventually be added to the XML file when flushed.

Downloads

HealthMonitoringExample

References

The following references may be of use to you to understand health monitoring and more of the specifics:

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Brian Mains

Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare. In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...

This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Lucene.NET vs SQL Server Full-text – Generating a million records and a full-text index
In this article we will take a look at how SQL Server performs with one million records in a table. ...
Identifying currently running SQL queries
This article is taken from the book SQL Server DMVs in Action. The author discusses a routine that i...
What's blocking my running SQL?
This article is taken from the book SQL Server DMVs in Action. The author discusses a routine that i...
Easy Insert, Update and Retrieve Values for Microsoft SQL Database with C#, Visual Studio
This article will provide you with the small amount of code required to insert, update and retrieve ...
SQL Azure to Developers: Part 1
In this part we will focus on overview of SQL Azure along with a first look on SQL Azure Management ...

You might also be interested in the following related blog posts


Keeping Pulse on Your Site With ASP.NET 2.0 Health Monitoring read more
Inconsistencies in Health Monitoring Between WebForms and MVC read more
Slides from the Boston Code Camp 12 read more
Health Monitoring and ASP.NET MVC read more
SQLAuthority News Download Microsoft SQL Server StreamInsight CTP2 read more
Creating Objects with Observable Properties in JavaScript read more
Keeping ELMAH's Error Log Size In Check read more
Dublin Sessions from the BizTalk Users Group in Sweden on Channel 9 read more
Final Six ASP.NET Hosting Tutorials Now Online read more
Introduction to HealthVault Development #12: More than one person read more
Top
 
 
 

Please login to rate or to leave a comment.

Free Agile Project Management Tool from Telerik
TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.