1. 概述

  生产环境中的程序,也是不能保证没有问题的。为了能方便的找出问题,.net提供了一些特性来进行程序诊断。

  这些特性包括:logging、tracing 、程序性能分析(profiling) 和 性能计数器(performance counters).

2. 主要内容

  2.1 Tracing 和 Logging

    Tracing 是 一种监控程序执行的操作。可以用于显示程序运行过程中各个细节。

    Logging 主要用于错误报告。可以配置Logging集中收集信息,通过e-mail发送或者直接记录到文件或数据库中。

    .net提供了一些相关的类(System.Diagnostics下):

    ① Debug:只能用于Debug编译模式下,可用于显示基本的日志信息和执行判定。

Debug.WriteLine(“Starting application”);
Debug.Indent();
int i =  + ;
Debug.Assert(i == );
Debug.WriteLineIf(i > , “i is greater than ”);

    ② TraceSource

TraceSource traceSource = new TraceSource(“myTraceSource”,
    SourceLevels.All); traceSource.TraceInformation(“Tracing application..”);
traceSource.TraceEvent(TraceEventType.Critical, , “Critical trace”);
traceSource.TraceData(TraceEventType.Information, , 
    new object[] { “a”, “b”, “c” }); traceSource.Flush();
traceSource.Close(); // Outputs:
// myTraceSource Information: 0 : Tracing application..
// myTraceSource Critical: 0 : Critical trace
// myTraceSource Information: 1 : a, b, c

    上述都是输出信息到输出窗口,生产环境中是看不到的。.net还提供了几种TraceListener,可以实现输出信息到各个介质。

    

Stream outputFile = File.Create(“tracefile.txt”);
TextWriterTraceListener textListener =
    new TextWriterTraceListener(outputFile); TraceSource traceSource = new TraceSource(“myTraceSource”,
    SourceLevels.All); traceSource.Listeners.Clear();
traceSource.Listeners.Add(textListener); traceSource.TraceInformation(“Trace output”); traceSource.Flush();
traceSource.Close();

    还可以使用配置文件来配置跟踪信息

<?xml version=”1.0” encoding=”utf-” ?>
<configuration>
  <system.diagnostics>
    <sources>
      <source name=”myTraceSource” switchName=”defaultSwitch”>
        <listeners>
          <add initializeData=”output.txt” 
type=”System.Diagnostics.TextWriterTraceListeer”            
name=”myLocalListener”>
<filter type=”System.Diagnostics.EventTypeFilter”
initializeData=”Warning”/>
</add>
          <add name=”consoleListener” />
<remove name=”Default”/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData=”output.xml” type=”System.Diagnostics.XmlWriterTraceListener”
         name=”xmlListener” traceOutputOptions=”None” />
      <add type=”System.Diagnostics.ConsoleTraceListener” name=”consoleListener”
          traceOutputOptions=”None” />
    </sharedListeners>
 <switches>
      <add name=”defaultSwitch” value=”All” />
    </switches>
  </system.diagnostics>
</configuration>

    使用EventLog可以写入日志到系统日志中。还可以从系统日志获取日志或者订阅日志变更事件。

class EventLogSample
{
    public static void Main()
    {
        EventLog applicationLog = new EventLog(“Application”, “.”, “testEventLogEvent”);
       applicationLog.EntryWritten += (sender, e) =>
        {
            Console.WriteLine(e.Entry.Message);
        };
        applicationLog.EnableRaisingEvents = true;
        applicationLog.WriteEntry(“Test message”, EventLogEntryType.Information);
        
        Console.ReadKey();
    }
}

  2.2 程序性能分析(Profiling)

    Profiling 是权衡程序对特定资源的占用情况的过程。

    ① 可以使用StopWatch类来监测指定代码的执行时间。

 class Program
 {
     const int numberOfIterations = ;
     static void Main(string[] args)
     {
         Stopwatch sw = new Stopwatch();
         sw.Start();
         Algorithm1();
         sw.Stop();
         Console.WriteLine(sw.Elapsed);
         
         sw.Reset();
         sw.Start();
         Algorithm2();
         sw.Stop();
                Console.WriteLine(sw.Elapsed);
      Console.WriteLine(“Ready…”);
      Console.ReadLine();
}
  private static void Algorithm2()
  {
      string result = “”;
      for (int x = ; x < numberOfIterations; x++)
      {
          result += ‘a’;
      }
  }
  private static void Algorithm1()
  {
      StringBuilder sb = new StringBuilder();
      for (int x = ; x < numberOfIterations; x++)
      {
          sb.Append(‘a’);
      }
      string result = sb.ToString();
  }
}

    ② Visual Studio 2012 包含了一个性能分析工具,可以以四种模式来分析程序性能:

      CPU sampling :最轻量级选项。对程序只有轻微影响,主要用于对程序问题做初级的查找定位工作。

      Instrumentation :该选项会植入一些代码到编译文件中,可以监测各个方法的执行。

      .NET memory allocation :使用该选项,程序给新对象分配内存或者旧对象被垃圾回收时,都会中断程序。用于监测内存的使用情况。

      Resource contention data:该选项用于多线程环境,用于查找指定方法访问指定资源前必须等待其他方法返回的原因。

  2.3 创建和监测性能计数器

    windows提供了性能监测器(Perfmon.exe),用于监测性能计数器。

    通过PerformanceCounter类,可以使用代码读取性能计数器信息。

  class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine(“Press escape key to stop”);
          using (PerformanceCounter pc = 
new PerformanceCounter(“Memory”, “Available Bytes”))
          {
              string text = “Available memory: “;
              Console.Write(text);
              do
              {                 
while (!Console.KeyAvailable)
                {
                    Console.Write(pc.RawValue);
                    Console.SetCursorPosition(text.Length, Console.CursorTop);
                }
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
        }
    }
}

    性能计数器(Performance counters)的几种有用的类型:

    ① NumberOfItems32/NumberOfItems64:用于统计操作或者数据项的数量。

    ② RateOfCountsPerSecond32/RateOfCountsPerSecond64:用于计算操作或数据项每秒的数量。

    ③ AvergateTimer32: 计算完成一个过程或操作一个数据项的平均时间。

    还可以创建和使用自定义的性能计数器(Performance counters)

    class Program
    {
        static void Main(string[] args)
        {
            if (CreatePerformanceCounters())
            {
Console.WriteLine(“Created performance counters”);
Console.WriteLine(“Please restart application”);
                Console.ReadKey();
                return;
            }
            var totalOperationsCounter = new PerformanceCounter(
                “MyCategory”,
                “# operations executed”,
                “”,                
false);
            var operationsPerSecondCounter = new PerformanceCounter(
                “MyCategory”,
                “# operations / sec”,
                “”,
               false);             totalOperationsCounter.Increment();
            operationsPerSecondCounter.Increment();
        }
    private static bool CreatePerformanceCounters()
    {
        if (!PerformanceCounterCategory.Exists(“MyCategory”))
        {
            CounterCreationDataCollection counters = 
new CounterCreationDataCollection
            {
                new CounterCreationData(
                    “# operations executed”,
                    “Total number of operations executed”,
                    PerformanceCounterType.NumberOfItems32),
                new CounterCreationData(
                    “# operations / sec”,
                    “Number of operations executed per second”,
                    PerformanceCounterType.RateOfCountsPerSecond32)
            };
            PerformanceCounterCategory.Create(“MyCategory”,
                    “Sample category for Codeproject”, counters);
            return true;
        }
          return false;
      }
  }

3. 总结

  ① Logging 和 Tracing 是在生产环境监控程序的重要手段,应该从项目的开始阶段就考虑实现。

  ② 可以使用Debug和TraceSource类去记录和跟踪程序信息。还可以通过配置不同的监听器,来实现将跟踪到的信息发送到各个位置。

  ③ 通过程序性能监测工具,可以定位程序中的问题位置,从而更好的解决问题。

第十七章 调试及安全性(In .net4.5) 之 程序诊断的更多相关文章

  1. 第十六章 调试及安全性(In .net4.5) 之 调试程序

    1. 概述 本章内容包括 如何选择合适的构建类型.创建和管理编译指令.管理程序数据文件(pdb)和指令. 2. 主要内容 2.1 构建类型 .net中默认的两种生成模式是 发布(Release)模式 ...

  2. 第十五章 调试及安全性(In .net4.5) 之 管理程序集

    1. 概述 本章将介绍 什么是程序集.如何强命名程序集.如何把程序集放入GAC.程序集版本 以及 WinMD程序集. 2. 主要内容 2.1 什么是程序集 程序集(Assembly)概念的出现,是为了 ...

  3. 第十四章 调试及安全性(In .net4.5) 之 对称及非对称加密

    1. 概述 本章内容包括:对称及非对称加密算法..net中的加密类.使用哈希操作.创建和管理签名认证.代码访问权限 和 加密字符串. 2. 主要内容 2.1 使用对称和非对称加密 ① 对称加密:使用同 ...

  4. 第十三章 调试及安全性(In .net4.5) 之 验证程序输入

    1. 概述 本章介绍验证程序输入的重要性以及各种验证方法:Parse.TryParse.Convert.正则表达式.JavaScriptSerializer.XML Schemas. 2. 主要内容 ...

  5. Linux内核设计第十七章笔记

    第十七章 设备与模块 关于设备驱动和设备管理,四种内核成分 设备类型:在所有unix系统中为了统一普通设备的操作所采用的分类 模块:Linux内核中用于按需加载和卸载目标代码的机制 内核对象:内核数据 ...

  6. 进击的Python【第十七章】:jQuery的基本应用

    进击的Python[第十七章]:jQuery的基本应用

  7. <构建之法>第十三章到十七章有感以及这个项目读后感

    <构建之法>第十三章到十七章有感 第13章:软件测试方法有哪些? 主要讲了软件测试方法:要说有什么问题就是哪种效率最高? 第14章:质量保障 软件的质量指标是什么?怎么样能够提升软件的质量 ...

  8. 程序员编程艺术第三十六~三十七章、搜索智能提示suggestion,附近点搜索

    第三十六~三十七章.搜索智能提示suggestion,附近地点搜索 作者:July.致谢:caopengcs.胡果果.时间:二零一三年九月七日. 题记 写博的近三年,整理了太多太多的笔试面试题,如微软 ...

  9. 《Linux命令行与shell脚本编程大全》 第二十七章 学习笔记

    第二十七章:shell脚本编程进阶 监测系统统计数据 系统快照报告 1.运行时间 uptime命令会提供以下基本信息: 当前时间 系统运行的天数,小时数,分钟数 当前登录到系统的用户数 1分钟,5分钟 ...

随机推荐

  1. Begin using git

    First thing first, you can easily install git in all 3 mainstream OS, Windows, Linux, OSX. Get windo ...

  2. 传输层(一)TCP的三次握手和四次挥手及关闭套接字的原理

    TCP连接需三次握手才能建立,断开连接则需要四次握手. 客户端TCP状态迁移: CLOSED->SYN_SENT->ESTABLISHED->FIN_WAIT_1->FIN_W ...

  3. How to deploy JAVA Application on Azure Service Fabric

    At this moment, Azure Service Fabric does not support JAVA application natively (but it's on the sup ...

  4. 如何创建下拉列表为一个树列表?(此文为dev控件中,服务器控件暂不知,但想方法应该都差不多吧)

    //前端控件代码:<dx:ASPxDropDownEdit ID="drop_treelist" runat="server" ClientInstanc ...

  5. ajax和servlet交互

    网上有比较多的教程来将如何实现ajax与servlet的交互了,这里和这里的教程可以参考参考,在此处我只简单说明一下,并记录一下我这次遇到的问题. 整个思路是:写个js函数,在里面使用XHR(ajax ...

  6. 集群监控系统Ganglia应用案例

    集群监控系统Ganglia应用案例 --我们把集群系统投入生产环境后,这时就需要一套可视化的工具来监视集群系统,这将有助于我们迅速地了解机群的整体配置情况,准确地把握机群各个监控节点的信息,全面地察看 ...

  7. CSS 之 Opacity多浏览器透明度兼容处理

    用来设定元素透明度的 Opacity 是CSS 3里的一个属性.当然现在还只有少部分浏览器支持. 不过各个浏览器都有自己的私有属性来支持,其中包括老版本的Mozilla和Safari: IE: fil ...

  8. verilog中符号位的扩展问题

    以下内容转自 艾米电子 - 使用有符号数,Verilog(http://www.cnblogs.com/yuphone/archive/2010/12/12/1903647.html) Verilog ...

  9. Magento修改css样式

    Magento研究了第四天才开始搞明白怎么运行. 首先对于前端开发来说要修改样式的话需要运行: grunt less:luma 如果提示: 那就说明grunt配置的路径不对,默认是英文的,如果我们用中 ...

  10. leetcode 110

    110. Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, ...