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) の値を使用してトレース出力書式設定ます。IndentIndentSize、および 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) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「TraceSource クラス」の関連用語

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

   

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



TraceSource クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

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

©2025 GRAS Group, Inc.RSS