SharePoint Guidance Library-SharePoint Logger Part-2

SharePoint Guidance Library - SharePoint Logger Part-1
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>();
Even you can reduce the ILogger instantiation to a single line of code, as follows.
ILogger logger = SharePointServiceLocator.GetCurrent().GetInstance<ILogger>();
******The SharePoint Logger includes a full-trust proxy that makes logging and tracing functionality available to sandboxed code. After you install and register the logging proxy, the SharePoint Logger automatically uses the proxy when it detects that it is running in the sandbox environment. As a result, the developer can use the SharePoint Logger in the same way regardless of whether he or she is writing full-trust code or sandboxed code—the developer experience is unchanged. If a developer attempts to use the SharePoint Logger in the sandbox environment, and the proxy is not installed and registered, any log or trace messages are dropped.
To install the logger proxy assemblies and register the proxy operations, you will need to deploy the solution package provided in Microsoft.Practices.SharePoint.Common.LoggerProxy. This package deploys a farm-scoped feature with a feature receiver class that registers the proxy operations. After it is deployed, the logger will function in the sandbox. Because the logger proxy is deployed at the farm scope, the proxy operations are available to all site collections within the farm.
At this point, you can start to use the ILogger object to write messages to the Windows event log and the ULS trace log.

Creating Log Entries

The ILogger interface defines a method named LogToOperations. Operations is another term for administrators and the tools that they use to monitor applications. When you log an event to operations, you should provide information that can help IT professionals understand how to remedy the problem. The information should be valuable and comprehensible to a systems administrator, even if the message is simply that the system behaved in an unexpected way that requires advanced debugging.
The default implementation of the LogToOperations method writes a message to both the Windows event log and the ULS trace log. The method provides several overloads that you can use to specify an event identifier, a severity, and a diagnostic area and category along with your message. All method overloads also append contextual information to the log entry, such as the user identity and the current URL, where applicable.
To log a message without specifying any additional information, simply pass in your message string as a parameter to the LogToOperations method.
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>();

// Log an event with a message.
string msg = "The current user does not have a valid PartnerID";
logger.LogToOperations(msg);
When you log an event, you may want to include an integer event ID with the event message. This can help system administrators to reference the issue and locate other instances of the same problem. It is good practice to use enumerated values or constants for event IDs in each solution that you develop. The following example assumes that you have created an enumeration of integer values named EventLogEventId.
// Log an event with a message and an event ID.
logger.LogToOperations(msg, (int)EventLogEventId.MissingPartnerID);
You may also want to specify a severity level. To do this, you can use the EventSeverity enumeration. This defines the severity levels used by SharePoint for the event log: ErrorCritical, Error, Warning, Information, and Verbose. The EventSeverity enumeration also contains various deprecated values that you should not use.
// Log an event with a message and a severity level.
logger.LogToOperations(msg, EventSeverity.Error);

// Log an event with a message, an event ID, and a severity level.
logger.LogToOperations(msg, (int) EventLogEventId.MissingPartnerID,
                       EventSeverity.Error);
Specifying a severity level enables system administrators to filter the Windows event log. For example, an administrator might want to view all messages with severity level Error without scrolling through many more trivial messages.
****The logger has several method overloads that accept a SandboxEventSeverity argument instead of an EventSeverity argument. Because the EventSeverity enumeration is not permitted in the sandbox, the SandboxEventSeverity provides a parallel enumeration structure that you can use within sandboxed code. If you use the SandboxEventSeverity enumeration, logging will succeed, regardless of whether your code runs inside or outside the sandbox.
Finally, in most cases, you should include values for diagnostic area and category when you log an event. Again, this can help system administrators to filter the event log to find only those events that are relevant to the issue under investigation. In the Windows event log, the area corresponds to the event source name and the category corresponds to the task category. To specify an area and category, you must pass a string parameter with the format "area/category" to the LogToOperations method.
// Log an event with a message, an event ID, a severity level, and a category.
string area = "Custom Area"
string category = "Execution";
string areaCategory = string.Format("{0}/{1}", area, category);
logger.LogToOperations(msg, (int) EventLogEventId.MissingPartnerID,
                       EventSeverity.Error, areaCategory);
If you do not specify a value for the diagnostic area and category when you log an event, the SharePoint Logger will set the area value to Patterns and Practices and the category value to SharePoint Guidance.

Using the LogToOperations Method to Log Exceptions

The following code shows how to use the LogToOperations method to log an exception from within a catch block. This example assumes that you have added a reference to the Microsoft.Practices.SharePoint.Common.dll assembly, the Microsoft.Practices.ServiceLocation.dll assembly, and the Microsoft.SharePoint.dll assembly.
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;
using Microsoft.Practices.SharePoint.Common.Logging;
using Microsoft.SharePoint;

// ...

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

try
{
   // Attempt a SharePoint operation.
}
catch (SPException ex)
{
   // Define your exception properties.
   string msg = "An error occurred while trying to retrieve the customer list";
   string category = @"SalesTool/Data";
   int eventID = 0;
   EventLogEntryType severity = EventSeverity.Error;

   // Log the exception.
   logger.LogToOperations(ex, msg, eventID, severity, category);
}

Creating Trace Messages

The ILogger interface defines a method named TraceToDeveloper. The default implementation of this method writes a message to the ULS trace log. Like the LogToOperations method, the TraceToDeveloper method provides several overloads that accept exceptions, integer event identifiers, severity levels, and diagnostic areas and categories along with your messages. However, while the LogToOperations method is aimed at system administrators, the TraceToDeveloper method is aimed at developers or advanced administrators who cannot attach a debugger to a production environment and therefore must rely on trace logs to identify the sources of problems.
The following code examples show how you can use different overloads of the TraceToDeveloper method. To log a message without specifying any additional information, simply pass in your message string as a parameter to the TraceToDeveloper method.
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>();

// Create a simple trace message.
string msg = "The current user does not have a valid PartnerID";
logger.TraceToDeveloper(msg);
If you are reporting an event to the trace log, you may want to include an integer event ID with your trace message. This can help developers who are searching for instances of a particular issue in the trace logs. The best practice approach is to use enumerated values or constants for event IDs in your solutions. The following example assumes that you have created an enumeration of integer values named TraceLogEventId.
// Create a trace message with an event ID.
logger.TraceToDeveloper(msg, (int) TraceLogEventId.MissingPartnerID);
If you want to specify a severity level in your trace message, use the TraceSeverity enumeration. This is a SharePoint-specific enumeration that is defined in the Microsoft.SharePoint.Administration namespace.
// Create a trace message with a trace severity level.
logger.TraceToDeveloper(msg, TraceSeverity.High);
****The logger has several method overloads that accept a SandboxTraceSeverity argument instead of a TraceSeverity argument. Because the TraceSeverity enumeration is not permitted in the sandbox, the SandboxTraceSeverity provides a parallel enumeration structure that you can use within sandboxed code. If you use the SandboxTraceSeverity enumeration, logging will succeed, regardless of whether your code runs inside or outside the sandbox.
You can also specify values for diagnostic area and category when you create a trace message. To specify an area and category, pass a string parameter with the format "area/category" to the TraceToDeveloper method.
// Create a trace message with a diagnostic area and category.
string area = "Custom Area"
string category = "Data";
string areaCategory = string.Format("{0}/{1}", area, category);
Logger.TraceToDeveloper(msg, areaCategory);
Other overloads of the TraceToDeveloper method allow you to specify various combinations of these properties.
Like the LogToOperations method, the TraceToDeveloper method provides several overloads that you can use to handle exceptions, as shown in the following code example
Exception ex = …

// 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, an event ID,
// a trace severity level, and an area/category string.
logger.TraceToDeveloper(ex, msg, (int) EventLogEventId.SkuNotFound,
     TraceSeverity.High, areaCategory);

// Trace an exception with an event ID, a trace severity level, and
// an area/category string.
logger.TraceToDeveloper(ex, (int) EventLogEventId.SkuNotFound,
     TraceSeverity.Verbose, areaCategory);
I next article I would try to cover how to extend the SharePoint logger

Comments