Logging and Tracing in the Partner Portal

This topic shows how the Partner Portal application uses the SharePoint logger that is provided by the SharePoint Guidance Library.

Locating the SharePoint Logger Service

The Partner Portal's ProductDetailsPresenter class demonstrates the following:

  • It demonstrates how to use the SharePoint logger to record information to the unified logging service (ULS) and the Windows event log.
  • It demonstrates how the SharePoint service locator decouples the logging consumer from the implementation.

The following code shows the ProductDetailsPresenter class's constructor. The product details presenter implementation is located in Contoso.PartnerPortal.ProductCatalog\WebParts\ProductDetails\ProductDetailsPresenter.cs.

public class ProductDetailsPresenter
   // ...

   private IProductDetailsView view;
   private ILogger logger;

   public ProductDetailsPresenter(IProductDetailsView view)
     this.view = view;
     this.logger = SharePointServiceLocator.Current.GetInstance<ILogger>();
// ...

The constructor uses the SharePointServiceLocator class to get a logger instance and save it in an instance field named logger. The ProductDetailsPresenter class is now decoupled from a specific logger implementation. The choice of logger implementation is configurable. The default logger can be replaced without modifying the ProductDetailsPresenter class.

For more information about the SharePoint service locator, see The SharePoint Service Locator.

Methods of the ProductDetailsPresenter class write diagnostic information to the logger that was initialized in the constructor. For example, the following code shows the LoadProduct method.

public void LoadProduct(string sku)
      this.logger.TraceToDeveloper("Start LoadProduct.");

      // ... perform application logic ...

      this.logger.TraceToDeveloper("End LoadProduct.");
    catch(Exception ex)
       // If something goes wrong, make sure the error gets logged
       new ViewExceptionHandler().HandleViewException(ex, this.ErrorVisualizer, 
           "Due to a technical problem, the product details cannot be displayed.");

The logger is invoked three times. There are TraceToDeveloper calls at the beginning and end of the LoadProduct method that create entries in the ULS trace log. There is also a call to the HandleViewException method of the ViewExceptionHandler class. The HandleViewException method also calls the logger’s LogToOperations method. This ensures that if the LoadProduct method throws an exception, the details are preserved in both the Windows event log and the ULS trace log.

Home page on MSDN | Community site