How to implement logging in SharePoint 2010–part1
Nowadays I’m doing lot of code review for SharePoint 2010 projects. One of the thing I’ve noticed is that the developers don’t understand the best practices for implementing logging with SharePoint 2010. This has compelled me to collate the guidance on SharePoint 2010 logging. I’ll be writing series of articles about SharePoint 2010 logging. In this article I’d be providing an overview of SharePoint Logger component and how to create an instance of ILogger object.
It is recommended to leverage the re-usable component SharePoint Logger(Logger) shipped with MSDN Patterns and Practices guidance for implementing logging capablities for SharePoint 2010 development. It provides the capability to write messages to the Windows event logs and ULS trace log. The interface ILogger exposes the following methods:-
This method can be used to write the Windows event logs and ULS trace logs. The overloaded parameters like identifiers, categories, severities and exception details can be provided
This method can be used to write to the ULS Trace log. The overloaded parameters like identifiers, categories, severities and exception details can be provided
The following code-snippet illustrates how to
ILogger oLogger = SharePointServiceLocator.GetCurrent ().Get Instance<ILogger> ();
oLogger.TraceToDeveloper ("Unexpected condition");
Creating a Logger object
The first step in logging message to the Windows event log or the ULS trace log is to create an object that implements ILogger interface. The SharePoint Logger provides a default implementation of this interface in a class named SharePointLogger. The SharePointLogger can be instantiated directly or it can be instantiated through the SharePoint Service Locator. It is recommended to leverage the SharePoint Service Locator pattern for getting the instance of SharePoint Logger, considering separation of concerns and test driven development in mind.
The next logical step is to add the reference to the required assemblies (Microsoft.Practices.SharePoint.Common.dll and Microsoft.Practices.ServiceLocation.dll).
//Get the instance of Service Locator
IServiceLocator oServiceLocator = SharePointServiceLocator.GetCurrent();
//Get the instance of ILogger
ILogger oLogger = oServiceLocator.GetInstance<ILogger>();
In the next post, I’d be focusing on how to create and manage custom log areas and custom log categories.
Subscribe to my blog