共用方式為


TraceSource 類別

定義

提供一組方法和屬性,可以讓應用程式追蹤程式碼的執行情形,並讓追蹤訊息與其來源產生關聯。

public ref class TraceSource
public class TraceSource
type TraceSource = class
Public Class TraceSource
繼承
TraceSource

範例

下列程式代碼範例示範 如何使用 TraceSource 類別將追蹤轉送至接聽程式。 此範例也會示範參數和篩選使用方式。

/////////////////////////////////////////////////////////////////////////////////
//
// NAME     TraceSource2.cpp : main project file
//
/////////////////////////////////////////////////////////////////////////////////



// The following configuration file can be used with this sample.
// When using a configuration file #define ConfigFile.
//            <source name="TraceTest" switchName="SourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
//                    <add name="console" type="System.Diagnostics.ConsoleTraceListener" initializeData="false" />
//                    <remove name ="Default" />
//            <!-- You can set the level at which tracing is to occur -->
//            <add name="SourceSwitch" value="Warning" />
//            <!-- You can turn tracing off -->
//            <!--add name="SourceSwitch" value="Off" -->
//        <trace autoflush="true" indentsize="4"></trace>

#define TRACE
//#define ConfigFile

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Diagnostics;
using namespace System::Reflection;
using namespace System::IO;
using namespace System::Security::Permissions;

void DisplayProperties(TraceSource^ ts);  // Forward Declaration


int main()
{
    TraceSource^ ts = gcnew TraceSource("TraceTest");

    try
        {
        // Initialize trace switches.
#if(!ConfigFile)
        SourceSwitch^ sourceSwitch = gcnew SourceSwitch("SourceSwitch", "Verbose");
        ts->Switch = sourceSwitch;
        int idxConsole = ts->Listeners->Add(gcnew System::Diagnostics::ConsoleTraceListener());
        ts->Listeners[idxConsole]->Name = "console";
#endif
        DisplayProperties(ts);
        ts->Listeners["console"]->TraceOutputOptions |= TraceOptions::Callstack;
        ts->TraceEvent(TraceEventType::Warning, 1);
        ts->Listeners["console"]->TraceOutputOptions = TraceOptions::DateTime;
        // Issue file not found message as a warning.
        ts->TraceEvent(TraceEventType::Warning, 2, "File Test not found");
        // Issue file not found message as a verbose event using a formatted string.
        ts->TraceEvent(TraceEventType::Verbose, 3, "File {0} not found.", "test");
        // Issue file not found message as information.
        ts->TraceInformation("File {0} not found.", "test");
        ts->Listeners["console"]->TraceOutputOptions |= TraceOptions::LogicalOperationStack;
        // Issue file not found message as an error event.
        ts->TraceEvent(TraceEventType::Error, 4, "File {0} not found.", "test");

        // Test the filter on the ConsoleTraceListener.
        ts->Listeners["console"]->Filter = gcnew SourceFilter("No match");
        ts->TraceData(TraceEventType::Error, 5,
            "SourceFilter should reject this message for the console trace listener.");
        ts->Listeners["console"]->Filter = gcnew SourceFilter("TraceTest");
        ts->TraceData(TraceEventType::Error, 6,
            "SourceFilter should let this message through on the console trace listener.");
        ts->Listeners["console"]->Filter = nullptr;

        // Use the TraceData method. 
        ts->TraceData(TraceEventType::Warning, 7, gcnew array<Object^>{ "Message 1", "Message 2" });

        // Activity tests.
        ts->TraceEvent(TraceEventType::Start, 9, "Will not appear until the switch is changed.");
        ts->Switch->Level = SourceLevels::ActivityTracing | SourceLevels::Critical;
        ts->TraceEvent(TraceEventType::Suspend, 10, "Switch includes ActivityTracing, this should appear");
        ts->TraceEvent(TraceEventType::Critical, 11, "Switch includes Critical, this should appear");
        ts->Flush();
        ts->Close();
        Console::WriteLine("Press enter key to exit.");
        Console::Read();
        }
    catch (Exception ^e)
        {
         // Catch any unexpected exception.
         Console::WriteLine("Unexpected exception: " + e->ToString());
         Console::Read();
        }
}


void DisplayProperties(TraceSource^ ts)
{
    Console::WriteLine("TraceSource name = " + ts->Name);
//    Console::WriteLine("TraceSource switch level = " + ts->Switch->Level);         // error C3063: operator '+': all operands must have the same enumeration type
    Console::WriteLine("TraceSource switch level = {0}", ts->Switch->Level);         //  SUCCESS:  does compile.  Weird
    Console::WriteLine("TraceSource Attributes Count " + ts->Attributes->Count);     //  SUCCESS:  also compiles.  Really weird
    Console::WriteLine("TraceSource Attributes Count = {0}", ts->Attributes->Count); //  SUCCESS:  okay, I give up.  Somebody call me a cab.

    Console::WriteLine("TraceSource switch = " + ts->Switch->DisplayName);
    array<SwitchAttribute^>^ switches = SwitchAttribute::GetAll(TraceSource::typeid->Assembly);

    for (int i = 0; i < switches->Length; i++)
        { 
        Console::WriteLine("Switch name = " + switches[i]->SwitchName);
        Console::WriteLine("Switch type = " + switches[i]->SwitchType);
        }

#if(ConfigFile)
            // Get the custom attributes for the TraceSource.
            Console::WriteLine("Number of custom trace source attributes = "
                + ts.Attributes.Count);
            foreach (DictionaryEntry de in ts.Attributes)
                Console::WriteLine("Custom trace source attribute = "
                    + de.Key + "  " + de.Value);
            // Get the custom attributes for the trace source switch.
            foreach (DictionaryEntry de in ts.Switch.Attributes)
                Console::WriteLine("Custom switch attribute = "
                    + de.Key + "  " + de.Value);
#endif
       Console::WriteLine("Number of listeners = " + ts->Listeners->Count);
       for each (TraceListener ^ traceListener in ts->Listeners)
           {
           Console::Write("TraceListener: " + traceListener->Name + "\t");
           // The following output can be used to update the configuration file.
           Console::WriteLine("AssemblyQualifiedName = " +
               (traceListener->GetType()->AssemblyQualifiedName));
           }
}
// The following configuration file can be used with this sample.
// When using a configuration file #define ConfigFile.
//            <source name="TraceTest" switchName="SourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
//                    <add name="console" type="System.Diagnostics.ConsoleTraceListener" initializeData="false" />
//                    <remove name ="Default" />
//            <!-- You can set the level at which tracing is to occur -->
//            <add name="SourceSwitch" value="Warning" />
//            <!-- You can turn tracing off -->
//            <!--add name="SourceSwitch" value="Off" -->
//        <trace autoflush="true" indentsize="4"></trace>
#define TRACE
//#define ConfigFile

using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Security.Permissions;

namespace Testing
{
    class TraceTest
    {
        // Initialize the trace source.
        static TraceSource ts = new TraceSource("TraceTest");
        [SwitchAttribute("SourceSwitch", typeof(SourceSwitch))]
        static void Main()
        {
            try
            {
                // Initialize trace switches.
#if(!ConfigFile)
                SourceSwitch sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
                ts.Switch = sourceSwitch;
                int idxConsole = ts.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
                ts.Listeners[idxConsole].Name = "console";
#endif
                DisplayProperties(ts);
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.Callstack;
                ts.TraceEvent(TraceEventType.Warning, 1);
                ts.Listeners["console"].TraceOutputOptions = TraceOptions.DateTime;
                // Issue file not found message as a warning.
                ts.TraceEvent(TraceEventType.Warning, 2, "File Test not found");
                // Issue file not found message as a verbose event using a formatted string.
                ts.TraceEvent(TraceEventType.Verbose, 3, "File {0} not found.", "test");
                // Issue file not found message as information.
                ts.TraceInformation("File {0} not found.", "test");
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.LogicalOperationStack;
                // Issue file not found message as an error event.
                ts.TraceEvent(TraceEventType.Error, 4, "File {0} not found.", "test");
                // Test the filter on the ConsoleTraceListener.
                ts.Listeners["console"].Filter = new SourceFilter("No match");
                ts.TraceData(TraceEventType.Error, 5,
                    "SourceFilter should reject this message for the console trace listener.");
                ts.Listeners["console"].Filter = new SourceFilter("TraceTest");
                ts.TraceData(TraceEventType.Error, 6,
                    "SourceFilter should let this message through on the console trace listener.");
                ts.Listeners["console"].Filter = null;
                // Use the TraceData method.
                ts.TraceData(TraceEventType.Warning, 7, new object());
                ts.TraceData(TraceEventType.Warning, 8, new object[] { "Message 1", "Message 2" });
                // Activity tests.
                ts.TraceEvent(TraceEventType.Start, 9, "Will not appear until the switch is changed.");
                ts.Switch.Level = SourceLevels.ActivityTracing | SourceLevels.Critical;
                ts.TraceEvent(TraceEventType.Suspend, 10, "Switch includes ActivityTracing, this should appear");
                ts.TraceEvent(TraceEventType.Critical, 11, "Switch includes Critical, this should appear");
                ts.Flush();
                ts.Close();
                Console.WriteLine("Press any key to exit.");
                Console.Read();
            }
            catch (Exception e)
            {
                // Catch any unexpected exception.
                Console.WriteLine("Unexpected exception: " + e.ToString());
                Console.Read();
            }
        }
        public static void DisplayProperties(TraceSource ts)
        {
            Console.WriteLine("TraceSource name = " + ts.Name);
            Console.WriteLine("TraceSource switch level = " + ts.Switch.Level);
            Console.WriteLine("TraceSource switch = " + ts.Switch.DisplayName);
            SwitchAttribute[] switches = SwitchAttribute.GetAll(typeof(TraceTest).Assembly);
            for (int i = 0; i < switches.Length; i++)
            {
                Console.WriteLine("Switch name = " + switches[i].SwitchName);
                Console.WriteLine("Switch type = " + switches[i].SwitchType);
            }
#if(ConfigFile)
            // Get the custom attributes for the TraceSource.
            Console.WriteLine("Number of custom trace source attributes = "
                + ts.Attributes.Count);
            foreach (DictionaryEntry de in ts.Attributes)
                Console.WriteLine("Custom trace source attribute = "
                    + de.Key + "  " + de.Value);
            // Get the custom attributes for the trace source switch.
            foreach (DictionaryEntry de in ts.Switch.Attributes)
                Console.WriteLine("Custom switch attribute = "
                    + de.Key + "  " + de.Value);
#endif
            Console.WriteLine("Number of listeners = " + ts.Listeners.Count);
            foreach (TraceListener traceListener in ts.Listeners)
            {
                Console.Write("TraceListener: " + traceListener.Name + "\t");
                // The following output can be used to update the configuration file.
                Console.WriteLine("AssemblyQualifiedName = " +
                    (traceListener.GetType().AssemblyQualifiedName));
            }
        }
    }
}
' The following configuration file can be used with this sample.
' When using a configuration file #define ConfigFile.
'            <source name="TraceTest" switchName="SourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
'                    <add name="console" type="System.Diagnostics.ConsoleTraceListener" initializeData="false" />
'                    <remove name ="Default" />
'            <!-- You can set the level at which tracing is to occur -->
'            <add name="SourceSwitch" value="Warning" />
'            <!-- You can turn tracing off -->
'            <!--add name="SourceSwitch" value="Off" -->
'        <trace autoflush="true" indentsize="4"></trace>
#Const TRACE = True
'#Const ConfigFile = True

Imports System.Collections
Imports System.Diagnostics
Imports System.Reflection
Imports System.IO
Imports System.Security.Permissions



Class TraceTest
    ' Initialize the trace source.
    Private Shared ts As New TraceSource("TraceTest")
    <SwitchAttribute("SourceSwitch", GetType(SourceSwitch))> _
    Shared Sub Main()
        Try
            ' Initialize trace switches.
#If (ConfigFile = False) Then
            Dim sourceSwitch As New SourceSwitch("SourceSwitch", "Verbose")
            ts.Switch = sourceSwitch
            Dim idxConsole As New Integer()
            idxConsole = ts.Listeners.Add(New System.Diagnostics.ConsoleTraceListener())
            ts.Listeners(idxConsole).Name = "console"
#End If
            DisplayProperties(ts)
            ts.Listeners("console").TraceOutputOptions = ts.Listeners("console").TraceOutputOptions Or TraceOptions.Callstack
            ts.TraceEvent(TraceEventType.Warning, 1)
            ts.Listeners("console").TraceOutputOptions = TraceOptions.DateTime
            ' Issue file not found message as a warning.
            ts.TraceEvent(TraceEventType.Warning, 2, "File Test not found")
            ' Issue file not found message as a verbose event using a formatted string.
            ts.TraceEvent(TraceEventType.Verbose, 3, "File {0} not found.", "test")
            ' Issue file not found message as information.
            ts.TraceInformation("File {0} not found.", "test")
            ts.Listeners("console").TraceOutputOptions = ts.Listeners("console").TraceOutputOptions Or TraceOptions.LogicalOperationStack
            ' Issue file not found message as an error event.
            ts.TraceEvent(TraceEventType.Error, 4, "File {0} not found.", "test")
            ' Test the filter on the ConsoleTraceListener.
            ts.Listeners("console").Filter = New SourceFilter("No match")
            ts.TraceData(TraceEventType.Error, 5, "SourceFilter should reject this message for the console trace listener.")
            ts.Listeners("console").Filter = New SourceFilter("TraceTest")
            ts.TraceData(TraceEventType.Error, 6, "SourceFilter should let this message through on the console trace listener.")
            ts.Listeners("console").Filter = Nothing
            ' Use the TraceData method. 
            ts.TraceData(TraceEventType.Warning, 7, New Object())
            ts.TraceData(TraceEventType.Warning, 8, New Object() {"Message 1", "Message 2"})
            ' Activity tests.
            ts.TraceEvent(TraceEventType.Start, 9, "Will not appear until the switch is changed.")
            ts.Switch.Level = SourceLevels.ActivityTracing Or SourceLevels.Critical
            ts.TraceEvent(TraceEventType.Suspend, 10, "Switch includes ActivityTracing, this should appear")
            ts.TraceEvent(TraceEventType.Critical, 11, "Switch includes Critical, this should appear")
            ts.Flush()
            ts.Close()
            Console.WriteLine("Press any key to exit.")
            Console.Read()
        Catch e As Exception
            ' Catch any unexpected exception.
            Console.WriteLine("Unexpected exception: " + e.ToString())
            Console.Read()
        End Try

    End Sub

    Public Shared Sub DisplayProperties(ByVal ts As TraceSource)
        Console.WriteLine("TraceSource name = " + ts.Name)
        Console.WriteLine("TraceSource switch level = " + ts.Switch.Level.ToString())
        Console.WriteLine("TraceSource switch = " + ts.Switch.DisplayName.ToString())
        Dim switches As SwitchAttribute() = SwitchAttribute.GetAll(GetType(TraceTest).Assembly)
        Dim i As Integer
        For i = 0 To switches.Length - 1
            Console.WriteLine("Switch name = " + switches(i).SwitchName.ToString())
            Console.WriteLine("Switch type = " + switches(i).SwitchType.ToString())
        Next i

#If (ConfigFile) Then
        ' Get the custom attributes for the TraceSource.
        Console.WriteLine("Number of custom trace source attributes = " + ts.Attributes.Count)
        Dim de As DictionaryEntry
        For Each de In ts.Attributes
            Console.WriteLine("Custom trace source attribute = " + de.Key + "  " + de.Value)
        Next de
        ' Get the custom attributes for the trace source switch.
        For Each de In ts.Switch.Attributes
            Console.WriteLine("Custom switch attribute = " + de.Key + "  " + de.Value)
        Next de
#End If
        Console.WriteLine("Number of listeners = " + ts.Listeners.Count.ToString())
        Dim traceListener As TraceListener
        For Each traceListener In ts.Listeners
            Console.Write("TraceListener: " + traceListener.Name + vbTab)
            ' The following output can be used to update the configuration file.
            Console.WriteLine("AssemblyQualifiedName = " + traceListener.GetType().AssemblyQualifiedName)
        Next traceListener

    End Sub
End Class

備註

應用程式會使用 TraceSource 類別產生能夠與應用程式相關聯的追蹤。 TraceSource 提供了追蹤方法,能讓您輕鬆地追蹤事件、追蹤資料和問題資訊追蹤。

在 .NET Framework 應用程式中,追蹤輸出TraceSource可由組態檔設定控制。 組態檔位於具有應用程式可執行檔的資料夾,且具有已新增 .config 擴展名的應用程式名稱。 例如,TraceSourceSample.exe 組態檔的名稱是 TraceSourceSample.exe.config。組態檔可用來指定要傳送追蹤資訊的位置,以及要追蹤的活動層級。 下列範例顯示範例 .NET Framework 應用程式組態檔的內容。

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="TraceTest" switchName="SourceSwitch"   
        switchType="System.Diagnostics.SourceSwitch" >  
        <listeners>  
          <add name="console" />  
          <remove name ="Default" />  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <!-- You can set the level at which tracing is to occur -->  
      <add name="SourceSwitch" value="Warning" />  
        <!-- You can turn tracing off -->  
        <!--add name="SourceSwitch" value="Off" -->  
    </switches>  
    <sharedListeners>  
      <add name="console"   
        type="System.Diagnostics.ConsoleTraceListener"   
        initializeData="false"/>  
    </sharedListeners>  
    <trace autoflush="true" indentsize="4">  
      <listeners>  
        <add name="console" />  
      </listeners>  
    </trace>  
  </system.diagnostics>  
</configuration>  

類別 TraceSource 是由來源的名稱來識別,通常是應用程式的名稱。 來自特定元件的追蹤訊息可以由特定追蹤來源起始,讓來自該元件的所有訊息都能輕鬆識別。

TraceSource 會定義追蹤方法,但實際上不會提供產生及儲存追蹤數據的任何特定機制。 追蹤數據是由追蹤接聽程式所產生,這是可由追蹤來源載入的外掛程式。

注意

在最終處理期間,您不應該呼叫追蹤方法。 這樣做可能會導致 ObjectDisposedException 擲回 。

您可以藉由新增或移除 TraceListener 儲存在 屬性中 TraceSource.Listeners 之集合中的實例,來自定義追蹤輸出的目標。 根據預設,追蹤輸出是使用 類別的 DefaultTraceListener 實例來產生。

上述 .NET Framework 應用程式組態檔範例示範移除 DefaultTraceListener 並新增 ,ConsoleTraceListener以產生追蹤來源的追蹤輸出。 如需詳細資訊,請參閱 <接聽> 程式和 <sharedListeners>

注意

如果追蹤接聽程式所使用的資源無法使用,將追蹤接聽程式新增至 Listeners 集合可能會導致擲回例外狀況。 條件和擲回的例外狀況取決於追蹤接聽程式,而且無法在此主題中列舉。 在區塊中try/catch對方法進行呼叫TraceSource,以偵測及處理來自追蹤接聽程式的任何例外狀況可能很有用。

類別 SourceSwitch 提供動態控制追蹤輸出的方法。 針對 .NET Framework 應用程式,上述組態檔範例示範如何從追蹤來源關閉追蹤,並控制追蹤發生的層級。 您可以修改來源參數的值,而不需重新編譯應用程式。 如需使用組態檔設定交換器的資訊,請參閱Switch如何:Create、初始化和設定追蹤參數

注意

如果您在應用程式執行時修改組態檔,則必須停止並重新啟動應用程式,或 Refresh 必須在新的設定生效之前呼叫 方法。

列舉 TraceEventType 可用來定義追蹤訊息的事件類型。 追蹤篩選條件會使用 TraceEventType 來判斷追蹤接聽程式是否應該產生追蹤訊息。

追蹤接聽程式可以選擇性地透過追蹤篩選條件進行額外的篩選。 如果追蹤接聽程式具有相關聯的篩選,接聽程式會呼叫 ShouldTrace 該篩選上的方法,以判斷是否要產生追蹤資訊。

追蹤接聽程式會使用類別屬性IndentIndentSizeAutoFlush 的值Trace來格式化追蹤輸出。 在 .NET Framework 應用程式中,您可以使用組態檔屬性來設定IndentIndentSizeAutoFlush 屬性。 下列範例會將 AutoFlush 屬性設定為 false ,並將 IndentSize 屬性設定為 3。

<configuration>  
  <system.diagnostics>  
    <trace autoflush="false" indentsize="3" />  
  </system.diagnostics>  
</configuration>  

建構函式

TraceSource(String)

使用指定的來源名稱,初始化 TraceSource 類別的新執行個體。

TraceSource(String, SourceLevels)

使用指定的來源名稱,以及要開始進行追蹤的層級,初始化 TraceSource 類別的新執行個體。

屬性

Attributes

取得在應用程式組態檔中定義的自訂參數屬性。

DefaultLevel

取得建構函式中指派的預設層級。

Listeners

取得追蹤來源的追蹤接聽程式集合。

Name

取得追蹤來源的名稱。

Switch

取得或設定來源參數值。

方法

Close()

關閉追蹤接聽程式集合中的所有追蹤接聽程式。

Equals(Object)

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

(繼承來源 Object)
Flush()

清除追蹤接聽程式集合中的所有追蹤接聽程式。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetSupportedAttributes()

取得由追蹤來源所支援的自訂屬性。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

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

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

使用指定的事件類型、事件識別項和追蹤資料,將追蹤資料寫入Listeners 集合中的追蹤接聽程式。

TraceData(TraceEventType, Int32, Object[])

使用指定的事件類型、事件識別項和追蹤資料,將追蹤資料陣列寫入 Listeners 集合中的追蹤接聽程式。

TraceEvent(TraceEventType, Int32)

使用指定的事件類型和事件識別項,將追蹤事件訊息寫入 Listeners 集合中的追蹤接聽程式。

TraceEvent(TraceEventType, Int32, String)

使用指定的事件類型、事件識別項和訊息,將追蹤事件訊息寫入 Listeners 集合中的追蹤接聽程式。

TraceEvent(TraceEventType, Int32, String, Object[])

使用指定的事件類型、事件識別項和引數陣列與格式,將追蹤事件寫入 Listeners 集合中的追蹤接聽程式。

TraceInformation(String)

使用指定的訊息,將告知性訊息寫入 Listeners 集合中的追蹤接聽程式。

TraceInformation(String, Object[])

使用指定的物件陣列和格式化資訊,將告知性訊息寫入 Listeners 集合中的追蹤接聽程式。

TraceTransfer(Int32, String, Guid)

使用指定的數值識別項、訊息和相關的活動識別項,將追蹤傳輸訊息寫入至 Listeners 集合中的追蹤接聽程式。

事件

Initializing

發生於需要初始化 時 TraceSource

適用於

執行緒安全性

此型別具備執行緒安全。

另請參閱