DefaultTraceListener 類別

定義

提供追蹤的預設輸出方法和行為。

public ref class DefaultTraceListener : System::Diagnostics::TraceListener
public class DefaultTraceListener : System.Diagnostics.TraceListener
[System.Runtime.InteropServices.ComVisible(false)]
public class DefaultTraceListener : System.Diagnostics.TraceListener
type DefaultTraceListener = class
    inherit TraceListener
[<System.Runtime.InteropServices.ComVisible(false)>]
type DefaultTraceListener = class
    inherit TraceListener
Public Class DefaultTraceListener
Inherits TraceListener
繼承
DefaultTraceListener
繼承
DefaultTraceListener
屬性

範例

下列程式碼範例會計算二項係數,這些係數是機率和統計資料中使用的值。 此範例會使用 DefaultTraceListener 來追蹤結果和記錄錯誤。 它會建立新的 DefaultTraceListener ,並將其新增至 Trace.Listeners 集合,並將 屬性設定 LogFileName 為命令列引數中指定的記錄檔。

如果在處理輸入參數時偵測到錯誤,或函 CalcBinomial 式擲回例外狀況,方法會 Fail 記錄並顯示錯誤訊息。 AssertUiEnabled如果 屬性為 false ,錯誤訊息也會寫入主控台。 成功計算結果時, Write(String)WriteLine(String) 方法會將結果寫入記錄檔。

FailWriteWriteLine 方法只會將追蹤資訊寫入 DefaultTraceListener 。 若要將追蹤資訊寫入集合中的所有 Trace.Listeners 接聽程式,請使用 Fail 類別的 TraceWriteWriteLine 方法。

using System;
using System.Diagnostics;
using Microsoft.VisualBasic;

class Binomial
{

    // args(0) is the number of possibilities for binomial coefficients.
    // args(1) is the file specification for the trace log file.
    public static void Main(string[] args)
    {

        decimal possibilities;
        decimal iter;

        // Remove the original default trace listener.
        Trace.Listeners.RemoveAt(0);

        // Create and add a new default trace listener.
        DefaultTraceListener defaultListener;
        defaultListener = new DefaultTraceListener();
        Trace.Listeners.Add(defaultListener);

        // Assign the log file specification from the command line, if entered.
        if (args.Length>=2)
        {
            defaultListener.LogFileName = args[1];
        }

        // Validate the number of possibilities argument.
        if (args.Length>=1)

            // Verify that the argument is a number within the correct range.
        {
            try
            {
                const decimal MAX_POSSIBILITIES = 99;
                possibilities = Decimal.Parse(args[0]);
                if (possibilities<0||possibilities>MAX_POSSIBILITIES)
                {
                    throw new Exception(String.Format("The number of possibilities must " +
                        "be in the range 0..{0}.", MAX_POSSIBILITIES));
                }
            }
            catch(Exception ex)
            {
                string failMessage = String.Format("\"{0}\" " +
                    "is not a valid number of possibilities.", args[0]);
                defaultListener.Fail(failMessage, ex.Message);
                if (!defaultListener.AssertUiEnabled)
                {
                    Console.WriteLine(failMessage+ "\n" +ex.Message);
                }
                return;
            }
        }
        else
        {
            // Report that the required argument is not present.
            const string ENTER_PARAM = "Enter the number of " +
                      "possibilities as a command line argument.";
            defaultListener.Fail(ENTER_PARAM);
            if (!defaultListener.AssertUiEnabled)
            {
                Console.WriteLine(ENTER_PARAM);
            }
            return;
        }

        for(iter=0; iter<=possibilities; iter++)
        {
            decimal result;
            string binomial;

            // Compute the next binomial coefficient and handle all exceptions.
            try
            {
                result = CalcBinomial(possibilities, iter);
            }
            catch(Exception ex)
            {
                string failMessage = String.Format("An exception was raised when " +
                    "calculating Binomial( {0}, {1} ).", possibilities, iter);
                defaultListener.Fail(failMessage, ex.Message);
                if (!defaultListener.AssertUiEnabled)
                {
                    Console.WriteLine(failMessage+ "\n" +ex.Message);
                }
                return;
            }

            // Format the trace and console output.
            binomial = String.Format("Binomial( {0}, {1} ) = ", possibilities, iter);
            defaultListener.Write(binomial);
            defaultListener.WriteLine(result.ToString());
            Console.WriteLine("{0} {1}", binomial, result);
        }
    }

    public static decimal CalcBinomial(decimal possibilities, decimal outcomes)
    {

        // Calculate a binomial coefficient, and minimize the chance of overflow.
        decimal result = 1;
        decimal iter;
        for(iter=1; iter<=possibilities-outcomes; iter++)
        {
            result *= outcomes+iter;
            result /= iter;
        }
        return result;
    }
}
Imports System.Diagnostics

Module Binomial

    ' args(0) is the number of possibilities for binomial coefficients.
    ' args(1) is the file specification for the trace log file.
    Sub Main(ByVal args() As String)

        Dim possibilities As Decimal
        Dim iter As Decimal

        ' Remove the original default trace listener.
        Trace.Listeners.RemoveAt(0)

        ' Create and add a new default trace listener.
        Dim defaultListener As DefaultTraceListener
        defaultListener = New DefaultTraceListener
        Trace.Listeners.Add(defaultListener)

        ' Assign the log file specification from the command line, if entered.
        If args.Length >= 2 Then
            defaultListener.LogFileName = args(1)
        End If

        ' Validate the number of possibilities argument.
        If args.Length >= 1 Then

            ' Verify that the argument is a number within the correct range.
            Try
                Const MAX_POSSIBILITIES As Decimal = 99
                possibilities = Decimal.Parse(args(0))
                If possibilities < 0 Or possibilities > MAX_POSSIBILITIES Then
                    Throw New Exception( _
                        String.Format("The number of possibilities must " & _
                            "be in the range 0..{0}.", MAX_POSSIBILITIES))
                End If
            Catch ex As Exception
                Dim failMessage As String = String.Format("""{0}"" " & _
                    "is not a valid number of possibilities.", args(0))
                defaultListener.Fail(failMessage, ex.Message)
                If Not defaultListener.AssertUiEnabled Then
                    Console.WriteLine(failMessage & vbCrLf & ex.Message)
                End If
                Return
            End Try
        Else
            ' Report that the required argument is not present.
            Const ENTER_PARAM As String = "Enter the number of " & _
                "possibilities as a command line argument."
            defaultListener.Fail(ENTER_PARAM)
            If Not defaultListener.AssertUiEnabled Then
                Console.WriteLine(ENTER_PARAM)
            End If
            Return
        End If

        For iter = 0 To possibilities
            Dim result As Decimal
            Dim binomial As String

            ' Compute the next binomial coefficient and handle all exceptions.
            Try
                result = CalcBinomial(possibilities, iter)
            Catch ex As Exception
                Dim failMessage As String = String.Format( _
                        "An exception was raised when " & _
                        "calculating Binomial( {0}, {1} ).", _
                        possibilities, iter)
                defaultListener.Fail(failmessage, ex.Message)
                If Not defaultListener.AssertUiEnabled Then
                    Console.WriteLine(failMessage & vbCrLf & ex.Message)
                End If
                Return
            End Try

            ' Format the trace and console output.
            binomial = String.Format("Binomial( {0}, {1} ) = ", _
                            possibilities, iter)
            defaultListener.Write(binomial)
            defaultListener.WriteLine(result.ToString)
            Console.WriteLine("{0} {1}", binomial, result)
        Next
    End Sub

    Function CalcBinomial(ByVal possibilities As Decimal, _
                        ByVal outcomes As Decimal) As Decimal

        ' Calculate a binomial coefficient, and minimize the chance of overflow.
        Dim result As Decimal = 1
        Dim iter As Decimal
        For iter = 1 To possibilities - outcomes
            result *= outcomes + iter
            result /= iter
        Next
        Return result
    End Function
End Module

備註

這個類別的實例會自動新增至 Debug.ListenersTrace.Listeners 集合。 明確新增第二 DefaultTraceListener 個會導致偵錯工具輸出視窗中重複的訊息,以及判斷提示的重複訊息方塊。

根據預設, WriteWriteLine 方法會將訊息發出至 Win32 OutputDebugString 函式和 Debugger.Log 方法。

根據預設,此方法 Fail 會在應用程式以使用者介面模式執行時顯示訊息方塊;它也會使用 WriteLine 發出訊息。

注意

Fail 方法呼叫訊息方塊 Assert 的顯示取決於 是否存在 DefaultTraceListenerDefaultTraceListener如果 不在集合中 Listeners ,則不會顯示訊息方塊。 DefaultTraceListener您可以藉由呼叫 Clear 屬性上的 Listeners 方法, () System.Diagnostics.Trace.Listeners.Clear() 來移除 。 對於.NET Framework應用程式,您也可以在應用程式的組態檔中使用< clear > 元素< remove > 元素

您必須啟用追蹤或偵錯,才能使用追蹤接聽程式。 下列語法是編譯器特有的。 如果您使用 C# 或 Visual Basic 以外的編譯器,請參閱編譯器的檔。

  • 若要在 C# 中啟用偵錯,請在編譯器程式碼時,將 旗標新增 /d:DEBUG 至編譯器命令列,或新增 #define DEBUG 至檔案頂端。 在 Visual Basic 中,將 /d:DEBUG=True 旗標新增至編譯器命令列。

  • 若要在 C# 中啟用追蹤,請在編譯器程式程式碼時,將 旗標新增 /d:TRACE 至編譯器命令列,或新增 #define TRACE 至檔案頂端。 在 Visual Basic 中,將 /d:TRACE=True 旗標新增至編譯器命令列。

對於.NET Framework應用程式,您可以編輯對應至應用程式名稱的組態檔,以新增追蹤接聽程式。 在此檔案中,您可以新增接聽程式、設定其類型並設定其參數、移除接聽程式,或清除應用程式先前設定的所有接聽程式。 組態檔的格式應該類似下列範例:

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

建構函式

DefaultTraceListener()

DefaultTraceListener 類別的新執行個體初始化 (將此執行個體的 Name 屬性值設為 "Default")。

屬性

AssertUiEnabled

取得或設定值,表示應用程式是否正在使用者介面模式下執行。

Attributes

取得在應用程式組態檔中定義的自訂追蹤接聽程式屬性。

(繼承來源 TraceListener)
Filter

取得或設定追蹤接聽程式的追蹤篩選。

(繼承來源 TraceListener)
IndentLevel

取得或設定縮排層級。

(繼承來源 TraceListener)
IndentSize

取得或設定縮排的空格數目。

(繼承來源 TraceListener)
IsThreadSafe

取得值,指出追蹤接聽程式是否為安全執行緒。

(繼承來源 TraceListener)
LogFileName

取得或設定要寫入追蹤或偵錯訊息的記錄檔名稱。

Name

取得或設定這個 TraceListener 的名稱。

(繼承來源 TraceListener)
NeedIndent

取得或設定值,指出是否要縮排輸出。

(繼承來源 TraceListener)
TraceOutputOptions

取得或設定追蹤輸出選項。

(繼承來源 TraceListener)

方法

Close()

當在衍生類別中覆寫時,關閉輸出資料流,使它不再接收追蹤或偵錯輸出。

(繼承來源 TraceListener)
CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
Dispose()

釋放 TraceListener 所使用的所有資源。

(繼承來源 TraceListener)
Dispose(Boolean)

釋放 TraceListener 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

(繼承來源 TraceListener)
Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Fail(String)

發出或顯示判斷提示 (Assertion) 總是失敗的訊息和堆疊追蹤。

Fail(String, String)

發出或顯示判斷提示總是失敗的詳細訊息和堆疊追蹤。

Flush()

當在衍生類別中覆寫時,會排清輸出緩衝區。

(繼承來源 TraceListener)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetSupportedAttributes()

取得由追蹤接聽程式支援的自訂屬性。

(繼承來源 TraceListener)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個執行個體的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。

(繼承來源 MarshalByRefObject)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object)

寫入追蹤資訊、資料物件與事件資訊至特定接聽程式的輸出。

(繼承來源 TraceListener)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object[])

寫入追蹤資訊、資料物件的陣列與事件資訊至特定接聽程式的輸出。

(繼承來源 TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32)

寫入追蹤和事件資訊至特定接聽程式的輸出。

(繼承來源 TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32, String)

寫入追蹤資訊、訊息與事件資訊至特定接聽程式的輸出。

(繼承來源 TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object[])

寫入追蹤資訊、格式化的物件陣列與事件資訊至特定接聽程式的輸出。

(繼承來源 TraceListener)
TraceTransfer(TraceEventCache, String, Int32, String, Guid)

寫入追蹤資訊、訊息、相關活動身分識別與事件資訊至特定接聽程式的輸出。

(繼承來源 TraceListener)
Write(Object)

將物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽程式。

(繼承來源 TraceListener)
Write(Object, String)

將類別名稱和物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽程式。

(繼承來源 TraceListener)
Write(String)

將輸出寫入 OutputDebugString 函示和 Log(Int32, String, String) 方法。

Write(String, String)

將分類名稱和訊息寫入當您實作 TraceListener 類別時所建立的接聽程式。

(繼承來源 TraceListener)
WriteIndent()

將縮排寫入當您實作這個類別時所建立的接聽程式,並且將 NeedIndent 屬性重設為 false

(繼承來源 TraceListener)
WriteLine(Object)

將物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽程式,後面跟隨著行結束字元。

(繼承來源 TraceListener)
WriteLine(Object, String)

將分類名稱和物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽程式,後面跟隨著行結束字元。

(繼承來源 TraceListener)
WriteLine(String)

將輸出寫入 OutputDebugString 函式和 Log(Int32, String, String) 方法,後面接著歸位字元和換行符號 (\r\n)。

WriteLine(String, String)

將分類名稱和訊息寫入當您實作 TraceListener 類別時所建立的接聽程式,後面跟隨著行結束字元。

(繼承來源 TraceListener)

適用於

執行緒安全性

這個類別是安全線程。

另請參閱