Logging an Exception

Typical Goals

In this scenario, you want to log an exception to the Windows event log and the ULS trace log.

Solution

In Visual Studio, add a reference to the SharePoint Guidance Library, Microsoft.Practices.SPG.Common.dll. Use the SharePoint service locator to get a reference to a Microsoft.Practices.SPG.Common.Logging.ILogger interface and invoke the LogToOperations method. Pass the exception that you want to log as an argument to the LogToOperations method.

Quickstart

For an extended example of how to log an exception using the SharePoint logger, see [TBD].

Logging an Exception

The following code demonstrates how to log an exception.
C#
try 
{
   /// ... a SharePoint operation ...
}
catch (SPException sharePointException)
{
   ILogger logger = SharePointServiceLocator.Current.GetInstance<ILogger>();
   logger.LogToOperations(sharePointException);
}

The LogToOperations method records the exception in the Windows event log and the ULS trace log.

Usage Notes

The LogToOperations method has overloaded versions that allow you to specify optional information for the exception you are logging. You can include:
  • An application-specific error string of your choosing.
  • An integer event ID.
  • An event-log entry type that distinguishes warnings from errors.
  • A string that denotes a category.
Here are examples of these options.
C#
// ILogger logger = ...
// Exception ex = ...
// string msg = ...
// string category = ...

// log an exception with an additional error message
logger.LogToOperations(ex, msg);

// log an exception with an additional error message and 
// an application-defined event id
logger.LogToOperations(ex, msg, (int) EventLogEventId.SkuNotFound);

// log an exception with an additional error message, a default event ID,
// an event-log entry type and a category string
logger.LogToOperations(ex, msg, 0, EventLogEntryType.Error, category)

// log an exception with a default event id, an event-log entry type and 
// a category string
logger.LogToOperations(ex, 0, EventLogEntryType.Warning, category)

For more information on the EventLogEntryType enumeration, see <insert link>.




To give feedback.
Copyright (c) 2007 by Microsoft Corporation. All rights reserved.

Last edited Jun 16, 2009 at 7:50 PM by ckeyser, version 1

Comments

No comments yet.