Logging, Tracing and Exception Management in Commerce Foundation

The Microsoft Multi-Channel Commerce Foundation Logging and Tracing is based on the .NET Framework's System.Diagnostics facilities provided for Tracing and Instrumenting Applications in Visual Basic and Visual C#, as described in the Visual Studio .NET documentation.

The functional goal of the Exception Management is to provide a consistent and flexible mechanism to handle errors in all Commerce Server 2009 subsystems from the Commerce Server 2009 Service (Broker and Providers) to the Commerce Server 2009 Presentation layer. The Commerce Server 2009 Exception Management relies on the Commerce Server 2009 Logging for logging exception.

Logging and Tracing

The Commerce Server 2009 Logging and Tracing mechanisms contain three main classes that help to make logging and tracing consistent and efficient, they are: Logger, Tracer and EtwTraceListener.

Dd451660.Mojave_Logger_Tracer_EtwTraceListener(en-US,CS.90).gif

The driver for tracing and logging is the Logger class that serves as a wrapper for the functionality provided by the System.Diagnostics.TraceSource and exposes two public overloaded methods: LogMessage and LogTrace. The LogMessage method forwards the calls to the System.Diagnostics.TraceSource instance that is identified in the configuration file by the Microsoft.Commerce.Trace.Messages name. The following is an example of the System.Diagnostics configuration for the Microsoft Multi-Channel Commerce Foundation tracing:

<system.diagnostics>
  <sources>
    <source name="Microsoft.Commerce.Trace.Presentation"     
            switchName="CommerceTraceSwitch">
      <listeners>
        <add name="CommerceEtwTraceListener" />
      </listeners>
    </source>

    <source name="Microsoft.Trace. Broker"     
            switchName="CommerceTraceSwitch">
      <listeners>
        <add name="CommerceEtwTraceListener" />
      </listeners>
    </source>

    <source name="Microsoft.Commerce.Trace.Provider"     
            switchName="CommerceTraceSwitch">
      <listeners>
        <add name="CommerceEtwTraceListener" />
      </listeners>
    </source>

    <source name="Microsoft.Commerce.Trace.CommerceServer"     
            switchName="CommerceTraceSwitch ">
      <listeners>
        <add name="CommerceEtwTraceListener" />
      </listeners>
    </source>

    <source name="Microsoft.Commerce.Trace.Custom"     
            switchName="CommerceTraceSwitch">
      <listeners>
        <add name="CommerceEtwTraceListener" />
      </listeners>
    </source>

  </sources>

  <switches>
    <add name="CommerceTraceSwitch" value="All"/>
  </switches>

  <sharedListeners>
    <add 
name="CommerceEtwTraceListener"
type="Microsoft.Commerce.Common.EtwTraceListener, Microsoft.Commerce.Common">
<filter type="System.Diagnostics.EventTypeFilter" initializeData="All" />
    </add>
  </sharedListeners>
</system.diagnostics>

By using System.Diagnostics configuration it is possible to configure any standard trace listener such as: EventLogTraceListener, TextWriterTraceListener, XmlWriterTraceListener, and so on; or a custom one that derives from the System.Diagnostics.TraceListener to be used with the Microsoft Multi-Channel Commerce Foundation Logger.

LogTrace method works in a similar way to the LogMessage method since it also forwards the calls to the TraceSource class. However, the LogTrace uses different trace sources based on the value of the first parameter passed to the method. The first parameter of this method is the TraceLayer enumeration:

public enum TraceLayer
    {
        Presentation,
        Broker,
        Provider,
        CommerceServer,
        Custom
    }

The following values of TraceLayer correspond to logical Commerce Server 2009 tiers:

Parameter

Description

Presentation

Indicates that the trace message originates from the presentation application level.

Broker

Indicates that the trace message originates from the broker application level.

Provider

Indicates that the trace message originates from the provider application level.

CommerceServer

Indicates that the trace message originates from the Commerce Server application level.

Custom

Indicates that the trace message originates from a custom application level.

The TraceLayer.CommerceServer corresponds to the Commerce Server 2009 code that directly invokes Microsoft Multi-Channel Commerce Foundation APIs within the Commerce Server 2009 service. The TraceLayer.Custom is available for use by the custom components that extend the shortMojave functionality.

To reduce the performance impact of tracing, especially in production, it is recommended to use the Event Tracing for Windows APIs (ETW). Microsoft Multi-Channel Commerce Foundation provides the EtwTraceListener class that wraps ETW APIs and can be used as a System.Diagnostics trace listener.

The role of the CommerceEtwTraceListener provider is to register events with ETW session when one exists, where they can be accessed by the ETW consumers. An ETW session is created by an ETW controller. For example:

set CommerceEtwTracingFileName="c:\logs\CommerceEtwTracingFileName.etl" 
call logman create trace CommerceEtwTracingSession -o %CommerceEtwTracingFileName% -p "{790227F0-C820-4258-9826-1D521C29409C}"
call logman start CommerceEtwTracingSession

To stop recording the ETW events the ETW session should be ended, for example:

logman query CommerceEtwTracingSession 2>1 >NUL

IF %ERRORLEVEL% EQU 0 (
    logman stop -ets CommerceEtwTracingSession
    logman delete CommerceEtwTracingSession
)

The ETW log file can be viewed by using the Service Trace Viewer (SvcTraceViewer.exe) utility from the Windows SDK.

To add tracing to a new component you are building for Microsoft Multi-Channel Commerce Foundation the Tracer class is designed to make it easy to trace entry and exit points of the code blocks - most often the methods. The Tracer class implements IDisposable interface and is supposed to be used with the C# using statement. The Lifetime of the Tracer object determines the beginning and the end of the trace.

void SomeMethod()

{

using (new Tracer(TraceLayer.Custom))

{

// Method implementation goes here.

}

}

When constructed the Tracer object logs the TraceEventType.Start event and its timestamp using the Commerce Server 2009 Logger.LogTrace. On leaving the using statement the Tracer object logs TraceEventType.Stop event and the duration of the code execution within the using statement using the Commerce Server 2009 Logger.LogTrace. These event entries can be used for performance analysis in the production systems.

To enable tracing at any level be sure that the GlobalServiceConfiguration attribute enableTracing is set to true.

<GlobalServiceConfiguration enableTracing="true">
    <Services>
        <Service contract="Microsoft.Commerce.Contracts.IOperationService, Microsoft.Commerce.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" implementation="Microsoft.Commerce.Broker.OperationService, Microsoft.Commerce.Broker,  Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </Services>
</GlobalServiceConfiguration>

Exception Management

The key class in the Exception Management is the ExceptionManager, which exposes a single overloaded method HandleException:

public static void HandleException(Exception exception)

public static void HandleException(string policyName, Exception exception)

where:

exception is the exception to handle;

If the policy name is not specified the default exception policy is used.

The power and flexibility of the ExceptionManager.HandleException method is based on the configurable exception policies. An exception policy is a named section in the configuration file that lists the exception handling components (exception handlers). When ExceptionManager.HandleException is invoked all the components specified in the exception policy are executed in the order they are listed in the configuration file. These components are required to implement the following interface:

    public interface IExceptionHandler
    {
        Exception HandleException(Exception exception);
        string InitializationData { get; set; }
    }

The IExceptionHandler.HandleException method, when implemented by a class, handles an exception. An exception handler can log exception information to a log, display an error window to the user, convert the original exception to a different exception type, and so on. Depending on the implementation this method returns either the original exception passed to it or a modified exception. The returned exception is passed to the next exception handler in the exception policy chain.

InitializationData is an optional property can be used to provide some initialization data to the handler. For example, the logging exception handler may have the trace source name provided through the InitializationData, this is an example of the Exception Management configuration:

<exceptionHandling defaultPolicyName="Default">
    <exceptionPolicy name="Default">
      <exceptionHandler 
          name="TextLoggingExceptionHandler"
          type="Microsoft.Commerce.Common.TextLoggingExceptionHandler, 
Microsoft.Commerce.Common"
    initializeData="Microsoft.Commerce.Exceptions" />
    </exceptionPolicy>

    <exceptionPolicy name="TestPolicy">
    <exceptionHandler
      name="WrappingExceptionHandler"
      type="Microsoft.Commerce.API.Test.Common.
          WrappingExceptionHandler, 
      Microsoft.Commerce.API.Test" />
    <exceptionHandler 
      name="XmlLoggingExceptionHandler"
      type="Microsoft.Commerce.Common.
XmlLoggingExceptionHandler, 
Microsoft.Commerce.Common"
initializeData="Microsoft.Commerce.Exceptions" />
  </exceptionPolicy>
</exceptionHandling>

All Exception Management configurations are contained within the <exceptionHandling> section, which consists of the collection of the exception policies configured within <exceptionPolicy> elements. The only required attribute of the <exceptionPolicy> element is name, which defines the policy name. This is the name used with the ExceptionManager.HandleException method. Each <exceptionPolicy> element contains one or more <exceptionHandler> elements that define exception handler components that belong to the policy. The <exceptionHandler> element has three required and one optional attributes:

Attribute

Description

name

The exception handler's name.

type

The exception handler's fully qualified .NET type.

initializeData

Optional string that is passed to the exception handler during its initialization through the IExceptionHandler.InitializationData property.

The <exceptionHandling> element has the required defaultPolicyName attribute, which refers to one of the <exceptionPolicy> elements contained within it. When ExceptionManager.HandleException method is called without the policy name specified then the ExceptionManager uses the policy specified by the defaultPolicyName attribute.

Microsoft Multi-Channel Commerce Foundation provides two exception handlers - XmlLoggingExceptionHandler and TextLoggingExceptionHandler. Application developers can provide additional exception handlers that implement IExceptionHandler interface and configure them through the <exceptionHandling> configuration section as described above.

See Also

Other Resources

Developing with the Multi-Channel Commerce Foundation

Extending Commerce Foundation

Starting, Stopping, and Formatting XMLTracer Output