Wednesday, June 12, 2013

Get log entries from the SharePoint 2013 ULS using C#

Suppose you aren't happy with the accessibility of the ULS log in SharePoint 2013. Often this is what you get from users who encounter an error:

"Thanks," you say. "Could you please recreate the error and click on the technical details and copy and paste the message to me?"

When you finally get the correlation Id, you have to scour the logs to find the log entries and start tracking down the error. There are various ways to make this process easier. One way is to use some variation of the C# code below:

var ulsLogEntries = new SPULSRetriever(
      300, 1000, DateTime.Now.AddMinutes(-180)).GetULSEntries(new Guid(_correlationId));

The SPULSRetriever class is part of the Microsoft.SharePoint.Diagnostics namespace and allows you to look up log entries for a specific correlation id. There is limited SDK documentation here:

In the example above, the _correlationId variable is created earlier in the code as a string and converted to a Guid before being passed into the GetULSEntries as a parameter. The GetULSEntries method returns a collection of LogFileEntry members. The LogFileEntry members contain the properties for a single log entry.

You can then iterate through the collection and display the log entries in whatever fashion you like. An example of how you could use this is to create an application page available to the support team that allows them to input a correlation id and capture the appropriate log entries. Another possibility is just to add something to the various error pages that automatically sends the log to the support team when a user encounters an error.

Have fun! As always, let me know if you have any comments or feedback.