Creating a Trace Message for Developers
Typical Goals
In this scenario, you want to write debugging information to 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 TraceToDeveloper method. You can include descriptive strings, event IDs, exceptions, trace severity levels, and category strings as arguments to the TraceToDeveloper method.
Creating a Trace Message During Development
The following code demonstrates how to create a trace message.
ILogger logger = SharePointServiceLocator.Current.GetInstance<ILogger>();
logger.TraceToDeveloper("Unexpected condition");
The TraceToDeveloper method writes to the ULS trace log.
Usage Notes
The TraceToDeveloper method has 11 overloaded versions that allow you to specify optional information such as trace severity level, event ID, exception data, and category string. The following are some examples of how to use the overloads.
// ILogger logger = ...
// Exception ex = ...
// string msg = ...
// string category = ...
// Here is a simple trace.
logger.TraceToDeveloper(msg);
// trace an event
logger.TraceToDeveloper(msg, (int) EventLogEventId.SkuNotFound);
// trace with a trace severity
logger.TraceToDeveloper(msg, TraceSeverity.High);
// trace with a category string
Logger.TraceToDeveloper(msg, category);
// trace with an event ID and a trace severity level
logger.TraceToDeveloper(msg, (int) EventLogEventId.PartnerNotFound,
TraceSeverity.Verbose);
// trace with an event ID, a trace severity level and a category string
logger.TraceToDeveloper(msg, (int) EventLogEventId.PartnerNotFound,
TraceSeverity.Unexpected, category);
// trace an exception
logger.TraceToDeveloper(ex);
// trace an exception with an additional error message
logger.TraceToDeveloper(ex, msg);
// trace an exception with an additional error message and
// an application-defined event id
logger.TraceToDeveloper(ex, msg, (int) EventLogEventId.SkuNotFound);
// trace an exception with an additional error message, a default event id,
// a trace severity level and a category string
logger.TraceToDeveloper(ex, msg, 0, TraceSeverity.High, category);
// trace an exception with a default event id, trace severity string and
// a category string
logger.TraceToDeveloper(ex, 0, TraceSeverity.Verbose, category);
The EventLogEventId enumeration is user defined. It is a recommended practice to encode your application's event types as enumerated values.
The TraceSeverity enumeration is provided by SharePoint. It is found in the Microsoft.SharePoint.Administration namespace. For more information, see TraceSeverity Enumeration on MSDN.