System.Diagnostics下面有三个类可以帮助我们诊断应用程序:

  1. Debug
  2. Trace
  3. EventLog

建立一个VS工程时,VS会为我们定义Trace和Debug这两个符号,它们的区别是Trace在release版本时也有效,而Debug只在Debug版本中有效。EventLog可以将日志记录到Windows的系统日志中.

Trace和Debug这两个类可以说用着相同的功能,只是Trace更强大些,默认情况下,它们的输出是调试器的Console。

示例(API的基本使用):

Effective C#学习笔记:适当使用.NET运行时诊断class Program
    }


 

Trace还和TraceSwitch可以搭配使用,来达到按级别配置输出的目的。还可以使用自定义的Listener

 

Effective C#学习笔记:适当使用.NET运行时诊断<?xml version="1.0" encoding="utf-8" ?>
Effective C#学习笔记:适当使用.NET运行时诊断
<configuration>
Effective C#学习笔记:适当使用.NET运行时诊断    
<system.diagnostics>
Effective C#学习笔记:适当使用.NET运行时诊断        
<trace autoflush="true" indentsize="0">
Effective C#学习笔记:适当使用.NET运行时诊断            
<listeners>
Effective C#学习笔记:适当使用.NET运行时诊断                
<add name="MyListener"
Effective C#学习笔记:适当使用.NET运行时诊断                     type
="System.Diagnostics.TextWriterTraceListener"
Effective C#学习笔记:适当使用.NET运行时诊断                     initializeData
="MyListener.log"/>
Effective C#学习笔记:适当使用.NET运行时诊断                
<add name="MyListener2"
Effective C#学习笔记:适当使用.NET运行时诊断                     type
="DiagnosticsApp.MyTraceListener, DiagnosticsApp"
Effective C#学习笔记:适当使用.NET运行时诊断                    
/>
Effective C#学习笔记:适当使用.NET运行时诊断            
</listeners>
Effective C#学习笔记:适当使用.NET运行时诊断        
</trace>
Effective C#学习笔记:适当使用.NET运行时诊断        
<switches>
Effective C#学习笔记:适当使用.NET运行时诊断            
<add name="Test" value="4"/>              
Effective C#学习笔记:适当使用.NET运行时诊断        
</switches>
Effective C#学习笔记:适当使用.NET运行时诊断    
</system.diagnostics>
Effective C#学习笔记:适当使用.NET运行时诊断
</configuration>

  Trace.WriteLineIf(GlobalSwitch.Level >= TraceLevel.Warning, "If error or warning...");

Effective C#学习笔记:适当使用.NET运行时诊断public class MyTraceListener : System.Diagnostics.TraceListener
    }



 

相关文章:

  • 2021-09-06
  • 2021-06-29
  • 2022-02-27
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-17
  • 2021-05-27
  • 2021-09-19
  • 2021-05-26
  • 2021-08-14
  • 2021-11-06
  • 2021-11-13
相关资源
相似解决方案