DefaultTraceListener DefaultTraceListener DefaultTraceListener DefaultTraceListener Class

定義

提供追蹤的預設輸出方法和行為。Provides the default output methods and behavior for tracing.

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

範例

下列程式碼範例會計算二項式係數, 這是 [機率] 和 [統計資料] 中使用的值。The following code example calculates binomial coefficients, which are values used in probability and statistics. 這個範例會使用DefaultTraceListener來追蹤結果和記錄錯誤。This example uses a DefaultTraceListener to trace results and log errors. 它會建立新DefaultTraceListener的, 並將它Trace.Listeners新增至LogFileName集合, 並將屬性設定為命令列引數中指定的記錄檔。It creates a new DefaultTraceListener, adds it to the Trace.Listeners collection, and sets the LogFileName property to the log file specified in the command-line arguments.

如果在處理輸入參數時偵測到錯誤, 或如果CalcBinomial函式擲回例外狀況, 則Fail方法會記錄並顯示錯誤訊息。If an error is detected while processing the input parameter, or if the CalcBinomial function throws an exception, the Fail method logs and displays an error message. 如果屬性為false, 則錯誤訊息也會寫入主控台。 AssertUiEnabledIf the AssertUiEnabled property is false, the error message is also written to the console. 成功計算結果時, Write(String)WriteLine(String)方法會將結果寫入記錄檔。When the result is calculated successfully, the Write(String) and WriteLine(String) methods write the results to the log file.

、和方法會導致只將DefaultTraceListener追蹤資訊寫入。 WriteLine Write FailThe Fail, Write, and WriteLine methods cause trace information to be written only to the DefaultTraceListener. 若要將Trace.Listeners追蹤資訊寫入集合中的所有接聽程式, 請Write Fail使用Trace類別WriteLine的、和方法。To write trace information to all listeners in the Trace.Listeners collection, use the Fail, Write, and WriteLine methods of the Trace class.

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集合。An instance of this class is automatically added to the Debug.Listeners and Trace.Listeners collections. 明確地新增第DefaultTraceListener二個會導致偵錯工具輸出視窗中的重複訊息, 和判斷提示的重複訊息方塊。Explicitly adding a second DefaultTraceListener causes duplicate messages in the debugger output window and duplicate message boxes for asserts.

根據預設, WriteWriteLine方法會將訊息發出至 Win32 OutputDebugString函式和Debugger.Log方法。By default, the Write and WriteLine methods emit the message to the Win32 OutputDebugString function and to the Debugger.Log method.

根據預設, WriteLine方法會在應用程式以使用者介面模式執行時顯示訊息方塊;它也會Fail使用發出訊息。The Fail method, by default, displays a message box when the application is running in a user interface mode; it also emits the message using WriteLine.

注意

Assert DefaultTraceListener和方法呼叫的訊息方塊顯示取決於是否存在。FailThe display of the message box for Assert and Fail method calls depends on the presence of the DefaultTraceListener. DefaultTraceListener如果不Listeners在集合中, 則不會顯示訊息方塊。If the DefaultTraceListener is not in the Listeners collection, the message box is not displayed. System.Diagnostics.Trace.Listeners.Clear() Clear 可以由Listeners clear > 專案、remove > 元素或在屬性 () 上呼叫方法來移除。 < < DefaultTraceListenerThe DefaultTraceListener can be removed by the <clear> element, by the <remove> element, or by calling the Clear method on the Listeners property (System.Diagnostics.Trace.Listeners.Clear()).

您必須啟用追蹤或偵錯工具, 才能使用追蹤接聽程式。You must enable tracing or debugging to use a trace listener. 下列語法是編譯器特有的。The following syntax is compiler specific. 如果您使用C#或 Visual Basic 以外的編譯器, 請參閱編譯器的檔。If you use compilers other than C# or Visual Basic, refer to the documentation for your compiler.

  • 若要在中C#啟用偵錯工具/d:DEBUG , 請在編譯器代碼時將旗標新增至編譯器命令列#define DEBUG , 或新增至檔案頂端。To enable debugging in C#, add the /d:DEBUG flag to the compiler command line when you compile your code, or add #define DEBUG to the top of your file. 在 Visual Basic 中, 將/d:DEBUG=True旗標新增至編譯器命令列。In Visual Basic, add the /d:DEBUG=True flag to the compiler command line.

  • 若要在中C#啟用追蹤, /d:TRACE請在編譯器代碼時將旗標新增至編譯器命令列, #define TRACE或新增至檔案頂端。To enable tracing in C#, add the /d:TRACE flag to the compiler command line when you compile your code, or add #define TRACE to the top of your file. 在 Visual Basic 中, 將/d:TRACE=True旗標新增至編譯器命令列。In Visual Basic, add the /d:TRACE=True flag to the compiler command line.

若要新增追蹤接聽程式, 請編輯對應至您應用程式名稱的設定檔。To add a trace listener, edit the configuration file that corresponds to the name of your application. 在此檔案中, 您可以加入接聽程式、設定其型別並設定其參數、移除接聽項, 或是清除應用程式先前設定的所有接聽項。Within this file, you can add a listener, set its type and set its parameters, remove a listener, or clear all the listeners previously set by the application. 設定檔的格式應該與下列範例類似:The configuration file should be formatted similar to the following example:

<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() DefaultTraceListener() DefaultTraceListener()

DefaultTraceListener 類別的新執行個體初始化 (將此執行個體的 Name 屬性值設為 "Default")。Initializes a new instance of the DefaultTraceListener class with "Default" as its Name property value.

屬性

AssertUiEnabled AssertUiEnabled AssertUiEnabled AssertUiEnabled

取得或設定值,表示應用程式是否正在使用者介面模式下執行。Gets or sets a value indicating whether the application is running in user-interface mode.

Attributes Attributes Attributes Attributes

取得在應用程式組態檔中定義的自訂追蹤接聽程式屬性。Gets the custom trace listener attributes defined in the application configuration file.

(Inherited from TraceListener)
Filter Filter Filter Filter

取得或設定追蹤接聽程式的追蹤篩選。Gets or sets the trace filter for the trace listener.

(Inherited from TraceListener)
IndentLevel IndentLevel IndentLevel IndentLevel

取得或設定縮排層級。Gets or sets the indent level.

(Inherited from TraceListener)
IndentSize IndentSize IndentSize IndentSize

取得或設定縮排的空格數目。Gets or sets the number of spaces in an indent.

(Inherited from TraceListener)
IsThreadSafe IsThreadSafe IsThreadSafe IsThreadSafe

取得值,指出追蹤接聽程式是否為執行緒安全。Gets a value indicating whether the trace listener is thread safe.

(Inherited from TraceListener)
LogFileName LogFileName LogFileName LogFileName

取得或設定要寫入追蹤或偵錯訊息的記錄檔名稱。Gets or sets the name of a log file to write trace or debug messages to.

Name Name Name Name

取得或設定這個 TraceListener 的名稱。Gets or sets a name for this TraceListener.

(Inherited from TraceListener)
NeedIndent NeedIndent NeedIndent NeedIndent

取得或設定值,指出是否要縮排輸出。Gets or sets a value indicating whether to indent the output.

(Inherited from TraceListener)
TraceOutputOptions TraceOutputOptions TraceOutputOptions TraceOutputOptions

取得或設定追蹤輸出選項。Gets or sets the trace output options.

(Inherited from TraceListener)

方法

Close() Close() Close() Close()

當在衍生類別中覆寫時,關閉輸出資料流,使它不再接收追蹤或偵錯輸出。When overridden in a derived class, closes the output stream so it no longer receives tracing or debugging output.

(Inherited from TraceListener)
CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

釋放 TraceListener 所使用的所有資源。Releases all resources used by the TraceListener.

(Inherited from TraceListener)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

釋放 TraceListener 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the TraceListener and optionally releases the managed resources.

(Inherited from TraceListener)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Fail(String) Fail(String) Fail(String) Fail(String)

發出或顯示判斷提示 (Assertion) 總是失敗的訊息和堆疊追蹤。Emits or displays a message and a stack trace for an assertion that always fails.

Fail(String, String) Fail(String, String) Fail(String, String) Fail(String, String)

發出或顯示判斷提示總是失敗的詳細訊息和堆疊追蹤。Emits or displays detailed messages and a stack trace for an assertion that always fails.

Flush() Flush() Flush() Flush()

當在衍生類別中覆寫時,會清除輸出緩衝區。When overridden in a derived class, flushes the output buffer.

(Inherited from TraceListener)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetSupportedAttributes() GetSupportedAttributes() GetSupportedAttributes() GetSupportedAttributes()

取得由追蹤接聽程式支援的自訂屬性。Gets the custom attributes supported by the trace listener.

(Inherited from TraceListener)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object) TraceData(TraceEventCache, String, TraceEventType, Int32, Object) TraceData(TraceEventCache, String, TraceEventType, Int32, Object) TraceData(TraceEventCache, String, TraceEventType, Int32, Object)

寫入追蹤資訊,資料物件,及事件資訊至特定接聽程式的輸出。Writes trace information, a data object and event information to the listener specific output.

(Inherited from TraceListener)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object[]) TraceData(TraceEventCache, String, TraceEventType, Int32, Object[]) TraceData(TraceEventCache, String, TraceEventType, Int32, Object[]) TraceData(TraceEventCache, String, TraceEventType, Int32, Object[])

寫入追蹤資訊,資料物件的陣列,及事件資訊至特定接聽程式的輸出。Writes trace information, an array of data objects and event information to the listener specific output.

(Inherited from TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32) TraceEvent(TraceEventCache, String, TraceEventType, Int32) TraceEvent(TraceEventCache, String, TraceEventType, Int32) TraceEvent(TraceEventCache, String, TraceEventType, Int32)

寫入追蹤和事件資訊至特定接聽程式的輸出。Writes trace and event information to the listener specific output.

(Inherited from TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32, String) TraceEvent(TraceEventCache, String, TraceEventType, Int32, String) TraceEvent(TraceEventCache, String, TraceEventType, Int32, String) TraceEvent(TraceEventCache, String, TraceEventType, Int32, String)

寫入追蹤資訊,訊息,及事件資訊至特定接聽程式的輸出。Writes trace information, a message, and event information to the listener specific output.

(Inherited from TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object[]) TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object[]) TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object[]) TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object[])

寫入追蹤資訊,格式化的物件陣列,及事件資訊至特定接聽程式的輸出。Writes trace information, a formatted array of objects and event information to the listener specific output.

(Inherited from TraceListener)
TraceTransfer(TraceEventCache, String, Int32, String, Guid) TraceTransfer(TraceEventCache, String, Int32, String, Guid) TraceTransfer(TraceEventCache, String, Int32, String, Guid) TraceTransfer(TraceEventCache, String, Int32, String, Guid)

寫入追蹤資訊、訊息、相關活動識別,及事件資訊至特定接聽程式的輸出。Writes trace information, a message, a related activity identity and event information to the listener specific output.

(Inherited from TraceListener)
Write(Object) Write(Object) Write(Object) Write(Object)

將物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽項。Writes the value of the object's ToString() method to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
Write(Object, String) Write(Object, String) Write(Object, String) Write(Object, String)

將分類名稱和物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽項。Writes a category name and the value of the object's ToString() method to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
Write(String) Write(String) Write(String) Write(String)

將輸出寫入 OutputDebugString 函示和 Log(Int32, String, String) 方法。Writes the output to the OutputDebugString function and to the Log(Int32, String, String) method.

Write(String, String) Write(String, String) Write(String, String) Write(String, String)

將分類名稱和訊息寫入當您實作 TraceListener 類別時所建立的接聽項。Writes a category name and a message to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
WriteIndent() WriteIndent() WriteIndent() WriteIndent()

將縮排寫入當您實作這個類別時所建立的接聽項,並且將 NeedIndent 屬性重設為 falseWrites the indent to the listener you create when you implement this class, and resets the NeedIndent property to false.

(Inherited from TraceListener)
WriteLine(Object) WriteLine(Object) WriteLine(Object) WriteLine(Object)

將物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽項,後面跟隨著行結束字元。Writes the value of the object's ToString() method to the listener you create when you implement the TraceListener class, followed by a line terminator.

(Inherited from TraceListener)
WriteLine(Object, String) WriteLine(Object, String) WriteLine(Object, String) WriteLine(Object, String)

將分類名稱和物件的 ToString() 方法的值寫入當您實作 TraceListener 類別時所建立的接聽項,後面跟隨著行結束字元。Writes a category name and the value of the object's ToString() method to the listener you create when you implement the TraceListener class, followed by a line terminator.

(Inherited from TraceListener)
WriteLine(String) WriteLine(String) WriteLine(String) WriteLine(String)

將輸出寫入 OutputDebugString 函式和 Log(Int32, String, String) 方法,後面接著歸位字元和換行符號 (\r\n)。Writes the output to the OutputDebugString function and to the Log(Int32, String, String) method, followed by a carriage return and line feed (\r\n).

WriteLine(String, String) WriteLine(String, String) WriteLine(String, String) WriteLine(String, String)

將分類名稱和訊息寫入當您實作 TraceListener 類別時所建立的接聽項,後面跟隨著行結束字元。Writes a category name and a message to the listener you create when you implement the TraceListener class, followed by a line terminator.

(Inherited from TraceListener)

適用於

執行緒安全性

這個類別是安全線程。This class is thread safe.

另請參閱