非淡泊无以明志,非宁静无以致远 -心静如止水,动于静

Track & Trace

在dot net里面有繼承了MFC的Trace機制。但在我們實際的開發中,發現有很少的開發人員養成在代碼里寫Debug和Trace語句的。這表明這些程序員缺乏基本功的培訓。

事實上,當在開發web component的時候,用logging的方式可以很快找到程序的bug所在,甚至更好的機制是在用戶還未發現系統有錯誤的時候,系統本身就向管理員報告了錯誤,這會給用戶體會上大大加分,同時也提升了IT的Value.

Trace和Debug是應用在不同的場景中的。Trace完全用于跟蹤系統的運行狀態。不論系統是Debug版本還是Release版本都應該用效(Enabled).

Debug語句一般用于Debug版本下,而且用斷言來主動彈出錯誤并且停留在錯誤的語句處。

TraceSource及TraceSwitch是應用于大型軟件開發對于Track&Trace的定制要求。一般系統用默認的Trace足夠。

Trace的輸出可以用代碼或配置文件兩種方式來處理

代碼方式:

System.Diagnostics.Trace.Listeners.Clear();
System.Diagnostics.Trace.AutoFlush=true;
System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.TextWriterTraceListener("app.log"));

配置方式:

<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="myListener"
          type="System.Diagnostics.TextWriterTraceListener"
          initializeData="TextWriterOutput.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

 

另外用屬性標簽來限定整塊的代碼也很方便,從MSDN中摘取代碼如下:

 

using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {              
        Console.WriteLine("Calling Method1");
        Method1(3);
        Console.WriteLine("Calling Method2");
        Method2();
       
        Console.WriteLine("Using the Debug class");
        Debug.Listeners.Add(new ConsoleTraceListener());
        Debug.WriteLine("DEBUG is defined");
    }
   
    [Conditional("CONDITION1")]
    public static void Method1(int x)
    {
        Console.WriteLine("CONDITION1 is defined");
    }
   
    [Conditional("CONDITION1"), Conditional("Condition2")] 
    public static void Method2()
    {
        Console.WriteLine("CONDITION1 or Condition2 is defined");
    }
}

/*
When compiled as shown, the application (named ConsoleApp)
produces the following output.

csc ConsoleApp.cs
Calling Method1
Calling Method2
Using the Debug class

csc /define:CONDITION1 ConsoleApp.cs
Calling Method1
CONDITION1 is defined
Calling Method2
CONDITION1 or Condition2 is defined
Using the Debug class

csc /define:Condition2 ConsoleApp.cs
Calling Method1
Calling Method2
CONDITION1 or Condition2 is defined
Using the Debug class

csc /define:DEBUG ConsoleApp.cs
Calling Method1
Calling Method2
Using the Debug class
DEBUG is defined
*/

posted @ 2009-01-07 17:43  烟雨客  阅读(634)  评论(1编辑  收藏  举报