TraceSourceとは? わかりやすく解説

TraceSource クラス

メモ : このクラスは、.NET Framework version 2.0 で新しく追加されたものです。

アプリケーションでコードの実行をトレースしてトレース メッセージをソースに関連付けることができるようにする、メソッドおよびプロパティのセットを提供します。

名前空間: System.Diagnostics
アセンブリ: System (system.dll 内)
構文構文

public class TraceSource
public ref class TraceSource
public class TraceSource
public class TraceSource
解説解説

TraceSource クラスをアプリケーションで使用すると、アプリケーションに関連付けることができるトレースを生成できます。TraceSource は、イベントのトレース、データのトレース、および情報トレースの発行を簡単に実行できるトレース方法を提供します。TraceSource からのトレース出力は、構成ファイル設定によって制御できます。構成ファイルは、アプリケーション実行ファイルと同じフォルダに格納されており、ファイル名はアプリケーションの名前および .config ファイル名拡張子で構成されています。たとえば、TraceSourceSample.exe の構成ファイルの名前は、TraceSourceSample.exe.config です。構成ファイルは、トレース情報の送信先や、トレース対象とする動作のレベルを決定するために使用できます。サンプル アプリケーション構成ファイルの内容を次の例に示します。

<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 はトレース方法を定義しますが、トレース データを生成および格納するための独自の方法を実際に提供するわけではありません。トレース データはトレース リスナによって生成されます。トレース リスナは、トレース ソースによって読み込まれるプラグインです。

トレース出力対象をカスタマイズするには、TraceSource.Listeners プロパティに格納されたコレクションで TraceListener インスタンスの追加や削除を行います。既定では、トレース出力は DefaultTraceListener クラスのインスタンスを使用して生成されます。前述の構成ファイルの例では、DefaultTraceListener を削除し、ConsoleTraceListener を追加して、トレース ソースのトレース出力を生成しています。詳細については、<source> の <listeners> 要素、<sharedListeners> 要素 の各トピックを参照してください。

SourceSwitch クラスは、トレース出力を動的に制御する手段を提供します。上記の構成ファイルの例では、トレース ソースからのトレースをオフにして、トレースが発生するレベルを制御しています。ソース スイッチの値は、アプリケーションを再コンパイルせずに変更できます。構成ファイルを使ってスイッチを設定する方法の詳細については、Switch のトピックおよび「方法 : トレース スイッチを設定する」を参照してください。

メモメモ

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

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

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

トレース リスナは、Trace クラスのプロパティ (Indent、IndentSize、および AutoFlush) の値を使用して、トレース出力を書式設定します。Indent、IndentSize、および AutoFlush の各プロパティを設定する場合は、構成ファイルの属性を使用できます。AutoFlush プロパティを false に設定し、IndentSize プロパティを 3 に設定する例を次に示します。

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

TraceSource クラスを使用してトレースをリスナに転送する方法を次のコード例に示します。この例では、スイッチとフィルタの使用方法も示されています。

' The following configuration file can be used with this sample.
' When using a configuration file #define ConfigFile.
'<configuration>
'    <system.diagnostics>
'        <sources>
'            <source name="TraceTest" switchName="SourceSwitch"
 switchType="System.Diagnostics.SourceSwitch" >
'                <listeners>
'                    <add name="console" type="System.Diagnostics.ConsoleTraceListener"
 initializeData="false" />
'                    <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>
'        <trace autoflush="true" indentsize="4"></trace>
'    </system.diagnostics>
'</configuration>
#Const TRACE = True
#Const ConfigFile = True

Imports System
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")
#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")
            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 'Main
    
    Public Shared Sub DisplayProperties(ByVal
 ts As TraceSource) 
        Console.WriteLine("SourceSwitch 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([Assembly].GetExecutingAssembly())
        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)
        ' 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
        #EndIf
        Console.WriteLine("Number of listeners = "
 + ts.Listeners.Count)
        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 'DisplayProperties
End Class 'TraceTest 

// The following configuration file can be used with this sample.
// When using a configuration file #define ConfigFile.
//<configuration>
//    <system.diagnostics>
//        <sources>
//            <source name="TraceTest" switchName="SourceSwitch"
 switchType="System.Diagnostics.SourceSwitch" >
//                <listeners>
//                    <add name="console" type="System.Diagnostics.ConsoleTraceListener"
 initializeData="false" />
//                    <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>
//        <trace autoflush="true" indentsize="4"></trace>
//    </system.diagnostics>
//</configuration>
#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");
#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");
                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("SourceSwitch name = " + ts.Name);
            Console.WriteLine("TraceSource switch level =
 " + ts.Switch.Level);
            Console.WriteLine("TraceSource switch = "
 + ts.Switch.DisplayName);
            SwitchAttribute[] switches = SwitchAttribute.GetAll(Assembly.GetExecutingAssembly());
            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));
            }
        }
    }
}
継承階層継承階層
System.Object
  System.Diagnostics.TraceSource
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

TraceSource コンストラクタ (String)

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

指定したソースの名前を使用して、TraceSource クラスの新しいインスタンスを初期化します。

名前空間: System.Diagnostics
アセンブリ: System (system.dll 内)
構文構文

public TraceSource (
    string name
)
public:
TraceSource (
    String^ name
)
public TraceSource (
    String name
)
public function TraceSource (
    name : String
)

パラメータ

name

ソースの名前 (通常はアプリケーションの名前)。

例外例外
例外の種類条件

ArgumentNullException

name が null 参照 (Visual Basic では Nothing) です。

ArgumentException

name が空の文字列 ("") です。

解説解説
使用例使用例

TraceSource コンストラクタを使用して新しい TraceSource オブジェクトを使用する方法を次のコード例に示します。このコード例は、TraceSource クラスのトピックで取り上げているコード例の一部分です。

' Initialize the trace source.
Private Shared ts As New
 TraceSource("TraceTest") 
// Initialize the trace source.
static TraceSource ts = new TraceSource("TraceTest");
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

TraceSource コンストラクタ (String, SourceLevels)

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

ソースの指定された名前、およびトレースが発生する既定のソース レベルを使用して、TraceSource クラスの新しいインスタンスを初期化します。

名前空間: System.Diagnostics
アセンブリ: System (system.dll 内)
構文構文

Public Sub New ( _
    name As String, _
    defaultLevel As SourceLevels _
)
Dim name As String
Dim defaultLevel As SourceLevels

Dim instance As New TraceSource(name,
 defaultLevel)
public TraceSource (
    string name,
    SourceLevels defaultLevel
)
public:
TraceSource (
    String^ name, 
    SourceLevels defaultLevel
)
public TraceSource (
    String name, 
    SourceLevels defaultLevel
)
public function TraceSource (
    name : String, 
    defaultLevel : SourceLevels
)

パラメータ

name

ソースの名前 (通常はアプリケーションの名前)。

defaultLevel

トレースする既定のソース レベルを指定する SourceLevels 値のビットごとの組み合わせ。

例外例外
例外の種類条件

ArgumentNullException

name が null 参照 (Visual Basic では Nothing) です。

ArgumentException

name が空の文字列 ("") です。

解説解説
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

TraceSource コンストラクタ


TraceSource プロパティ


TraceSource メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Close トレース リスナ コレクション内のすべてのトレース リスナを閉じます。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド Flush トレース リスナ コレクション内のすべてのトレース リスナをフラッシュします。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String を返します。 ( Object から継承されます。)
パブリック メソッド TraceData オーバーロードされます。 トレース データを Listeners コレクション内のトレース リスナに書き込みます。
パブリック メソッド TraceEvent オーバーロードされます。 トレース イベント メッセージを Listeners コレクションのトレース リスナに書き込みます。
パブリック メソッド TraceInformation オーバーロードされます。 情報メッセージを Listeners コレクションのトレース リスナに書き込みます。
パブリック メソッド TraceTransfer 指定された数値識別子、メッセージ、および関連する動作識別子を使用して、トレース転送メッセージを Listeners コレクションのトレース リスナに書き込みます。
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

TraceSource クラス
System.Diagnostics 名前空間

その他の技術情報

トレースおよびデバッグ設定のスキーマ

TraceSource メンバ

アプリケーションでコードの実行をトレースしてトレース メッセージをソースに関連付けることができるようにする、メソッドおよびプロパティのセットを提供します。

TraceSource データ型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド も参照)
  名前 説明
パブリック メソッド Close トレース リスナ コレクション内のすべてのトレース リスナを閉じます。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド Flush トレース リスナ コレクション内のすべてのトレース リスナをフラッシュします。
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String を返します。 (Object から継承されます。)
パブリック メソッド TraceData オーバーロードされます。 トレース データを Listeners コレクション内のトレース リスナに書き込みます。
パブリック メソッド TraceEvent オーバーロードされます。 トレース イベント メッセージを Listeners コレクションのトレース リスナに書き込みます。
パブリック メソッド TraceInformation オーバーロードされます。 情報メッセージを Listeners コレクションのトレース リスナに書き込みます。
パブリック メソッド TraceTransfer 指定された数値識別子、メッセージ、および関連する動作識別子を使用して、トレース転送メッセージを Listeners コレクションのトレース リスナに書き込みます。
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

TraceSource クラス
System.Diagnostics 名前空間

その他の技術情報

トレースおよびデバッグ設定のスキーマ



英和和英テキスト翻訳

英語⇒日本語日本語⇒英語

辞書ショートカット

すべての辞書の索引

「TraceSource」の関連用語

TraceSourceのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



TraceSourceのページの著作権

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.

©2026 GRAS Group, Inc.RSS