Robin's Blog

记录 积累 学习 成长

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

asp.net Health Monitor参考

健康监视的定义:
健康监视(Health Monitoring)是监视ASP.NET应用程序运行并记录指定ASP.NET应用程序事件的框架。


健康监视的必要性:

健康监视为产品环境运行时执行服务,所以它可以提供处于运行状态的ASP.NET应用程序信息。健康监视提供事件的发生时间以及事件的详细相关信息,而不仅仅提供统计数字,这些信息可以帮助我们解决应用程序发生的问题。健康监视服务可行自定义,所有事件信息均可进行裁剪。

 

健康监视事件记录示例:

l 应用程序的启动/停止

l 用户登录失败

l “心跳”

l 成功/失败的Membership登录尝试

l 成功/失败的已登录用户访问URL以及访问控制列表审核

l 无效和过期表单认证凭据

l 视图状态验证失败

l 编译错误

l 配置错误

l 未处理异常

l 请求验证失败

l 任何导致请求终止的行为

l 排队、处理中或者被拒绝的请求

l 监视事件的指定/删除

l 处理启动时间

 

健康监视事件记录存储位置:

l Windows事件日志

l SQL Server数据库

l 电子邮件

l WMI控制台窗口

l Trace输出窗口

 

健康监视事件定义:

健康监视事件帮助你对处于运行状态中的ASP.NET应用程序触发的不同事件机型追踪。这些事件主要被分为五个领域:

l 应用程序生命周期事件

l 所有审核事件

l 所有错误事件

l 请求的处理事件

l “心跳”事件

下为自定义健康监视类型以及说明:

事件类型

WebBaseEvent

通用基础事件类由其它类继承。

WebManagementEvent

所有应用程序事件的基类,包括请求错误,生命周期事件(应用程序开始和结束)和审核事件

WebHeartbeatEvent

一般由ASP.NET引擎触发的事件,包含当时应用程序健康信息:活动线程数、队列和执行中请求,以及内存使用。

WebRequestEvent

Web请求相关所有事件的基类

WebAuditEvent

审核事件

WebBaseErrorEvent

错误事件基类

WebErrorEvent

基础结构错误事件,编译、转换、配置错误

 

健康监视提供程序(Providers)的定义:

下表为健康监视提供程序及其说明

提供者程序

EventLogWebEventProvider

记录事件到Windows事件日志

SqlWebEventProvider

记录事件到SQL Server

TraceWebEventProvider

发送事件到当前追踪侦听器集合

WmiWebEventProvider

将事件推送到WMI子系统

SimpleMailWebEventProvider

通过邮件发送Web事件信息

TemplateMailWebEventProvider

使用邮件模板填写Web事件信息

 

健康监视档案(Profiles)的定义:

健康监视档案决定了ASP.NET如何收集事件并且将事件发送给提供程序;默认情况下配置文件中包含Critical和Default两个档案。

 

健康监视缓冲(Buffer)的定义:

缓冲模式(bufferModes)定义了健康监视事件如何在触发之前进行缓冲。以下三种提供者程序可以使用缓冲模式:

l SqlWebEventProvider

l SimpleMailWebEventProvider

l TemplatedMailWebEventProvider

以上提供程序每个都继承自BufferedWebEventProvider类。

 

健康监视规则(Rules)的定义:

规则定义了时间如何触发的过程。至少要在每个规则中包含事件名称、提供者和档案。

 

健康监视配置和控制:

配置是主要位置用来如何控制事件监视和这些事件如何被监视。你可以同时使用文本编辑器或使用API更改配置。更多信息参考MSDN的HealthMonitoringSection类和ASP.NET配置文件

 

健康监视的配置位置:

<healthMonitoring>节放置在<system.web>节中。

<healthMonitoring>配置节子节点:

<healthMonitoring>节中包含五个子节。HealthMonitoring节如下:

<healthMonitoring ...>

 <bufferModes>

    ...

 </bufferModes>

 <providers>

    ...

 </providers>

  <eventMappings>

    ...

 </eventMappings>

 <profiles>

    ...

 </profiles>

 <rules>

    ...

 </rules>

</healthMonitoring>

 

<healthMonitoring>节点是默认配置属性:

<healthMonitoring>节点的默认属性被包含在根web.config文件中。此根web.config文件位于%windir%"Microsoft.NET"Framework"v2.0.50727"CONFIG。默认情况下指定的事件映射(eventMappings)、提供者程序(providers)、规则(rules)和缓冲模式(bufferModes)都已经包含在<healthMonitoring>节点中。

 

健康监视默认事件:

默认事件记录在根web.config文件中:

<eventMappings>

 <add name="All Events" type="System.Web.Management.WebBaseEvent, ..." />

 <add name="HeartBeats"

    type="System.Web.Management.WebHeartBeatEvent, ..." />

 <add name="Application Lifetime Events"

    type="System.Web.Management.WebApplicationLifetimeEvent, ..." />

 <add name="Request Processing Events"

    type="System.Web.Management.WebRequestEvent, ..." />

 <add name="All Errors"

    type="System.Web.Management.WebBaseErrorEvent, ..." />

 <add name="Infrastructure Errors"

    type="System.Web.Management.WebErrorEvent, ..." />

 <add name="Request Processing Errors"

    type="System.Web.Management.WebRequestErrorEvent, ..." />

 <add name="All Audits" type="System.Web.Management.WebAuditEvent, ..." />

 <add name="Failure Audits"

    type="System.Web.Management.WebFailureAuditEvent, ..." />

 <add name="Success Audits"

    type="System.Web.Management.WebSuccessAuditEvent, ..." />

</eventMappings>

 

健康监视默认提供者程序:

默认提供者程序包含在根web.config中:

<providers>

    <add name="EventLogProvider"

            type="System.Web.Management.EventLogWebEventProvider, …

    <add name="SqlWebEventProvider"

            connectionStringName="LocalSqlServer"

            maxEventDetailsLength="1073741823"

            buffer="false"

            bufferMode="Notification"

            type="System.Web.Management.SqlWebEventProvider, …

    <add name="WmiWebEventProvider"

              type="System.Web.Management.WmiWebEventProvider,…

</providers>

 

健康监视默认档案:

默认档案包含于如下的根web.config文件中:

<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>

 

健康监视默认缓冲模式:

如下的默认缓冲模式设置被包含在根web.config配置中:

<bufferModes>

    <add name="Critical Notification"

         maxBufferSize="100"

         maxFlushSize="20"

         urgentFlushThreshold="1"

         regularFlushInterval="Infinite"

         urgentFlushInterval="00:01:00"

         maxBufferThreads="1" />

    <add name="Notification"

         …

    </>

    <add name="Analysis"

         …

    </>

    <add name="Logging“

         …

    </>

</bufferModes>

 

健康监视默认规则:

默认规则设置包含在根web.config配置文件中:

<rules>

 <add name="Failure Audits Default"

       eventName="Failure Audits"

       provider="EventLogProvider"

       profile="Default"       

       minInterval="00:00:00"

       minInstances="1"

       maxLimit="Infinite"

 />

    ...

</rules>

 

实现健康监视的简单步骤:

l 创建新的Web应用程序

l 从“站点”菜单中选择“添加新的项目”

l 选择并添加一个“Web配置文件”

l 添加如下节点到<system.web>节点的闭标签之前:

<healthMonitoring enabled="true" heartbeatInterval="10">

    <rules>

        <add name="Heartbeats Default"

             eventName="Heartbeats"

             provider="EventLogProvider"

             profile="Critical"/>

              </rules>

</healthMonitoring>

l 运行你的应用程序

l 运行事件查看器(eventvwr.exe)

l 在事件查看器中选择“应用程序”

l 注意你应用程序每10秒发生一次的“心跳”事件

 

使用SqlWebEventProvider记录监视事件示例:

参考ASP.NET站点演示的SqlWebEventProvider示例程序。

 

修改<healthMonitoring>配置注意事项:

l 使用Add, Remove和Clear元素

l 不要修改根级别配置文件

l 使用文本编辑器或者API修改

 

通过事件友好名称(如“All Audits”)定位事件类型:

参考MSDN的WebEventCodes,此列表提供了事件的列表。

 

使用事件编号匹配事件:

Web事件代码

事件编号

InvalidEventCode

-1

UndefinedEventCode

0

UndefinedEventDetailCode

0

ApplicationCodeBase

1000

ApplicationStart

1001

ApplicationShutdown

1002

ApplicationCompilationStart

1003

ApplicationCompilationEnd

1004

ApplicationHeartbeat

1005

RequestCodeBase

2000

RequestTransactionComplete

2001

RequestTransactionAbort

2002

ErrorCodeBase

3000

RuntimeErrorRequestAbort

3001

RuntimeErrorViewStateFailure

3002

RuntimeErrorValidationFailure

3003

RuntimeErrorPostTooLarge

3004

RuntimeErrorUnhandledException

3005

WebErrorParserError

3006

WebErrorCompilationError

3007

WebErrorConfigurationError

3008

WebErrorOtherError

3009

WebErrorPropertyDeserializationError

3010

WebErrorObjectStateFormatterDeserializationError

3011

AuditCodeBase

4000

AuditFormsAuthenticationSuccess

4001

AuditMembershipAuthenticationSuccess

4002

AuditUrlAuthorizationSuccess

4003

AuditFileAuthorizationSuccess

4004

AuditFormsAuthenticationFailure

4005

AuditMembershipAuthenticationFailure

4006

AuditUrlAuthorizationFailure

4007

AuditFileAuthorizationFailure

4008

AuditInvalidViewStateFailure

4009

AuditUnhandledSecurityException

4010

AuditUnhandledAccessException

4011

MiscCodeBase

6000

WebEventProviderInformation

6001

ApplicationDetailCodeBase

50000

ApplicationShutdownUnknown

50001

ApplicationShutdownHostingEnvironment

50002

ApplicationShutdownChangeInGlobalAsax

50003

ApplicationShutdownConfigurationChange

50004

ApplicationShutdownUnloadAppDomainCalled

50005

ApplicationShutdownChangeInSecurityPolicyFile

50006

ApplicationShutdownBinDirChangeOrDirectoryRename

50007

ApplicationShutdownBrowsersDirChangeOrDirectoryRename

50008

ApplicationShutdownCodeDirChangeOrDirectoryRename

50009

ApplicationShutdownResourcesDirChangeOrDirectoryRename

50010

ApplicationShutdownIdleTimeout

50011

ApplicationShutdownPhysicalApplicationPathChanged

50012

ApplicationShutdownHttpRuntimeClose

50013

ApplicationShutdownInitializationError

50014

ApplicationShutdownMaxRecompilationsReached

50015

StateServerConnectionError

50016

AuditDetailCodeBase

50200

InvalidTicketFailure

50201

ExpiredTicketFailure

50202

InvalidViewStateMac

50203

InvalidViewState

50204

WebEventDetailCodeBase

50300

SqlProviderEventsDropped

50301

WebExtendedBase

100000

 

健康监视事件详细信息:

WebBaseEvent类提供了记录每个事件的详细信息:

public class WebBaseEvent : System.Object

{

    public static WebApplicationInformation

              ApplicationInformation { get; }

    public int EventCode { get; }

    public int EventDetailCode { get; }

    public Guid EventId { get; }

       public long EventOccurrence { get; }

    public long EventSequence { get; }

    public object EventSource { get; }

    public DateTime EventTime { get; }

    public DateTime EventTimeUtc { get; }

    public string Message { get; }

    public virtual void FormatCustomEventDetails (...);

    public virtual void Raise (...);

}

更多信息参考 WebBaseEvent Members。

 

激活/注销健康监视事件控制台应用程序:

创建一个Web应用程序,名字为”aspnetexample”。使用C#和HTTP(localhost)

现在创建一个新的C#控制台应用程序。添加如下代码到控制台应用程序。

// Add references:

// System.Configuration

// System.Web

 

#region Using directives

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Configuration;

using System.Web;

using System.Web.Configuration;

 

#endregion

 

namespace HealthMonExample

{

    class UsingHealthMonitoringSection

    {

        static void Main(string[] args)

        {

            try

            {

                // Set the path of the config file.

                string configPath = "/aspnetexample";

 

                // Get the Web application configuration object.

                Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

 

                // Get the section related object.

                HealthMonitoringSection configSection =

                  (HealthMonitoringSection)config.GetSection("system.web/healthMonitoring");

 

                // Display title and info.

                Console.WriteLine("ASP.NET Configuration Info");

                Console.WriteLine();

 

                // Display Config details.

                Console.WriteLine("File Path: {0}",

                  config.FilePath);

                Console.WriteLine("Section Path: {0}",

                  configSection.SectionInformation.Name);

 

                // Display Enabled property.

                Console.WriteLine("Enabled (old value): {0}",

                  configSection.Enabled.ToString());

 

                // Toggle the Enabled property.

                if (!configSection.Enabled)

                {

                    configSection.Enabled = true;

                }

                else

                {

                    configSection.Enabled = false;

                }

 

                // Display Providers Count.

                Console.WriteLine("Providers Count: {0}",

                  configSection.Providers.Count);

 

                // Display EventMappings Count.

                Console.WriteLine("EventMappings Count: {0}",

                  configSection.EventMappings.Count);

 

                // Display Profiles Count.

                Console.WriteLine("Profiles Count: {0}",

                  configSection.Profiles.Count);

 

                // Display Rules Count.

                Console.WriteLine("Rules Count: {0}",

                  configSection.Rules.Count);

 

                // Update if not locked.

                if (!configSection.SectionInformation.IsLocked)

                {

                   config.Save();

                    Console.WriteLine("** Configuration updated.");

                }

                else

                {

                    Console.WriteLine("** Could not update, section is locked.");

                }

            }

 

            catch (Exception e)

            {

                // Unknown error.

                Console.WriteLine(e.ToString());

            }

 

            // Display and wait

            Console.ReadLine();

        }

    }

}

确认已经添加如下引用到你的控制台应用程序:

l System.Configuration

l System.web

运行控制台应用程序,你会注意到每次打开控制台应用程序,你的Web应用程序健康监视状况就会打开或关闭。

 

健康状况监视子系统扩展:

可以通过创建自己的提供者程序、事件和其它对象帮助你自定义你的ASP.NET应用程序监视。更多信息参考Web Event Providers 和 WebBaseEvent Class。

 

参考资料:

ASP.NET Health Monitoring 

How to: Install and Configure SMTP Virtual Servers in IIS  

How to: Send E-mail for Health Monitoring Notifications

Web Event Providers (自定义提供者程序示例)

ASP.NET SQL Server Registration Tool

WebEventCodes Class

Walkthrough: Listening for WMI Events in ASP.NET Health Monitoring  

System.Web.Management Namespace

 

posted on 2009-08-01 19:01  Robin99  阅读(583)  评论(0)    收藏  举报