This post is migrated from previous hosting provider. There are still some issues with old posts. Please make a comment on this post with any issues.

Working with SharePoint 2010 Correlation ID in PowerShell and code

Tags: SharePoint 2010, SharePoint 2010 Web Parts in Action

SharePoint 2010 the logging has been extended with a new Correlation ID which is unique for each request or operation. The Correlation ID makes it very easy to track down any unexpected errors since you can search for the id in the trace logs. This unique ID is also maintained between servers for instance when making a call to a service application.

SharePoint 2010 error message The SharePoint 2010 error page also shows this Correlation ID so that any end-users seeing the message can contact support and give the the Correlation ID. Using the ID the support team can then track down the cause of the error.

To Search for the Correlation ID in the Trace Logs the Windows Suisse Knife called Notepad can be used but a far better, faster and more 2010:ish approach is to use the Get-SPLogEvent cmdlet.

Get-SPLogEvent

The Get-SPLogEvent cmdlet is used to search the local Trace logs or merged (Merge-SPLogFile) logs. To search for a Correlation ID the following PowerShell command line can be used.

Get-SPLogEvent |
?{$_.Correlation -eq "2872bd2d-a0a5-4cac-b218-f504a7d2a4c5"} |
ft Category, Message -Autosize

This will search the Trace Logs for the Correlation ID and output the category and message of any records in the log related to the id.

Correlation ID in code

If you have error handling in your code and perhaps logging information manually to the Trace Logs you can get the current Correlation ID by using a native method called EventActivityIdControl() found in advapi32.dll. You have to import the method like this:

[DllImport("advapi32.dll")]
public static extern uint EventActivityIdControl(uint controlCode, ref Guid activityId);
public const uint EVENT_ACTIVITY_CTRL_GET_ID = 1;

And then use it in code like below, perhaps in a catch statement

Guid g = Guid.Empty;
EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, ref g);
this.Controls.Add(new Label { 
    Text = string.Format("An error occurred with correlation id {0}", g)
});

Pretty neat! If you like it you can find even more information on the topic in my upcoming book SharePoint 2010 Web Parts in Action.

6 Comments

Comments have been disabled for this content.

AWS Tracker

About Wictor...

Wictor Wilén is a Director and SharePoint Architect working at Connecta AB. Wictor has achieved the Microsoft Certified Architect (MCA) - SharePoint 2010, Microsoft Certified Solutions Master (MCSM) - SharePoint  and Microsoft Certified Master (MCM) - SharePoint 2010 certifications. He has also been awarded Microsoft Most Valuable Professional (MVP) for four consecutive years.

And a word from our sponsors...

SharePoint 2010 Web Parts in Action