第十七章 调试及安全性(In .net4.5) 之 程序诊断
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) 之 程序诊断的更多相关文章
- 第十六章 调试及安全性(In .net4.5) 之 调试程序
1. 概述 本章内容包括 如何选择合适的构建类型.创建和管理编译指令.管理程序数据文件(pdb)和指令. 2. 主要内容 2.1 构建类型 .net中默认的两种生成模式是 发布(Release)模式 ...
- 第十五章 调试及安全性(In .net4.5) 之 管理程序集
1. 概述 本章将介绍 什么是程序集.如何强命名程序集.如何把程序集放入GAC.程序集版本 以及 WinMD程序集. 2. 主要内容 2.1 什么是程序集 程序集(Assembly)概念的出现,是为了 ...
- 第十四章 调试及安全性(In .net4.5) 之 对称及非对称加密
1. 概述 本章内容包括:对称及非对称加密算法..net中的加密类.使用哈希操作.创建和管理签名认证.代码访问权限 和 加密字符串. 2. 主要内容 2.1 使用对称和非对称加密 ① 对称加密:使用同 ...
- 第十三章 调试及安全性(In .net4.5) 之 验证程序输入
1. 概述 本章介绍验证程序输入的重要性以及各种验证方法:Parse.TryParse.Convert.正则表达式.JavaScriptSerializer.XML Schemas. 2. 主要内容 ...
- Linux内核设计第十七章笔记
第十七章 设备与模块 关于设备驱动和设备管理,四种内核成分 设备类型:在所有unix系统中为了统一普通设备的操作所采用的分类 模块:Linux内核中用于按需加载和卸载目标代码的机制 内核对象:内核数据 ...
- 进击的Python【第十七章】:jQuery的基本应用
进击的Python[第十七章]:jQuery的基本应用
- <构建之法>第十三章到十七章有感以及这个项目读后感
<构建之法>第十三章到十七章有感 第13章:软件测试方法有哪些? 主要讲了软件测试方法:要说有什么问题就是哪种效率最高? 第14章:质量保障 软件的质量指标是什么?怎么样能够提升软件的质量 ...
- 程序员编程艺术第三十六~三十七章、搜索智能提示suggestion,附近点搜索
第三十六~三十七章.搜索智能提示suggestion,附近地点搜索 作者:July.致谢:caopengcs.胡果果.时间:二零一三年九月七日. 题记 写博的近三年,整理了太多太多的笔试面试题,如微软 ...
- 《Linux命令行与shell脚本编程大全》 第二十七章 学习笔记
第二十七章:shell脚本编程进阶 监测系统统计数据 系统快照报告 1.运行时间 uptime命令会提供以下基本信息: 当前时间 系统运行的天数,小时数,分钟数 当前登录到系统的用户数 1分钟,5分钟 ...
随机推荐
- OC基础(10)
id类型 SEL类型 *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !im ...
- CString.Format的详细用法(转)
CString.Format的详细用法(转) 在MFC程序中,使用CString来处理字符串是一个很不错的选择.CString既可以处理Unicode标准的字符串,也可以处理ANSI标准的字符串.CS ...
- CPPUTest 单元测试框架(针对 C 单元测试的使用说明)
CPPUTest 虽然名称上看起来是 C++ 的单元测试框架, 其实它也是支持测试 C 代码的. 本文主要介绍用CPPUTest来测试 C 代码. (C++没用过, 平时主要用的是C) C++相关的内 ...
- python学习(二):python基本语法
前言:python基本的语法与其他语言诸如C,JAVA等类似,但个中有些许不同. 一.常规语法 1.变量名与关键字 与其他语言类似,变量名由字母.数字.下划线组成,且必须由字母开头. 变量使用不需要提 ...
- 通过weka.jar包来进行数据预处理
前言:注意首先要将weka.jar包加载到相应的路径中去.程序中的数据也是用的weka自带的数据. 扩展:eclipse添加jar包的操作方法: 打开eclipse ,在对应的工程下右击,选择Buil ...
- dedecms首页怎么调用公司简介的内容
DeDeCMS功能虽然强大,但还是有些细节上的功能没有实现,正如本文描述的问题一样,DEDECMS要在网站首页调用公司简介的内容,而且还要截取前多少个字符数的时候,DEDECMS标签中没有能实现这样的 ...
- Eclipse SVN冲突解决
基本原则是:每次提交前需要先和线上的对比,先把冲突解决掉,然后把线上的更新到本地,最后把本地的提交上去. 右键项目 -> Team -> 与资源库同步 在同步视图中选择Conflicts ...
- Activity的四种launchMode 详细分析
launchMode在多个Activity跳转的过程中扮演着重要的角色,它可以决定是否生成新的Activity实例,是否重用已存在的 Activity实例,是否和其他Activity实例公用一个tas ...
- 关键字 this 的作用
1.关键字 this ①是指当前对象自己 当一个类中要明确指出使用对象自己的变量或函数时,就应该加上this关键字,小栗子a如下: public class A { string Name = &qu ...
- kickstart bonding安装
bonding用的是最简单的负载均衡模式,交换机不需要做配置. https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Lin ...