Бөлісу құралы:


Creating a Logger Object

Before you can write messages to the Windows event logs or the ULS trace log, you must create an object that implements the ILogger interface. The SharePoint Logger provides a default implementation of this interface in a class named SharePointLogger. You can directly instantiate the SharePointLogger class although it is typically a good practice to use the SharePoint Service Locator to request an implementation of the ILogger interface. This keeps your code decoupled from the SharePointLogger implementation.

Before you can use the SharePoint Logger in your custom solutions, you must add references to the Microsoft.Practices.SharePoint.Common.dll assembly and the Microsoft.Practices.ServiceLocation.dll assembly. The following code shows how you can get an implementation of the ILogger interface from the SharePoint Service Locator.

using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;
using Microsoft.Practices.SharePoint.Common.Logging;

IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
ILogger logger = serviceLocator.GetInstance<ILogger>();

For brevity, you can reduce the ILogger instantiation to a single line of code, as follows.

ILogger logger = SharePointServiceLocator.GetCurrent().GetInstance<ILogger>();

At this point, you can start to use the ILogger object to write messages to the Windows event log and the ULS trace log.

Note

If you want to use the SharePoint Logger from sandboxed code, you must first register the logger proxy. The SharePoint Logger automatically detects whether it is running in a sandbox environment and will use the proxy when appropriate—the developer experience is unchanged. For more information about how to register the logger proxy, see Using the SharePoint Logger from Sandboxed Code.