C#笔记30:Trace、Debug和TraceSource的使用以及日志设计

简介: C#笔记30:Trace、Debug和TraceSource的使用以及日志设计 本章概要: 1:Trace 和 Debug区别 2:什么是Listeners 3:跟踪开关      3.1:使用BooleanSwitch开关      3.

C#笔记30:Trace、Debug和TraceSource的使用以及日志设计

本章概要:

1:Trace 和 Debug区别

2:什么是Listeners

3:跟踪开关

     3.1:使用BooleanSwitch开关

     3.2:使用TraceSwitch开关

4:使用TraceSource代替Trace和

 

5:设计一个日志系统

6:关于EventLog

 

      .NET Framework 命名空间 System.Diagnostics 包含用于跟踪执行流程的 TraceDebugTraceSource 类,以及用于分析代码的 ProcessEventLogPerformanceCounter 类。

      跟踪是一种在应用程序运行时监视其执行情况的方式。当开发 .NET Framework 应用程序时,可以在其中添加跟踪和调试检测功能,并且在开发应用程序时和部署应用程序后,都可以使用该检测功能。利用 TraceDebug 类,可以将有关错误和应用程序执行的信息记录到日志、文本文件或其他设备中,以便在随后进行分析。

      下面列出了六个写入跟踪信息的 Debug Members 和 Trace 方法。

Assert:指定的文本;如果未指定任何文本,则为“调用堆栈”。只有当 Assert 语句中以参数形式指定的条件为 false 时,才会写入输出。

Fail:指定的文本;如果未指定任何文本,则为“调用堆栈”。

Write:指定的文本。

WriteIf:如果满足 WriteIf 语句中以参数形式指定的条件,则为指定的文本。

WriteLine:指定的文本和一个回车。

WriteLineIf:如果满足 WriteLineIf 语句中以参数形式指定的条件,则为指定的文本和一个回车。

 

1:Trace 和 Debug区别

      TraceDebug 类基本相同,不同的只是 Trace 类的过程和函数默认为编译成发布版本。

 

2:什么是Listeners

      Listenters属性,它是TraceListenerCollection类型(TraceSource类和TraceListener类),给类属性控制跟踪信息输出的方向,可以是控制台(add(TextWriterTraceListener(new Console.Out))),文件(add(TextWriterTraceListener(new IO.File.CreateText(“output.txt”))等。Listenters集合中的成员包括TextWriterTraceListener,DefaultTraceListener,EventLogTraceListener,WebPageTraceListener等。而TextWriterTraceListener的子类又有ConsoleTraceListener, DelimitedListTraceListener,XmlWriterTraceListener,EventSchemaTraceListener。

     您可以通过实现您自己的侦听器来生成自定义的结果。 所有自定义侦听器都应支持文章开头表中的六个方法。

     以下的例子说明输出的消息将会在控制台、TXT文件以及系统日志中均被记录。

            TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
            Debug.Listeners.Add(tr1);
            TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("output.txt"));
            Debug.Listeners.Add(tr2);
            EventLogTraceListener tr3 = new EventLogTraceListener();
            Debug.Listeners.Add(tr3);

 

3:跟踪开关

      除了指定Listener外,要控制消息是否被输出,还需要指定跟踪开关。跟踪开关用于启用、禁用和筛选跟踪输出。

      Framework 中提供了三种类型的跟踪开关:BooleanSwitch 类、TraceSwitch 类和 SourceSwitch 类。BooleanSwitch是最简单的跟踪开关,可以指定是否输出消息。TraceSwitchSourceSwitch 类用于为特定的跟踪级别启用跟踪开关,以便显示为该级别及其下的所有级别指定的 TraceTraceSource 消息。

3.1:使用BooleanSwitch开关

      以下是使用BooleanSwitch的例子:

            TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
            Debug.Listeners.Add(tr1);
            TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("output.txt"));
            Debug.Listeners.Add(tr2);
            EventLogTraceListener tr3 = new EventLogTraceListener();
            Debug.Listeners.Add(tr3);

            bool someBizCondition = true;
            BooleanSwitch bs = new BooleanSwitch("DataMessageSwitch", "DataMessageSwitch des");
            bs.Enabled = true;
            Debug.WriteLineIf(someBizCondition, "log....");
            Debug.Flush();

 

      bs.Enabled设置为true或者false,并不会使程序自动决定是否输出信息。

      如果不使用代码方式,而是使用配置文件的方式,是在 <configuration> 标记之后,但在 </configuration> 标记之前添加相应的 XML 来配置您的开关。如下:

<system.diagnostics>
   <switches>
      <add name="DataMessagesSwitch" value="1" />
   </switches>
</system.diagnostics>
 

3.2:使用TraceSwitch开关

      TraceSwitch类可以通过使用跟踪开关来筛选消息,通过Level属性来获取或设置开关级别。0、1、2、3 和 4 分别对应于 OffErrorWarningInfoVerbose。任何大于 4 的数字都会被当作 Verbose,任何小于零的数字都会被当作 Off

      以下的例子,用代码的方式来演示使用TraceSwitch来设置跟踪开关:

            TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
            Debug.Listeners.Add(tr1);
            TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("output.txt"));
            Debug.Listeners.Add(tr2);
            EventLogTraceListener tr3 = new EventLogTraceListener();
            Debug.Listeners.Add(tr3);

            bool someBizCondition = true;
            TraceSwitch ts = new TraceSwitch("mySwitch", "in the Config file");
            ts.Level = TraceLevel.Verbose;
            Debug.WriteLineIf(ts.TraceError && someBizCondition, "Error!!!");
            Debug.WriteLineIf(ts.TraceWarning && someBizCondition, "Warning!!!");
            Debug.WriteLineIf(ts.TraceInfo && someBizCondition, "Info!!!");
            Debug.WriteLineIf(ts.TraceVerbose && someBizCondition, "Verbose!!!");
            Debug.Flush();

 

       使用XML来配置,如下:

<system.diagnostics>
   <switches>
      <add name="mySwitch" value="1" />
   </switches>
</system.diagnostics>

 

4:使用TraceSource代替Trace和Debug

       从FRAMEWORK2.0开始,就不建议使用Trace和Debug了,而改而用TraceSouce。TraceSource 旨在用作增强的跟踪系统,并且可代替较旧的 TraceDebug 跟踪类的静态方法使用。熟悉的 TraceDebug 类仍然存在,不过建议的做法是使用 TraceSource 类进行跟踪。

       下面的例子演示使用代码来实现消息的输出:

 

        private static TraceSource mySource = new TraceSource("TraceSourceApp");
        static void Main(string[] args)
        {
            mySource.Switch = new SourceSwitch("sourceSwitch", "Error");
            mySource.Listeners.Remove("Default");

            TextWriterTraceListener textListener =  new TextWriterTraceListener("myListener.log");
            textListener.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.Callstack;
            textListener.Filter = new EventTypeFilter(SourceLevels.Error);
            mySource.Listeners.Add(textListener);
            
            ConsoleTraceListener console = new ConsoleTraceListener(false);
            console.Filter = new EventTypeFilter(SourceLevels.Information);
            console.Name = "console";
            mySource.Listeners.Add(console);
            Activity1();

            // Set the filter settings for the 
            // console trace listener.
            mySource.Listeners["console"].Filter =  new EventTypeFilter(SourceLevels.Critical);
            Activity2();

            // Allow the trace source to send messages to 
            // listeners for all event types. 
            mySource.Switch.Level = SourceLevels.All;

            // Change the filter settings for the console trace listener.
            mySource.Listeners["console"].Filter = new EventTypeFilter(SourceLevels.Information);
            Activity3();
            mySource.Close();

            return;
        }
        static void Activity1()
        {
            mySource.TraceEvent(TraceEventType.Error, 1, "Error message.");
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.");
        }
        static void Activity2()
        {
            mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.");
            mySource.TraceInformation("Informational message.");
        }
        static void Activity3()
        {
            mySource.TraceEvent(TraceEventType.Error, 4, "Error message.");
            mySource.TraceInformation("Informational message.");
        }

 

 

      以上代码,如果使用配置文件的方式实现,如下:

  <system.diagnostics>
    <sources>
      <source name="TraceSourceApp" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch">
        <listeners>
          <add name="console" type="System.Diagnostics.ConsoleTraceListener">
            <filter type="System.Diagnostics.EventTypeFilter" initializeData="Warning"/>
          </add>
          <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="myListener.log" 
               traceOutputOptions="Callstack">
            <filter type="System.Diagnostics.EventTypeFilter" initializeData="Error"></filter>
          </add>
          <remove name="Default"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="sourceSwitch" value="Warning"/>
    </switches>
  </system.diagnostics>

 

      配置文件实现的对应代码部分为:

        private static TraceSource mySource = new TraceSource("TraceSourceApp");
        static void Main(string[] args)
        {
            Activity1();
            Activity2();
            Activity3();
            mySource.Close();
            return;
        }
        static void Activity1()
        {
            mySource.TraceEvent(TraceEventType.Error, 1, "Error message.");
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.");
        }
        static void Activity2()
        {
            mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.");
            mySource.TraceInformation("Informational message.");
        }
        static void Activity3()
        {
            mySource.TraceEvent(TraceEventType.Error, 4, "Error message.");
            mySource.TraceInformation("Informational message.");
        }

 

 

5:设计一个日志系统

      有了以上的知识之后,我们就可以来设计一个应用程序的日志系统(是的,我们不在需要LOG4NET)。我们来假设这个日志系统最基础的功能:

      1、以日期来创建日志名,以免历史日志全部写入一个文件中去;

      2、可以配置想要输出的日志类别,如Warning或者Error等;

      3、可以配置想要的日志内容:如StackTrace或者错误信息等;

      思路:

      1、在应用程序启动代码中,设置文件名。因为文件名要根据日期动态生成,所以不能使用配置文件;

      2、其它配置可以配置文件实现;

      3、DO IT;

 

6:关于EventLog

     关于EventLog是一个我不喜欢的功能,更多内容,可参考:http://msdn.microsoft.com/zh-cn/library/aaaxk5bx(VS.80).aspx

 微信扫一扫,关注最课程(www.zuikc.com),获取更多我的文章,获取软件开发每日一练

练习:

1.You are using the Microsoft Visual Studio 2005 IDE to examine the output of a method that returns a string. 
You assign the output of the method to a string variable named fName. You need to write a code segment that
prints the following on a single line     The message. "Test Failed. " The value of fName if the value of fName does 
not equal "John" You also need to ensure that the code segment simultaneously facilitates uninterrupted execution   
of the application. Which code segment should you use?
A. Debug.Assert(fName == "John", "Test FaileD. ", fName);
B. Debug.WriteLineIf(fName != "John", fName, "Test Failed");
C. if (fName != "John") {Debug.Print("Test FaileD. "); Debug.Print(fName);      }
D. if (fName != "John") {Debug.WriteLine("Test FaileD. "); Debug.WriteLine(fName);     }
Answer: B

 

17.You are testing a newly developed method named PersistToDB. This method accepts a parameter of type 
EventLogEntry. This method does not return a value. You need to create a code segment that helps you to test the   
method. The code segment must read entries from the application log of local computers and then pass the entries
on to the PersistToDB method. The code block must pass only events of type Error or Warning from the source
MySource to the PersistToDB method. Which code segment should you use? 
A. EventLog myLog = new EventLog("Application", ".");       
foreach (EventLogEntry entry in myLog.Entries)   
{if (entry.Source == "MySource") {  PersistToDB(entry);     }  }
B. EventLog myLog = new EventLog("Application", ".");        
myLog.Source = "MySource";     
foreach (EventLogEntry entry in myLog.Entries) {          
if (entry.EntryType == (EventLogEntryType.Error & EventLogEntryType.Warning))   
{ PersistToDB(entry);  }}

C. EventLog myLog = new EventLog("Application", ".");        
foreach (EventLogEntry entry in myLog.Entries)   
{ if (entry.Source == "MySource")  
{if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning) 
  {PersistToDB(entry); }  } }
D. EventLog myLog = new EventLog("Application", ".");       
myLog.Source = "MySource";     
foreach (EventLogEntry entry in myLog.Entries)   
{if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning)   
{PersistToDB(entry); }
Answer: C

Creative Commons License本文基于 Creative Commons Attribution 2.5 China Mainland License发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名 http://www.cnblogs.com/luminji(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。
相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
目录
相关文章
|
5月前
|
数据可视化 BI
利用可视化方法优化年终述职:职场人如何让汇报效率提升200%?
本教程教你用可视化思维打造高效述职报告:通过四大模块(成果全景、KPI仪表盘、能力雷达、未来规划)和五步法(数据整理、工具选择、设计原则、结构优化、演讲技巧),结合看板工具实操,将零散工作转化为直观图表,让成果清晰可见、价值精准传达,提升专业形象与汇报说服力。
|
2月前
|
人工智能 机器人 Linux
小龙虾 OpenClaw 一人团队搭建指南:阿里云/本地部署+集成钉钉+Seedance2.0 打造全自动AI漫剧工作室
“一个人如何日更3条漫剧视频?”——这是2026年内容创作者的核心诉求。参考文章作者“刀哥”通过实战验证,用OpenClaw联动钉钉AI表格与Seedance2.0,搭建起全自动化漫剧生产流水线:每天8:30自动抓取爆款榜单、分析热门要素、生成分镜脚本、产出视频成片,全程无需人工干预,真正实现“一人即团队”。
2577 3
|
2月前
|
人工智能 自然语言处理 API
AI漫剧零代码制作喂饭级教程:OpenClaw阿里云/本地部署+Seed2.0 Skills 实战指南
无需专业剪辑技术、不用复杂软件操作,甚至不用手动绘制分镜——借助OpenClaw与Seed2.0 Skills的组合,2026年普通人也能零门槛制作AI漫剧。从剧本创作、分镜设计到视频合成,全程AI自动化完成,手机端也能快速产出高质量作品。开源项目「AI漫导」(director_ai)已收获1.1k Star,其核心逻辑正是通过OpenClaw集成Seed2.0漫剧专属技能,让漫剧制作从“专业门槛”变为“人人可玩”。
2700 2
|
5月前
|
移动开发 安全 API
阿里云最新域名注册续费收费标准,域名优惠口令及口令使用教程
目前阿里云的.com英文域名的注册价格由原来的83元涨价到了85元,续费价格也涨到了95元,不过阿里云为用户提供了多种域名活动,例如域名批量注册优惠,新用户首次注册优惠,以及域名续费优惠口令等,不管是新用户还是老用户,在注册、续费域名的时候,都可以使用域名优惠口令享受一定金额的减免优惠,本文为大家整理了截止目前最新的域名注册续费和转入收费价格表,以及阿里云最新域名优惠口令及口令使用教程。
4014 0
|
4月前
|
人工智能 前端开发 Docker
Huobao Drama 开源短剧生成平台:从剧本到视频
Huobao Drama 是一个基于 Go + Vue3 的开源 AI 短剧自动化生成平台,支持剧本解析、角色与分镜生成、图生视频及剪辑合成,覆盖短剧生产全链路。内置角色管理、分镜设计、视频合成、任务追踪等功能,支持本地部署与多模型接入(如 OpenAI、Ollama、火山等),搭配 FFmpeg 实现高效视频处理,适用于短剧工作流验证与自建 AI 创作后台。
5053 6
|
12月前
|
人工智能 自然语言处理 算法
AI智能混剪视频大模型开发方案:从文字到视频的自动化生成·优雅草卓伊凡
AI智能混剪视频大模型开发方案:从文字到视频的自动化生成·优雅草卓伊凡
1543 0
AI智能混剪视频大模型开发方案:从文字到视频的自动化生成·优雅草卓伊凡
|
8月前
|
JSON 监控 API
淘宝/天猫:使用订单查询API实时追踪包裹状态,自动推送物流通知至用户
在淘宝/天猫平台,通过集成订单查询API实现物流状态实时监控,结合定时轮询与自动推送通知功能,可有效减少用户频繁刷新页面,提升购物体验。本文详解API调用原理、状态判断及Python代码实现,助力开发者构建高效、智能的物流通知系统。
766 0
|
12月前
|
Web App开发 数据采集 JavaScript
动态网页爬取:Python如何获取JS加载的数据?
动态网页爬取:Python如何获取JS加载的数据?
1751 58
|
12月前
|
机器学习/深度学习 开发框架 数据可视化
B站开源SOTA动画视频生成模型 Index-AniSora!
B站升级动画视频生成模型Index-AniSora技术并开源,支持番剧、国创、漫改动画、VTuber、动画PV、鬼畜动画等多种二次元风格视频镜头一键生成!
1282 32

热门文章

最新文章