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. python函数 位置参数,关键字参数,可变参数优先级

    def fun(arg,args=1,*arg,**keywords): python 一共有这四类参数,第一类最常见,不用多说,第二类,关键字参数,python能通过关键字找到参数,python函数 ...

  2. The Ninth Hunan Collegiate Programming Contest (2013) Problem F

    Problem F Funny Car Racing There is a funny car racing in a city with n junctions and m directed roa ...

  3. CODESOFT对话框中的显示字体怎么修改

      不同的人其使用软件的视觉习惯是不一样的,直接给大家介绍过如何设置CODESOFT的界面语言,这是一个大范围的界面显示设置.本文,将介绍如何修改CODESOFT对话框显示的字体,以满足自己的视觉习惯 ...

  4. 解决VS2008 开发Windows Mobile 项目生成速度慢的问题

    最近用VS2008开发Windows Mobile程序,使用C#..NET Compact Framework,发现项目生成速度比较慢.用VS2008打开项目后,开始一段时间生成速度还能忍受,时间一长 ...

  5. Android开发-API指南-任务和回退栈

    Task and Back Stack 英文原文: http://developer.android.com/guide/components/tasks-and-back-stack.html 采集 ...

  6. Select的深入应用(1)

    在子句中使用列的位置: 使用select语句创建新表: 在子句中使用列的别名: 注意,你的 ANSI SQL 不允许你在一个WHERE子句中引用一个别名.这是因为在WHERE代码被执行时,列值还可能没 ...

  7. 解决问题 “You don't have permission to access /index.html on this server.”

    前几天装一个linux 企业版5.0安装了apache,打开测试页面的时候出现如下错误: Forbidden You don't have permission to access /index.ht ...

  8. 二模11day2解题报告

    T1.修改文章(amend) 给出n个单词和一个长度为m的字符串,求改动多少个字符才能使字符串全由单词组成. 要说这道题还真的坑很坑超坑非常坑无敌坑--不过还是先想到了动规.毕竟要修改的前提是要组成的 ...

  9. win8下安装ubuntu双系统

    终于成功在win8下安装成功ubuntu13.10, 安装方法来源于http://forum.ubuntu.org.cn/viewtopic.php?t=446557 下面的文件是该楼主的将安装ubu ...

  10. vyos (一) 基础配置

    http://www.lowefamily.com.au/2015/11/29/using-a-vyos-router-with-hyper-v/1/ http://thomasvochten.com ...