Writing to the SharePoint Trace Log in your code

Updated: You should not register the trace provider on every request.  Use a singleton to check for registration.

Found a great example on how to write to the SharePoint trace log on msdn.  http://msdn2.microsoft.com/en-us/library/aa979522.aspx.  This is very helpful for doing application instrumentation.  Although there are many apis for doing this in .NET very cool to be able to have all the info in one place for the product.  Additionally here's some sample code for correlating traces together in httprequests. 

           string product = "Trace Provider";
           string category = "Runtime";
           string exeName = "SharePoint TraceWriter";
           string message = string.Concat("Time{", DateTime.Now.ToLongTimeString(), "} :: Message{", message, "}");

           //Get correlation string
           Guid guid = Guid.Empty;
           object guidObject = null ;
           if (HttpContext.Current != null)
               guidObject = HttpContext.Current.Items["TraceGuid"];
           if (guidObject == null)
               guid = Guid.NewGuid();
               HttpContext.Current.Items.Add("TraceGuid", guid);
               guid = (Guid)guidObject;

                //Write to sharepoint trace
                TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.Monitorable, guid, exeName, product, category, message);

Skip to main content