Thursday, August 2, 2012

Sample code for SharePoint ULS logging

The following code is a sample of how to write information to the ULS Log from your SharePoint-related code (in this case, I'd like to send an informational message from the code in my web part):

SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("My Web Part", TraceSeverity.Verbose, EventSeverity.Information), TraceSeverity.Verbose, "Message I'd like to log", null);

In the event you don't see the message showing up in the ULS Log, it could be possible that your SharePoint Admin is filtering out items with a low level TraceSeverity or EventSeverity such as those I'm using here (i.e. TraceSeverity.Verbose and EventSeverity.Information).  By the way, I'll be certain to cover how this is controlled in my next post.

Now, if you're interested in communicating error messages, there is a different method that you can use to write to both the Event Log and the ULS Log. The following code covers a simple way that you can communicate an error to both of those logs:

try
{
     ...
}
catch (Exception ex)
{
     SPDiagnosticsService.Local.WriteEvent(0, new SPDiagnosticsCategory("My Web Part ", TraceSeverity.Unexpected, EventSeverity.Error), EventSeverity.Error, ex.Message, ex.StackTrace);
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.