Share via


Using Custom Logger Classes

By default, when you use the SharePoint Service Locator to request an ILogger implementation, the SharePoint Service Locator returns an object of type SharePointLogger. In certain scenarios, you may need to substitute the SharePointLogger class with a different implementation of the ILogger interface. For example, you might want to use a mock object for unit testing, or you might want to develop a custom logging provider to meet your organization-specific logging requirements.

Suppose that you have developed a class named MyLogger that provides an alternative implementation of the ILogger interface. To replace the default SharePoint Logger functionality, all you need to do is to register the MyLogger class with the SharePoint Service Locator as the default implementation of the ILogger interface. Any code that uses the SharePoint Logger will not need to be updated or recompiled, because calling classes simply request an implementation of ILogger instead of a specific type.

The following code example shows how you can register the MyLogger class with the SharePoint Service Locator as an ILogger implementation.

IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
IServiceLocatorConfig typeMappings =  
serviceLocator.GetInstance<IServiceLocatorConfig>();

typeMappings.RegisterTypeMapping<ILogger, MyLogger>();

If you are substituting a mock ILogger implementation for unit testing, you should register your implementation with the SharePoint Service Locator as a singleton service. For more information about customizing the logger for unit testing, see Customizing the Logger for Unit Testing.

For details of how to create custom logger classes, see Creating Custom Logger Classes.