Редагувати

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


EventSchemaTraceListener Class

Definition

Directs tracing or debugging output of end-to-end events to an XML-encoded, schema-compliant log file.

public ref class EventSchemaTraceListener : System::Diagnostics::TextWriterTraceListener
public class EventSchemaTraceListener : System.Diagnostics.TextWriterTraceListener
type EventSchemaTraceListener = class
    inherit TextWriterTraceListener
Public Class EventSchemaTraceListener
Inherits TextWriterTraceListener
Inheritance

Examples

The following code example demonstrates how to use the EventSchemaTraceListener class.


///////////////////////////////////////////////////////////////////////
//
// EventSchemaTraceListener.cpp : main project file.
// Expected Output:
// 1)
//      EventSchemaTraceListener CPP Sample
//
//      IsThreadSafe? True
//      BufferSize =  65536
//      MaximumFileSize =  20480000
//      MaximumNumberOfFiles =  2
//      Name =  eventListener
//      TraceLogRetentionOption = LimitedCircularFiles
//      TraceOutputOptions = DateTime, Timestamp, ProcessId
//
//      Press the enter key to exit
//
// 2) An output file is created named TraceOutput.xml.  It will be
//    opened and displayed in Microsoft Notepad.
//
// NOTE 1:
//  Under certain circumstances, the VS C++ compiler will treat
//          Console::WriteLine("MyText = " + MyVar);
//        differently then the VS CSharp compiler.
//        The C++ compiler will produce error C3063, whereas the 
//        CSharp compiler accepts the statement.
//        This occurs when the VS C++ compiler cannot determine the
//        datatype of "MyVar" because it is an enumeration type.
//        The solution is:
//        Use either of the following two methods:
//          Console::WriteLine("MyText = {0} " , MyVar);
//          Console::WriteLine("MyText =  " + MyVar.ToString());
//
//        Although not specific to this particular pieces of code,
//        this is demonstrated below in the Display function:  The
//        last two members, TraceLogRetentionOption, and
//        TraceOutputOptions, are enumerations, and cannot simply be
//        concatenated into Console::WriteLine.
//
///////////////////////////////////////////////////////////////////////
#using <System.dll>
#using <System.Core.dll>

#define NOCONFIGFILE 1
using namespace System;
using namespace System::IO;
using namespace System::Diagnostics;


[STAThreadAttribute]
void main()
{
    Console::WriteLine("EventSchemaTraceListener CPP Sample\n");

    File::Delete("TraceOutput.xml");
    TraceSource ^ ts = gcnew TraceSource("TestSource");


#if NOCONFIGFILE
    ts->Listeners->Add(gcnew EventSchemaTraceListener("TraceOutput.xml",
                            "eventListener", 65536,
                            TraceLogRetentionOption::LimitedCircularFiles,
                            20480000, 2));
    ts->Listeners["eventListener"]->TraceOutputOptions =
                                    TraceOptions::DateTime |
                                    TraceOptions::ProcessId |
                                    TraceOptions::Timestamp;
#endif

    EventSchemaTraceListener ^ ESTL =
               (EventSchemaTraceListener^)(ts->Listeners["eventListener"]);


    Console::WriteLine("IsThreadSafe?            = " + ESTL->IsThreadSafe);
    Console::WriteLine("BufferSize               = " + ESTL->BufferSize);
    Console::WriteLine("MaximumFileSize          = " + ESTL->MaximumFileSize);
    Console::WriteLine("MaximumNumberOfFiles     = " + ESTL->MaximumNumberOfFiles);
    Console::WriteLine("Name                     = " + ESTL->Name);
    Console::WriteLine("TraceLogRetentionOption  = " + ESTL->TraceLogRetentionOption.ToString());
    Console::WriteLine("TraceOutputOptions       = {0}\n", ESTL->TraceOutputOptions);

    ts->Switch->Level = SourceLevels::All;
    String ^ testString = "<Test><InnerElement Val=\"1\" />"
                        + "<InnerElement Val=\"Data\"/>"
                        + "<AnotherElement>11</AnotherElement></Test>";

    UnescapedXmlDiagnosticData ^ unXData = gcnew UnescapedXmlDiagnosticData(testString);
    ts->TraceData(TraceEventType::Error, 38, unXData);
    ts->TraceEvent(TraceEventType::Error, 38, testString);
    ts->Flush();
    ts->Close();

    Process::Start("notepad.exe", "TraceOutput.xml");
    Console::WriteLine("\nPress the enter key to exit");
    Console::ReadLine();
}
#define NOCONFIGFILE
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics;

class testClass
{
    [STAThreadAttribute]
    static void Main()
    {
        File.Delete("TraceOutput.xml");
        TraceSource ts = new TraceSource("TestSource");
#if NOCONFIGFILE
        //ts.Listeners.Add(new EventSchemaTraceListener("TraceOutput.xml", "eventListener", 65536, TraceLogRetentionOption.LimitedCircularFiles, 20480000, 2));
        ts.Listeners.Add(new EventSchemaTraceListener("TraceOutput.xml", "eventListener"));
        ts.Listeners["eventListener"].TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ProcessId | TraceOptions.Timestamp;
#endif
        ts.Switch.Level = SourceLevels.All;
        string testString = "<Test><InnerElement Val=\"1\" /><InnerElement Val=\"Data\"/><AnotherElement>11</AnotherElement></Test>";
        UnescapedXmlDiagnosticData unXData = new UnescapedXmlDiagnosticData(testString);
        ts.TraceData(TraceEventType.Error, 38, unXData);
        ts.TraceEvent(TraceEventType.Error, 38, testString);
        Trace.Listeners.Add(new EventSchemaTraceListener("TraceOutput.xml"));
        Trace.Write("test", "test");
        Trace.Flush();
        ts.Flush();
        ts.Close();
        DisplayProperties(ts);
        Process.Start("notepad.exe", "TraceOutput.xml");
        Console.WriteLine("Press the enter key to exit");
        Console.ReadLine();
    }
    private static void DisplayProperties(TraceSource ts)
    {
        Console.WriteLine("IsThreadSafe? " + ((EventSchemaTraceListener)ts.Listeners["eventListener"]).IsThreadSafe);
        Console.WriteLine("BufferSize =  " + ((EventSchemaTraceListener)ts.Listeners["eventListener"]).BufferSize);
        Console.WriteLine("MaximumFileSize =  " + ((EventSchemaTraceListener)ts.Listeners["eventListener"]).MaximumFileSize);
        Console.WriteLine("MaximumNumberOfFiles =  " + ((EventSchemaTraceListener)ts.Listeners["eventListener"]).MaximumNumberOfFiles);
        Console.WriteLine("Name =  " + ((EventSchemaTraceListener)ts.Listeners["eventListener"]).Name);
        Console.WriteLine("TraceLogRetentionOption =  " + ((EventSchemaTraceListener)ts.Listeners["eventListener"]).TraceLogRetentionOption);
        Console.WriteLine("TraceOutputOptions =  " + ((EventSchemaTraceListener)ts.Listeners["eventListener"]).TraceOutputOptions);
    }
}
#Const NOCONFIGFILE = True
Imports System.IO
Imports System.Xml
Imports System.Xml.XPath
Imports System.Diagnostics

Class testClass

    <STAThreadAttribute()> _
    Shared Sub Main()
        File.Delete("TraceOutput.xml")
        Dim ts As New TraceSource("TestSource")
#If NOCONFIGFILE Then
        ts.Listeners.Add(New EventSchemaTraceListener("TraceOutput.xml", "eventListener", 65536, TraceLogRetentionOption.LimitedCircularFiles, 20480000, 2))
        ts.Listeners("eventListener").TraceOutputOptions = TraceOptions.DateTime Or TraceOptions.ProcessId Or TraceOptions.Timestamp
#End If
        ts.Switch.Level = SourceLevels.All
        Dim testString As String = "<Test><InnerElement Val=""1"" /><InnerElement Val=""Data""/><AnotherElement>11</AnotherElement></Test>"
        Dim unXData As New UnescapedXmlDiagnosticData(testString)
        ts.TraceData(TraceEventType.Error, 38, unXData)
        ts.TraceEvent(TraceEventType.Error, 38, testString)
        ts.Flush()
        ts.Close()
        DisplayProperties(ts)
        Process.Start("notepad.exe", "TraceOutput.xml")
        Console.WriteLine("Press the enter key to exit")
        Console.ReadLine()

    End Sub

    Private Shared Sub DisplayProperties(ByVal ts As TraceSource)
        Console.WriteLine("IsThreadSafe? " + CType(ts.Listeners("eventListener"), EventSchemaTraceListener).IsThreadSafe.ToString())
        Console.WriteLine("BufferSize =  " + CType(ts.Listeners("eventListener"), EventSchemaTraceListener).BufferSize.ToString())
        Console.WriteLine("MaximumFileSize =  " + CType(ts.Listeners("eventListener"), EventSchemaTraceListener).MaximumFileSize.ToString())
        Console.WriteLine("MaximumNumberOfFiles =  " + CType(ts.Listeners("eventListener"), EventSchemaTraceListener).MaximumNumberOfFiles.ToString())
        Console.WriteLine("Name =  " + CType(ts.Listeners("eventListener"), EventSchemaTraceListener).Name)
        Console.WriteLine("TraceLogRetentionOption =  " + CType(ts.Listeners("eventListener"), EventSchemaTraceListener).TraceLogRetentionOption.ToString())
        Console.WriteLine("TraceOutputOptions =  " + CType(ts.Listeners("eventListener"), EventSchemaTraceListener).TraceOutputOptions.ToString())
    End Sub
End Class

Remarks

The EventSchemaTraceListener class provides tracing of end-to-end schema-compliant events. You can use end-to-end tracing for a system that has heterogeneous components that cross thread, AppDomain, process, and computer boundaries. A standardized event schema enables tracing across these boundaries. The schema enables the addition of custom, schema-compliant elements. You can use the Service Trace Viewer Tool (SvcTraceViewer.exe) to display the event data.

EventSchemaTraceListener is tuned for logging performance with implicit support for lock-free tracing.

The EventSchemaTraceListener class converts tracing and debugging information into an XML-encoded text stream. The description of the XML output is shown in the tables later in this section.

You can create an EventSchemaTraceListener object in your code. Alternatively, for .NET Framework apps, you can enable or disable an EventSchemaTraceListener object through the application configuration file, and then use the configured EventSchemaTraceListener object in your application. For information about the use of configuration files for tracing and debugging in .NET Framework apps, see Trace and Debug Settings Schema.

To configure an EventSchemaTraceListener object in a .NET Framework app, modify the configuration file that corresponds to the name of your application. In this file, you can add, remove, or set the properties for a listener. The configuration file should be formatted as follows:

<configuration>  
    <system.diagnostics>  
        <sources>  
            <source name="TestSource" >  
                <listeners>  
                    <!--Remove the default trace listener for better performance.-->  
                    <remove name="Default"/>  
                    <!--Note: Removing the default trace listener prevents the dialog box   
                    from being displayed for Debug.Fail or Debug.Assert commands that are   
                    executed in user mode.-->  
                    <add name="eventListener"   
                      type="System.Diagnostics.EventSchemaTraceListener,  system.core"  
                      initializeData="TraceOutput.xml"   
                      traceOutputOptions="ProcessId, DateTime, Timestamp"   
                      bufferSize="65536"  
                      maximumFileSize="20480000"  
                      logRetentionOption="LimitedCircularFiles"  
                      maximumNumberOfFiles="2"/>  
                </listeners>  
            </source>  
        </sources>  
    </system.diagnostics>  

The EventSchemaTraceListener class inherits the Filter property from the base class TraceListener. The Filter property allows for an additional level of trace output filtering at the listener. If a filter is present, the Trace methods of the trace listener call the ShouldTrace method of the filter to determine whether to emit the trace.

If an attempt is made to write to a file that is being used or is unavailable, a GUID suffix is automatically added to the file name.

Note

Listener methods are intended to be called by methods of the Debug, Trace, and TraceSource classes. Do not call the listener methods directly from application code. The EventSchemaTraceListener listener is primarily intended for use by the TraceSource class.

The following table describes the elements and attributes of the XML output.

Element Attributes Output Notes
CallStack None Depends on the presence of the Callstack flag in the TraceOutputOptions property. Special characters such as > or < are replaced with escape sequences. See the escaped character translation table in the next table.
Computer None Always present. This element represents the value of the MachineName property.
Correlation ActivityID Always present. If ActivityID is not specified, the default is an empty GUID.
RelatedActivityID Depends on the presence of the relatedActivityId parameter in the Trace method call. The RelatedActivityID attribute corresponds to the relatedActivityId parameter of the TraceTransfer method.
Data None Always present. This element represents parameter input (data). One element is provided for each data object. In the case of event logs, the Data element contains escaped XML data. In the case of data logs, the Data element contains unescaped data. The data log output uses the ToString method of the passed-in data objects.
Event None Always present. This element contains a trace event.
EventData None Present for event logs. This element represents parameter input (message, args). It contains Data elements with escaped XML data that is created by calling the TraceEvent method.
EventID None Always present. This element represents parameter input (id).
Execution ProcessID Depends on the presence of the ProcessId flag in the TraceOutputOptions property. The ProcessID attribute is specified in the TraceEventCache.
ThreadID Present when ProcessID is present. The ThreadID attribute is specified in the TraceEventCache.
Level None Always present. This element represents parameter input (the numeric value of eventType). Parameter values that are larger than 255 are output as a level 8, which represents TraceEventType.Information. Trace event types Critical, Error, Warning, Information, and Verbose are output as levels 1, 2, 4, 8, and 10, respectively.
LogicalOperationStack None Depends on the presence of the LogicalOperationStack flag in the TraceOutputOptions property. Only one logical operation can exist. Therefore, the values are written as LogicalOperation nodes under the LogicalOperationStack element.
OpCode None Present when Level is greater than 255. This element represents Trace event types that have numeric values greater than 255. Start, Stop, Suspend, Resume, or Transfer are output as levels 1, 2, 4, 8, and 10, respectively.
Provider GUID Always present. Always empty.
RenderingInfo Culture Always present. This attribute represents a resource string for the event type. It is always "en-EN\".
System Name Always present.
TimeCreated SystemTime Depends on the presence of the DateTime flag in the TraceOutputOptions property. The time is the value of the TraceEventCache.DateTime property. This property is expressed as Coordinated Universal Time
TimeStamp None Depends on the presence of the Timestamp flag in the TraceOutputOptions property. This element is specified in the TraceEventCache.
UserData None Present for data logs. This element contains Data elements with unescaped, user-provided data from a TraceData method.

The following table shows the characters that are escaped in the XML output. Escaping occurs in all the elements and attributes except for the UserData element, which contains user-provided, unescaped data. The UserData element is a result of calls to the TraceData method.

Escaped character Value
& &
< <
> >
" "
|'
0xD &#xD;
0xA &#xA;

Constructors

EventSchemaTraceListener(String, String, Int32, TraceLogRetentionOption, Int64, Int32)

Initializes a new instance of the EventSchemaTraceListener class with the specified name and specified buffer size, using the specified file with the specified log retention policy, maximum size, and file count as the recipient of the debugging and tracing output.

EventSchemaTraceListener(String, String, Int32, TraceLogRetentionOption, Int64)

Initializes a new instance of the EventSchemaTraceListener class with the specified name and specified buffer size, using the specified file with the specified log retention policy and maximum size as the recipient of the debugging and tracing output.

EventSchemaTraceListener(String, String, Int32, TraceLogRetentionOption)

Initializes a new instance of the EventSchemaTraceListener class with the specified name and specified buffer size, using the specified file with the specified log retention policy as the recipient of the debugging and tracing output.

EventSchemaTraceListener(String, String, Int32)

Initializes a new instance of the EventSchemaTraceListener class with the specified name and specified buffer size, using the specified file as the recipient of debugging and tracing output.

EventSchemaTraceListener(String, String)

Initializes a new instance of the EventSchemaTraceListener class with the specified name, using the specified file as the recipient of debugging and tracing output.

EventSchemaTraceListener(String)

Initializes a new instance of the EventSchemaTraceListener class, using the specified file as the recipient of debugging and tracing output.

Properties

Attributes

Gets the custom trace listener attributes defined in the application configuration file.

(Inherited from TraceListener)
BufferSize

Gets the size of the output buffer.

Filter

Gets or sets the trace filter for the trace listener.

(Inherited from TraceListener)
IndentLevel

Gets or sets the indent level.

(Inherited from TraceListener)
IndentSize

Gets or sets the number of spaces in an indent.

(Inherited from TraceListener)
IsThreadSafe

Gets a value indicating whether the trace listener is thread safe.

MaximumFileSize

Gets the maximum size of the log file.

MaximumNumberOfFiles

Gets the maximum number of log files.

Name

Gets or sets a name for this TraceListener.

(Inherited from TraceListener)
NeedIndent

Gets or sets a value indicating whether to indent the output.

(Inherited from TraceListener)
TraceLogRetentionOption

Gets the trace log retention option for the file.

TraceOutputOptions

Gets or sets the trace output options.

(Inherited from TraceListener)
Writer

Gets or sets the underlying text writer that writes to the log file.

Methods

Close()

Closes the log file for this listener so that it no longer receives tracing or debugging output.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose()

Releases all resources used by the TraceListener.

(Inherited from TraceListener)
Dispose(Boolean)

Disposes this TextWriterTraceListener object.

(Inherited from TextWriterTraceListener)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Fail(String, String)

Writes error information, including a basic error message and a detailed error message, to the log file.

Fail(String)

Emits an error message to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
Flush()

Causes buffered data to be written to the log for this listener.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetSupportedAttributes()

Gets the custom XML configuration attributes that the trace listener supports.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString()

Returns a string that represents the current object.

(Inherited from Object)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object)

Writes trace information, a single data object, and event information to the log file.

TraceData(TraceEventCache, String, TraceEventType, Int32, Object[])

Writes trace information, multiple data objects, and event information to the log file.

TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object[])

Writes trace information, a formatted message, and event information to the log file.

TraceEvent(TraceEventCache, String, TraceEventType, Int32, String)

Writes trace information, a message, and event information to the log file.

TraceEvent(TraceEventCache, String, TraceEventType, Int32)

Writes trace and event information to the listener specific output.

(Inherited from TraceListener)
TraceTransfer(TraceEventCache, String, Int32, String, Guid)

Writes trace information, including the identity of a related activity, a message, and event information, to the log file.

Write(Object, String)

Writes a category name and the value of the object's ToString() method to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
Write(Object)

Writes the value of the object's ToString() method to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
Write(String, String)

Writes a category name and a message to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
Write(String)

Writes a message to the log file without providing any additional context information.

WriteIndent()

Writes the indent to the listener you create when you implement this class, and resets the NeedIndent property to false.

(Inherited from TraceListener)
WriteLine(Object, String)

Writes a category name and the value of the object's ToString() method to the listener you create when you implement the TraceListener class, followed by a line terminator.

(Inherited from TraceListener)
WriteLine(Object)

Writes the value of the object's ToString() method to the listener you create when you implement the TraceListener class, followed by a line terminator.

(Inherited from TraceListener)
WriteLine(String, String)

Writes a category name and a message to the listener you create when you implement the TraceListener class, followed by a line terminator.

(Inherited from TraceListener)
WriteLine(String)

Writes a message followed by the current line terminator to the log file without providing any additional context information.

Applies to