[C#.NET] 追蹤類別 - Debug 與 Trace 類別

  • 20615
  • 0
  • C#
  • 2013-07-05

[C#.NET] 追蹤類別-Debug 與 Trace 類別

在寫程式的時候我常用Debug 類別Trace 類別,這兩個類別的用法都一樣,只是差當在Debug模式時,Debug與Trace類別都會執行,在Release模式下時只會執行Trace類別,我們可以使用下列語法將程式印出,最後它們會在輸出視窗出現。

Debug.WriteLine("余小章");
Trace.WriteLine("余小章");

image

image



倘若只有這樣當然很難觀察的到,我們可以使用TextWriterTraceListener 類別將它們輸出到檔案,慢慢的看。

TextWriterTraceListener _DebugLog = new TextWriterTraceListener(System.IO.File.CreateText("Debug_Output.txt"));

Debug.Listeners.Add(_DebugLog);
Debug.AutoFlush = true;
Debug.WriteLine("Debug 余小章");
Trace.WriteLine("Release 余小章");

Debug.AutoFlush=true將會自動的存到檔案,不然也可以使用Debug.Flush()來存到檔案;若無指定路徑輸出後的檔案將與你編譯好的執行檔擺在一起。


同樣的結果我們也可以利用組態檔來達成,在App.config裡輸入以下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" >
      <listeners>
        <add name="testLog" 
             type="System.Diagnostics.TextWriterTraceListener"
             initializeData="d:\testLog.log">
        </add>
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>


善用Debug.Assert()方法,在還沒知道使用Debug.Assert之前(vb6的時候)我都用MessageBox.Show(),這真不是一個好方法,當專案要Release時還得手動去把它註解掉,現在我用就不必特意這麼做了

Debug.Assert(false, "錯誤", "觸發錯誤");

image

使用Debug.Assert()方法最主要是在觀察條件是否有成立,若沒有成立則跳出警告視窗,條件沒有成立可能是自己所沒有想到的條件,所以千萬不要爛用try catch來忽略錯誤,否則未來將很難找的出到底是哪個條件不成立;小弟個人的習慣在程式初步建構時不會輕易的使用try catch,除非真的很確定使用try catch不會有困擾發生。

assertuienabled屬性是用來啟/停警告視窗<assert assertuienabled="false"/>,logfilename屬性是用來輸出結果至檔案<assert logfilename="d:\test.text"/>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" >
      <listeners>
        <add name="testLog" 
             type="System.Diagnostics.TextWriterTraceListener"
             initializeData="d:\testLog.log"
             traceOutputOptions="DateTime,ProcessId,Timestamp,ThreadId">
        </add>
       
      </listeners>
    </trace>
    <assert assertuienabled="false" logfilename="d:\test.txt"/>

  </system.diagnostics>
</configuration>

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo