Error Logging for ASP.NET MVC, Health Monitoring

June 14, 2011 · Posted in Development 

We have serveral options for error logging in ASP.NET MVC application:

- ASP.NET Health Monitoring

- ELMAH for error logging

- log4net

- NLog


ASP.NET Health Monitoring

 

The health monitoring system was introduced in ASP.NET 2.0 and is designed to monitor the health of a deployed ASP.NET application by logging events that occur during the application or request’s lifetime. The events logged by the health monitoring system are referred to as health monitoring events or Web events, and include:

  • Application lifetime events, such as when an application starts or stops
  • Security events, including failed login attempts and failed URL authorization requests
  • Application errors, including unhandled exceptions, view state parsing exceptions, request validation exceptions, and compilation errors, among other types of errors.

When a health monitoring event is raised it can be logged to any number of specified log sources. The health monitoring system ships with log sources that log Web events to a Microsoft SQL Server database, to the Windows Event Log, or via an e-mail message, among others. You can also create your own log sources.

The events the health monitoring system logs, along with the log sources used, are defined in Web.config. With a few lines of configuration markup you can use health monitoring to log all unhandled exceptions to a database and to notify you of the exception via e-mail.

 

ASP.NET health monitoring enables you to do the following tasks:

  • Monitor the performance of an application to make sure that it is healthy.
  • Rapidly diagnose applications or systems that are failing.
  • Appraise significant events during the life cycle of an application.
  • Monitor live ASP.NET applications, individually or across a Web farm.
  • Log events that do not necessarily relate to errors in an ASP.NET application.

What is Health Monitoring?

Health Monitoring is a framework for monitoring status of running ASP.NET applications and logging significant ASP.NET application events.

Why would I use Health Monitoring?

  • Health Monitoring is runtime based for your production environment, so it provides information of your running ASP.NET applications.
  • Health Monitoring gives event details rather than providing a number or a total, which can be useful to solve running application issues.
  • Health Monitoring is customizable, so you can tailor the event information they way you need it.

What are examples of Health Monitoring events that can be logged?

  • Application starts and stops
  • Failed logins and unhandled exceptions
  • “Heartbeats”
  • Successful and failed login attempts through Membership
  • Successful and failed URL and ACL authorizations by authenticated users
  • Valid and expired forms authentication tickets
  • View state validation failures
  • Compilation errors
  • Configuration errors
  • Unhandled exceptions
  • Request validation failures
  • Anything that causes request to abort
  • Requests queued, processing, or rejected
  • Specific or periodic monitoring event
  • Process start time and more

What are examples of locations where Health Monitoring events can be logged?

  • Windows event log
  • SQL Server database
  • Email
  • Console window using WMI
  • Trace output window

What are Health Monitoring events?

Health Monitoring events help you keep track of different things that are occurring while your ASP.NET application is running. These events are divided into five main areas:

  • Application Lifetime Events
  • All Audits
  • All Errors
  • Reqeust Processing Events
  • Heartbeats

Web Events

There are several events that you can trap using the health monitoring system. These events are called Web Events. Each web event is defined by a class. Some of the important events are given below:

  • WebBaseEvent : Acts as a base class for all the other web events.
  • WebBaseErrorEvent : Acts as a base class for all web events related to errors in the system.
  • WebHeartbeatevent : Records web events after a predefined interval instead of each and every occurrence.
  • WebRequestEvent : Represents web events occurring during a request.
  • WebErrorEvent : Represents configuration or compilation errors.
  • WebApplicationLifetimeEvent : Deals with application level events including application starts and stops.
  • WebRequestErrorEvent : Deal with unhandled exceptions and any request related errors.
  • WebAuditEvent: Represents a base class for web events related to login attempts.
  • WebFailureAuditEvent : Deals with login failures.

 

Configuring health monitoring features

In order to use the health monitoring system you need to do some configuration job as outlined below:

  1. Enable health monitoring
  2. Map events with developer defined friendly names (optional)
  3. Specify buffering behavior for the providers (optional)
  4. Configure one or more providers
  5. Specify which system events are to be monitored and by which providers

 

Logging Events to a Database

The SqlWebEventProvider class is part of the health monitoring system and logs a health monitoring event to a specified SQL Server database.

The database must have a predefined schema with a table named aspnet_WebEvent_Events and a stored-procedure called apsnet_WebEvent_LogEvent.

You can add these objects to your database using the aspnet_regsql.exe tool. The aspnet_regsql.exe is located at the %WINDOWS%\Microsoft.NET\Framework\version directory.

We can run the command as the following:

aspnet_regsql.exe -E -S .\SqlExpress -d mydbname -A w

 

Once you have the necessary stored procedure and table added to your database, all that remains is to instruct health monitoring to log all unhandled exceptions to the database. Accomplish this by adding the following markup to your website’s Web.config file:

<configuration>
...
<connectionStrings>
<add name="ApplicationServices"
connectionString="..your_connection_string.."
providerName="System.Data.SqlClient"
/>
</connectionStrings>
..
<system.web>
...
<healthMonitoring enabled="true">
<eventMappings>
<clear />
<add name="All Errors" type="System.Web.Management.WebBaseErrorEvent"
startEventCode="0" endEventCode="2147483647" />
</eventMappings>
<providers>
<clear />
<add connectionStringName="ApplicationServices" 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" />
</rules>
</healthMonitoring>
</system.web>
</configuration>

The WebBaseErrorEvent event is only raised for server errors; it is not raised for HTTP errors, such as a request for an ASP.NET resource that is not found. This differs from the behavior of theHttpApplication class’s Error event, which is raised for both server and HTTP errors.

Some examples of ASP.NET Health Monitoring configurations

 

* Logging errors to a Database

<configuration>
..
<connectionStrings>
<add name="ApplicationServices"
connectionString="..your_connection_string"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
..
<system.web>
<healthMonitoring enabled="true">
<providers>
<add name="sqlProvider"
type="System.Web.Management.SqlWebEventProvider"
connectionStringName="ApplicationServices"
buffer="false" bufferMode="Notification" />
</providers>
<eventMappings>
<clear />
<add name="All Errors" type="System.Web.Management.WebBaseErrorEvent,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
startEventCode="0" endEventCode="2147483647" />
</eventMappings>
<rules>
<clear />
<add name="All Errors Default" eventName="All Errors" provider="sqlProvider"
profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
</rules>
</healthMonitoring>
...
</system.web>
</configuration>

 

 

* Logging Events to E-Mail

 

<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="Data Source=localhost;Database=mydbname;User ID=sa;Password=mypwd;Pooling=true;Connect Timeout=450; Max Pool Size=1000; Min Pool Size=0;"
providerName="System.Data.SqlClient" />
</connectionStrings>
...
<system.web>
<healthMonitoring enabled="true">
<providers>
  <clear />
<add type="System.Web.Management.SimpleMailWebEventProvider"
name="EmailWebEventProvider" buffer="false"
from="support@example.com" to="support@example.com"
subjectPrefix="Runtime Error: " />
<add connectionStringName="ApplicationServices" maxEventDetailsLength="1073741823"
buffer="false" name="SqlWebEventProvider"
type="System.Web.Management.SqlWebEventProvider" />
</providers>
<rules>
<clear />
<add name="All Errors To E-Mail" eventName="All Errors" provider="EmailWebEventProvider"
profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
<add name="All Errors To Database" eventName="All Errors" provider="SqlWebEventProvider"
profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
</rules>
</healthMonitoring>
...
</system.web>
</configuration>

 

 

Read more about ASP.NET Health Monitoring:

* http://www.asp.net/hosting/tutorials/logging-error-details-with-asp-net-health-monitoring-cs

* MSDN: ASP.NET Health Monitoring Overview (.NET Framework 4)

* http://dotnetslackers.com/articles/aspnet/ConfiguringAndCustomizingTheHealthMonitoringSystemOfASPNET.aspx

* Logging ASP.NET Application Shutdown Events

* FAQ – Health Monitoring in ASP.NET 2.0 – http://forums.asp.net/t/1027461.aspx

ELMAH

Many people are using ELMAH for error logging. ELMAH is easier to use and configure compared to the built-in health monitoring features. ELMAH also includes a number of display options, including the ability to generate RSS feeds from logged events.

Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilites without changing a single line of your code:

  • Logging of nearly all unhandled exceptions.
  • A web page to remotely view the entire log of recoded exceptions.
  • A web page to remotely view the full details of any one logged exception.
  • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrorsmode turned off.
  • An e-mail notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log.
  • A number of backing storage implementations for the log, including in-memory, Microsoft SQL Server and several contributed by the community.

For more information read this article – using ELMAH in an MVC application.

If you are already using ELMAH, you still might consider looking at health monitoring for some scenarios. ELMAH is a fantastic error reporting tool, but some of the information available from health monitoring is only available via health monitoring, since it has a close tie to the ASP.NET runtime.

If you want to take the health monitoring events and publish them via ELMAH, than Eric Schoenholzer (@bluesware) has written an ElmahEventProvider you can download from the Files section of the ELMAH project site.

Log4Net

Steps to add Log4Net:
1. Download Log4Net
2. Add a reference to Log4Net
3. Add a table in our database to store the Log4Net logs
4. Modify the web.config file for Log4Net
5. Implement a Log4NetLogger that implements our ILogger interface.

Comments

  • http://ywwy.be/ Olivier G.

    Clear and complete overview. Perfect for preparing my MCSD486. thx