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 は、トレース メソッドを定義しますが、実際にトレース データを生成して格納する、特定のメカニズムは提供されません。 トレース データはトレース リスナーによって生成されます。トレース リスナーは、トレース ソースによって読み込むことができるプラグインです。

Note

ファイナライゼーション処理中にトレース メソッドを呼び出すべきではありません。 ObjectDisposedException がスローされる結果になります。

TraceListener インスタンスが格納されているコレクション TraceSource.Listeners プロパティに追加または削除することによって、トレース出力のターゲットをカスタマイズすることができます。 既定では、DefaultTraceListener クラスのインスタンスを使用して、トレース出力が生成されます。

前.NET Frameworkアプリ構成ファイルの例では、 を削除DefaultTraceListenerし、 を追加ConsoleTraceListenerしてトレース ソースのトレース出力を生成する方法を示します。 詳細については、「リスナー>と sharedListeners」を参照してください<><

Note

Listeners コレクションにトレース リスナーを追加することで、トレース リスナーによって使用されるリソースが利用できない場合、トレース中に例外を発生させることになります。 条件とスローされる例外は、トレース リスナーに依存し、このトピックで列挙することはできません。 トレース リスナーから例外を検出し、処理するために、TraceSource メソッドの呼び出しをtry/catchブロックに配置することができます。

SourceSwitchクラスには、トレース出力を動的に制御するための手段が用意されています。 .NET Framework アプリの場合、前の構成ファイルの例では、トレース ソースからトレースをオフにし、トレースが発生するレベルを制御する方法を示しています。 アプリケーションを再コンパイルしなくてもソース スイッチの値を変更できます。 スイッチを設定する構成ファイルの使用方法の詳細については、Switchスイッチおよび方法: トレーススイッチを作成、初期化、および構成するを参照してください。

Note

アプリケーションの実行中に構成ファイルを変更する場合、アプリケーションを停止して再起動するか、新しい設定を有効にするために、Refresh メソッドを呼び出す必要があります。

TraceEventType列挙体は、トレースメッセージのイベントの種類を定義するために使用されます。 トレース フィルターを使用して、TraceEventType をトレース リスナーがトレース メッセージを生成する必要があるかどうかを判断します。

トレース リスナーは、必要に応じて、トレース フィルターを使用してフィルター処理する追加のレイヤーを持つことができます。 トレース リスナーに関連付けられたフィルターがある場合、リスナーはそのフィルターで メソッドを ShouldTrace 呼び出して、トレース情報を生成するかどうかを判断します。

トレース リスナーは、クラス プロパティ Indent、、IndentSizeおよび AutoFlush の値をTrace使用して、トレース出力の書式設定を行います。 .NET Framework アプリでは、構成ファイル属性を使用して、、IndentSize、および AutoFlush プロパティをIndent設定できます。 次の例では、 プロパティを AutoFlushfalse 設定し、 プロパティを 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 に発生します。

適用対象

スレッド セーフ

この型はスレッド セーフです。

こちらもご覧ください