Writing to the SharePoint Trace Log in your code

Published 18 November 07 11:24 PM | shawnfel 

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);
           }
           else
           {
               guid = (Guid)guidObject;
           }

           System.Diagnostics.Debug.WriteLine(message);
           System.Diagnostics.Trace.WriteLine(message);
           SPSecurity.RunWithElevatedPrivileges(
            delegate()
            {
                //Write to sharepoint trace
                TraceProvider.RegisterTraceProvider();
                TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.Monitorable, guid, exeName, product, category, message);
                TraceProvider.UnregisterTraceProvider();
            }
          );

Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Web 2.0 - Social Media - Internet News - Blogging » Sharepoint Logging said on November 18, 2007 7:33 PM:

PingBack from http://hyiplive.org/sharepoint-logging

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

About shawnfel

I'm a consultant for Microsoft Consulting Services specializing in SharePoint and BI Products. I've been with Microsoft since 03/2006. The opinions expressed herein are my own personal opinions and do not represent my employer's views in anyway.

Search

This Blog

Syndication

Page view tracker