Поделиться через


Практическое руководство. Создание и инициализация источников трассировки

Замечание

Эта статья связана с .NET Framework. Он не применяется к более новым реализациям .NET, включая .NET 6 и более поздние версии.

Класс TraceSource используется приложениями для создания трассировок, которые могут быть связаны с приложением. TraceSource предоставляет методы трассировки, позволяющие легко отслеживать события, данные трассировки и создавать информационные трассировки. Выходные данные TraceSource трассировки можно создавать и инициализировать как с использованием файлов конфигурации, так и без них. В этом разделе приведены инструкции по обоим параметрам. Однако рекомендуется использовать файлы конфигурации для упрощения перенастройки трассировок, созданных источниками трассировки во время выполнения.

Создание и инициализация источника трассировки с помощью файла конфигурации

  1. Создайте проект консольного приложения Visual Studio (.NET Framework) и замените предоставленный код следующим кодом. Этот код регистрирует ошибки и предупреждения и выводит некоторые из них в консоль, а некоторые из них — в файл myListener, созданный записями в файле конфигурации.

    using System;
    using System.Diagnostics;
    
    class TraceTest
    {
    
        private static TraceSource mySource =
                new TraceSource("TraceSourceApp");
            static void Main(string[] args)
            {
               // Issue an error and a warning message. Only the error message
                // should be logged.
                Activity1();
    
                // Save the original settings from the configuration file.
                EventTypeFilter configFilter =
                    (EventTypeFilter)mySource.Listeners["console"].Filter;
    
                // Create a new event type filter that ensures
                // warning messages will be written.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Warning);
    
                // Allow the trace source to send messages to listeners
                // for all event types. This statement will override
                // any settings in the configuration file.
                // If you do not change the switch level, the event filter
                // changes have no effect.
                mySource.Switch.Level = SourceLevels.All;
    
                // Issue a warning and a critical message. Both should be logged.
                Activity2();
    
                // Restore the original filter settings.
                mySource.Listeners["console"].Filter = configFilter;
                Activity3();
                mySource.Close();
                return;
            }
            static void Activity1()
            {
                mySource.TraceEvent(TraceEventType.Error, 1,
                    "Error message.");
                mySource.TraceEvent(TraceEventType.Warning, 2,
                    "Warning message.");
            }
            static void Activity2()
            {
                mySource.TraceEvent(TraceEventType.Critical, 3,
                    "Critical message.");
                mySource.TraceEvent(TraceEventType.Warning, 2,
                    "Warning message.");
            }
            static void Activity3()
            {
                mySource.TraceEvent(TraceEventType.Error, 4,
                    "Error message.");
                mySource.TraceInformation("Informational message.");
            }
        }
    
    Imports System.Diagnostics
    
    Class TraceTest
    
        Private Shared mySource As New TraceSource("TraceSourceApp")
    
        Shared Sub Main(ByVal args() As String)
            ' Issue an error and a warning message. Only the error message
            ' should be logged.
            Activity1()
    
            ' Save the original settings from the configuration file.
            Dim configFilter As EventTypeFilter = CType(mySource.Listeners("console").Filter, EventTypeFilter)
    
            ' Create a new event type filter that ensures 
            ' warning messages will be written.
            mySource.Listeners("console").Filter = New EventTypeFilter(SourceLevels.Warning)
    
            ' Allow the trace source to send messages to listeners 
            ' for all event types. This statement will override 
            ' any settings in the configuration file.
            ' If you do not change the switch level, the event filter
            ' changes have no effect.
            mySource.Switch.Level = SourceLevels.All
    
            ' Issue a warning and a critical message. Both should be logged.
            Activity2()
    
            ' Restore the original filter settings.
            mySource.Listeners("console").Filter = configFilter
            Activity3()
            mySource.Close()
            Return
    
        End Sub
    
        Shared Sub Activity1()
            mySource.TraceEvent(TraceEventType.Error, 1, "Error message.")
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.")
    
        End Sub
    
        Shared Sub Activity2()
            mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.")
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.")
    
        End Sub
    
        Shared Sub Activity3()
            mySource.TraceEvent(TraceEventType.Error, 4, "Error message.")
            mySource.TraceInformation("Informational message.")
    
        End Sub
    End Class
    
  2. Добавьте файл конфигурации приложения, если он отсутствует, в проект, чтобы инициализировать источник трассировки, названный TraceSourceApp в примере кода на шаге 1.

  3. Замените содержимое файла конфигурации по умолчанию следующими параметрами, чтобы инициализировать прослушиватель трассировки консоли и прослушиватель трассировки записи текста для источника трассировки, созданного на шаге 1.

    <configuration>
      <system.diagnostics>
        <sources>
          <source name="TraceSourceApp"
            switchName="sourceSwitch"
            switchType="System.Diagnostics.SourceSwitch">
            <listeners>
              <add name="console"
                type="System.Diagnostics.ConsoleTraceListener">
                <filter type="System.Diagnostics.EventTypeFilter"
                  initializeData="Error"/>
              </add>
              <add name="myListener"/>
              <remove name="Default"/>
            </listeners>
          </source>
        </sources>
        <switches>
          <add name="sourceSwitch" value="Error"/>
        </switches>
        <sharedListeners>
          <add name="myListener"
            type="System.Diagnostics.TextWriterTraceListener"
            initializeData="myListener.log">
            <filter type="System.Diagnostics.EventTypeFilter"
              initializeData="Error"/>
          </add>
        </sharedListeners>
      </system.diagnostics>
    </configuration>
    

    Помимо настройки прослушивателей трассировки, файл конфигурации создает фильтры для обоих прослушивателей и создает исходный коммутатор для источника трассировки. Показаны два метода для добавления прослушивателей трассировки: добавление прослушивателя непосредственно в источник трассировки и добавление прослушивателя в коллекцию общих прослушивателей, а затем добавление его по имени в источник трассировки. Фильтры, назначенные для двух слушателей, инициализированы с разными уровнями источника. Это приводит к тому, что некоторые сообщения записываются только одним из двух прослушивателей.

    Файл конфигурации инициализирует параметры источника трассировки во время инициализации приложения. Приложение может динамически изменять свойства, заданные файлом конфигурации, чтобы переопределить все параметры, указанные пользователем. Например, может потребоваться убедиться, что критически важные сообщения всегда отправляются в текстовый файл независимо от текущих параметров конфигурации. В примере кода показано, как переопределить параметры файла конфигурации, чтобы убедиться, что критически важные сообщения выводятся прослушивателям трассировки.

    Изменение параметров файла конфигурации во время выполнения приложения не изменяет начальные параметры. Чтобы изменить параметры, необходимо либо перезапустить приложение, либо программно обновить приложение с помощью Trace.Refresh метода.

Инициализация источников трассировки, прослушивателей и фильтров без файла конфигурации

  • Используйте следующий пример кода, чтобы включить трассировку через источник трассировки без использования файла конфигурации. Это не рекомендуется, но могут возникнуть обстоятельства, в которых вы не хотите зависеть от файлов конфигурации, чтобы обеспечить трассировку.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    namespace TraceSourceApp
    {
        class Program
        {
            private static TraceSource mySource =
                new TraceSource("TraceSourceApp");
            static void Main(string[] args)
            {
                mySource.Switch = new SourceSwitch("sourceSwitch", "Error");
                mySource.Listeners.Remove("Default");
                TextWriterTraceListener textListener =
                    new TextWriterTraceListener("myListener.log");
                ConsoleTraceListener console =
                    new ConsoleTraceListener(false);
                console.Filter =
                    new EventTypeFilter(SourceLevels.Information);
                console.Name = "console";
                textListener.Filter =
                    new EventTypeFilter(SourceLevels.Error);
                mySource.Listeners.Add(console);
                mySource.Listeners.Add(textListener);
                Activity1();
    
                // Allow the trace source to send messages to
                // listeners for all event types. Currently only
                // error messages or higher go to the listeners.
                // Messages must get past the source switch to
                // get to the listeners, regardless of the settings
                // for the listeners.
                mySource.Switch.Level = SourceLevels.All;
    
                // Set the filter settings for the
                // console trace listener.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Critical);
                Activity2();
    
                // Change the filter settings for the console trace listener.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Information);
                Activity3();
                mySource.Close();
                return;
            }
            static void Activity1()
            {
                mySource.TraceEvent(TraceEventType.Error, 1,
                    "Error message.");
                mySource.TraceEvent(TraceEventType.Warning, 2,
                    "Warning message.");
            }
            static void Activity2()
            {
                mySource.TraceEvent(TraceEventType.Critical, 3,
                    "Critical message.");
                mySource.TraceInformation("Informational message.");
            }
            static void Activity3()
            {
                mySource.TraceEvent(TraceEventType.Error, 4,
                    "Error message.");
                mySource.TraceInformation("Informational message.");
            }
        }
    }
    
    
    Imports System.Diagnostics
    Imports System.Threading
    
    
    
    Class Program
        Private Shared mySource As New TraceSource("TraceSourceApp")
    
        Shared Sub Main(ByVal args() As String)
            mySource.Switch = New SourceSwitch("sourceSwitch", "Error")
            mySource.Listeners.Remove("Default")
            Dim textListener As New TextWriterTraceListener("myListener.log")
            Dim console As New ConsoleTraceListener(False)
            console.Filter = New EventTypeFilter(SourceLevels.Information)
            console.Name = "console"
            textListener.Filter = New EventTypeFilter(SourceLevels.Error)
            mySource.Listeners.Add(console)
            mySource.Listeners.Add(textListener)
            Activity1()
    
            ' Allow the trace source to send messages to 
            ' listeners for all event types. Currently only 
            ' error messages or higher go to the listeners.
            ' Messages must get past the source switch to 
            ' get to the listeners, regardless of the settings 
            ' for the listeners.
            mySource.Switch.Level = SourceLevels.All
    
            ' Set the filter settings for the 
            ' console trace listener.
            mySource.Listeners("console").Filter = New EventTypeFilter(SourceLevels.Critical)
            Activity2()
    
            ' Change the filter settings for the console trace listener.
            mySource.Listeners("console").Filter = New EventTypeFilter(SourceLevels.Information)
            Activity3()
            mySource.Close()
            Return
    
        End Sub
    
        Shared Sub Activity1()
            mySource.TraceEvent(TraceEventType.Error, 1, "Error message.")
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.")
    
        End Sub
    
        Shared Sub Activity2()
            mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.")
            mySource.TraceInformation("Informational message.")
    
        End Sub
    
        Shared Sub Activity3()
            mySource.TraceEvent(TraceEventType.Error, 4, "Error message.")
            mySource.TraceInformation("Informational message.")
    
        End Sub
    End Class
    
    

См. также