zoukankan      html  css  js  c++  java
  • 第十九章 排查和调试Web程序 之 防止和排查运行时问题

    1. 概述

      常见的几种运行时问题包括 错误数据、慢于预期的响应、未知行为 或者 未处理的异常。

      Visual Studio 提供了 排查、跟踪 和 日志 等工具 来帮助排查系统的问题。有些情况还需要插入诊断代码。

      本章内容包括:排查性能、安全问题和运行时错误, 实现跟踪、日志(包括使用attributes) 和 调试(包括 IntelliTrace),使用代码契约来加强条件验证,启用和配置健康监视。

    2. 主要内容

      2.1 排查性能问题、安全问题和运行时错误

        性能问题会让用户有挫败感

        安全问题可能会导致一切的问题,包括内部和外部的,如果用户的数据受到安全威胁的话。

        运行时错误会影响所有,包括 表现、安全 和 生成不正确的数据。

        2.1.1 使用性能向导(Performance Wizard)

          VS2012提供的性能向导,是一个性能分析工具。

          包含 CPU sampling、Instrumentation、.NET memory allocation (sampling) 和 Resource contention data (concurrency)。

          

          CPU sampling: 是一种轻量级的监测,更多的用于初始检查,提供进一步系统检查的方向。

          Instrumentation:方法调用的计数和时间。是一种更加侵入性的过程,性能工具会添加监测代码到组件中。

          .NET memory allocation (sampling): 监测内存分配。分析每一个对象从被创建到被回收的过程。

          Resource contention data (con-currency):用于多线程程序。提供线程交互信息以及线程与系统交互的信息。

        2.1.2 使用 Visual Studio Profiler

          Visual Studio 提供了一个 Profiler,提供了对系统中调用操作的完成跟踪信息。

          相对于性能监测工具对性能的关注,Visual Studio Profiler 主要监测活动并且记录它们。这种详细的数据,可以用来做更深入的分析。  

          

          这个图标展示了每秒钟Cpu的使用情况。

        2.1.3 使用 性能监测器(Performance Monitor)

          性能监测器是 Windows Server 提供的工具,可用于在生产环境监测程序。

          

      2.2 排查安全问题

        一般来说,安全问题都与 身份验证 和 授权访问 有关。

        身份验证问题,需要考虑验证问题的范围,是 所有用户、特定的一个用户 还是 一组用户。

        授权访问问题,也是类似的思路。根据范围确定问题可能发生的原因。

      2.3 实现 跟踪、日志 以及 调试

        跟踪 是一种 可以在程序运行时进行分析的技术。 .net內建了对跟踪的支持。

     Trace.WriteIf(someValueIsTrue, “Message”).

        日志 是记录信息的过程。NLog 和 log4net 是两种常用的开源日志工具。

        可以使用try-catch手动处理 调试、错误 和 跟踪信息,也可以通过使用 HandleErrorAttribute 来自动处理。

         HandleErrorAttribute 可用于 actions, controllers, 或者 globally。

    [HandleError(ExceptionType=typeof(System.IOException),View="FileError")]

        

    protected override void OnException(ExceptionContext exceptionContext) 
    { 
        if (exceptionContext.IsChildAction) 
        { 
            //we don't want to display the error screen if it is a child action, 
            base.OnException(exceptionContext); 
            return; 
        } 
             
        // log the exception in your configured logger 
        Logger.Log(exceptionContext.Exception); 
     
        //handle when the app is not configured to use the custom error path 
        if (!exceptionContext.HttpContext.IsCustomErrorEnabled) 
        { 
            exceptionContext.ExceptionHandled = true; 
            this.View("ErrorManager").ExecuteResult(this.ControllerContext); 
        } 
    }

      2.4 使用代码契约来加强条件验证

        代码契约在.net4.0中引入,允许开发者在程序中加入限制条件。包括三种类型:

        a. Preconditions 方法执行前,验证输入的条件。

        b. Invariants 方法执行过程中,防止出现非法的状态。

        c. Postconditions 方法完成时,检查要输出的结果。

        使用代码契约需要一种不同的方式去管理异常处理流程。

    internal Article GetArticle(int id) 
    { 
        System.Diagnostics.Contracts.Contract.Requires(id > 0); 
        // some work here 
    }

        Invariant检查用于确保类中不会出现非法的状态。

    [ContractInvariantMethod] 
    protected void ManageInvariant() 
    { 
        System.Diagnostics.Contract.Invariant(this.Id < 0); 
    }

        Postconditions

    internal Article GetArticle(int id) 
    { 
        System.Diagnostics.Contracts.Contract.Requires(id > 0);  
        System.Diagnostics.Contracts.Contract.Ensures( 
                Contract.Results<Article>() != null); 
        // some work here 
    }

        还可以用其他方式处理违反合约的情况,可以通过注册 Contract.ContractFailed 事件,来添加自定义的处理逻辑。

      2.5 启用和配置健康监视

        健康监视(Health monitoring) 是ASP.NET中的子系统,是为了处理各种web事件的日志记录而设计的。比如 应用程序生命周期事件、安全事件 和 程序错误。

        健康监视(Health monitoring) 的好处包括:

        a. ASP.NET平台內建,访问性高于其他第三方组件。

        b. 遵从MS framework的标准,可以通过配置添加到程序中。

        c. 支持多种日志源(Microsoft SQL Server, the Windows Event Log, email)以及多种日志文件格式。

        通知配置,每种日志事件都可以被以不同的方式处理。

    <healthMonitoring> 
        <bufferModes> 
            <add name="Critical Notification" maxBufferSize="100" maxFlushSize="20" 
                urgentFlushThreshold="1" regularFlushInterval="Infinite" 
                urgentFlushInterval="00:01:00" maxBufferThreads="1" /> 
            <add name="Logging" maxBufferSize="1000" maxFlushSize="200" 
                urgentFlushThreshold="800" regularFlushInterval="00:30:00" 
                urgentFlushInterval="00:05:00" maxBufferThreads="1" /> 
        </bufferModes> 
        <providers> 
            <add name="EventLogProvider"  
                type="System.Web.Management.EventLogWebEventProvider, System.Web" />  
        </providers> 
     <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> 
        <rules> 
            <add name="All Errors Default" eventName="All Events"  
                   provider="EventLogProvider" profile="Default" minInstances="1" 
                   maxLimit="Infinite" minInterval="00:01:00" custom="" /> 
            <add name="Failure Audits Default" eventName="App Lifetime Events" 
                   provider="EventLogProvider" profile="Default" minInstances="1" 
                   maxLimit="Infinite" minInterval="00:01:00" custom="" /> 
        </rules> 
        <eventMappings> 
            <add name="All Events" type="System.Web.Management.WebBaseEvent,System.Web" 
                startEventCode="0" endEventCode="2147483647" /> 
            <add name="Heartbeats" startEventCode="0" endEventCode="2147483647" 
                type="System.Web.Management.WebHeartbeatEvent,System.Web" /> 
            <add name="App Lifetime Events" startEventCode="0" endEventCode="2147483647" 
                type="System.Web.Management.WebApplicationLifetimeEvent" /> 
        </eventMappings> 
    </healthMonitoring>

          <bufferModes>节点用来定义事件被阻塞的时间长度。

          <providers> 提供了一组参数,可以设置 最小和最大实例数 等。

          <rules>节点 在 provider 和 event 之间创建关联。

          <eventMappings>节点 显示了程序映射的三种方式 all events, heartbeats, 和 application lifetime events。

    3. 总结

      1) ASP.NET MVC 目的就是让用户去完成一系列的工作任务。程序设计应该使任务简化。程序性能是用户体验的一个核心组成部分,会在多个方面影响用户体验。

      2) 排查性能问题是使得程序更加健壮的核心。Visual Studio 提供的性能向导可以在  CPU, memory, 和 resource/threading 方面收集相关信息。根据这些信息,可以去排查程序可能存在的逻辑问题,比如 方法被调用太多次 等。

      3) Windows系统提供的性能监测工具,也可以在多个方面提供运行程序的相关信息。

      4) System.Diagnostics 下的 Tracing,可以记录信息到一个或多个 TraceListeners。需要的话,还可以创建自定义的TraceListener。

      5) Logging是用来捕捉程序信息的。可以使用第三方组件 NLog 或 log4net,或者使用System.Diagnostics命名空间来捕获和记录信息。

      6) 代码契约 是 用来 强化方法定义 和 发布内部条件验证 的一种方式。这些条件包括 preconditions、invariant 和  postconditions。

      7) Health monitoring是ASP.NET中的一个系统,用来 跟踪程序中的各种事件。通过配置文件来配置。

  • 相关阅读:
    How to Compile Java DBus
    BZOJ 2783 JLOI 2012 树 乘+二分法
    Robotium原则的实施源代码分析
    基本的负载均衡算法
    人大、上财、复旦、上交四校2013年应届金融硕士就业去向
    2014届上财金融硕士就业情况
    三跨),总分420+
    复旦金融专硕和上财金融专硕
    一个三跨考生三战上海财经大学金融硕士的考研经验
    董某某
  • 原文地址:https://www.cnblogs.com/stone_lv/p/5436112.html
Copyright © 2011-2022 走看看