HOW TO:建立和初始設定追蹤接聽項
更新:2007 年 11 月
Debug 和 Trace 類別將訊息傳送至稱為接聽程式的物件,由接聽項物件負責接收和處理這些訊息。當啟用追蹤或偵錯時,會自動建立和初始化 DefaultTraceListener 此類接聽項,如需詳細資訊,請參閱追蹤接聽項。如果您要將 Trace 或 Debug 輸出傳送至任何其他來源,您必須建立和初始化其他的追蹤接聽項。
您建立的接聽程式應反映出您個人的需求。例如,您可能想要所有追蹤輸出的文字記錄。在這種情況中,您建立的接聽程式要在啟用時,將所有的輸出寫入新的文字檔。另一方面,您可能只想在應用程式執行期間檢視輸出。在這種情況中,您可建立導向所有輸出至主控台視窗的接聽程式。EventLogTraceListener 可以導向追蹤輸出至事件記錄檔,而 TextWriterTraceListener 可將追蹤輸出寫入資料流。
若要建立和初始化追蹤接聽項
宣告追蹤接聽項。如果您要建立的接聽程式需要任何其他物件,也請宣告這些物件。下列範例顯示如何建立接聽程式以寫入文字檔:
' Creates the text file that the trace listener will write to. Dim myTraceLog As New System.IO.FileStream("C:\myTraceLog.txt", _ IO.FileMode.OpenOrCreate) ' Creates the new trace listener Dim myListener As New TextWriterTraceListener(myTraceLog)
// Creates the text file that the trace listener will write to. System.IO.FileStream myTraceLog = new System.IO.FileStream("C:\\myTraceLog.txt", System.IO.FileMode.OpenOrCreate); // Creates the new trace listener. System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener(myTraceLog);
發出追蹤輸出。
如果您要接聽程式接收所有的追蹤輸出,請將追蹤接聽項加入至 Listeners 集合。
下列範例顯示如何將接聽程式加入至 Listeners 集合:
Trace.Listeners.Add(myListener)
System.Diagnostics.Trace.Listeners.Add(myListener);
-或-
如果您不希望接聽項接收追蹤輸出,請不要將接聽程式加入至 Listeners 集合。您可透過與 Listeners 集合無關的接聽程式來發出輸出,其方式是呼叫接聽項自己的輸出方法。下列範例顯示如何將指令碼寫入不在 Listeners 集合中的接聽程式:
myListener.WriteLine( _ "This output will not go to the Listeners collection")
myListener.WriteLine( "This output will not go to the Listeners collection");
如果您的接聽程式不是 Listeners 集合的成員,可能必須呼叫 Flush 方法才能記錄輸出。
' Flushes the buffers of all listeners in the Listeners collection. Trace.Flush() ' Flushes only the buffer of myListener. myListener.Flush()
// Flushes the buffers of all listeners in the Listeners collection. System.Diagnostics.Trace.Flush(); // Flushes only the buffer of myListener. myListener.Flush();