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

Класс 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
    
    

См. также