web analytics

SharePoint 2010 ULS Logging C# Code

Here is an excellent piece of code to enable you guys out there to specify ULS log entries in SharePoint 2010:

 

public static void LogULS(TraceSeverity level, string message)
{
string traceSeverityName = null;
string eventSeverityName = “None”;
uint tag = 123;
string area = “Custom Area”;
string categoryName = “Custom Category”;

// ** Map the SP2007 TraceSeverity Enum to the SP2010 ones
switch (level)
{
case TraceSeverity.High:
case TraceSeverity.Medium:
case TraceSeverity.Monitorable:
case TraceSeverity.Unexpected:
traceSeverityName = “Unexpected”;
break;
case TraceSeverity.Verbose:
case TraceSeverity.VerboseEx:
traceSeverityName = “Medium”;
break;
default:
// ** Anything else is mapped 1:1
traceSeverityName = level.ToString();
break;
}

// ** Load the SharePoint 2010 version of Microsoft.SharePoint
Assembly assembly = Assembly.Load(“Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”);

// ** Get SPDiagnosticsService.Local
Type spDiagnosticsServiceType = assembly.GetType(“Microsoft.SharePoint.Administration.SPDiagnosticsService”);
object service = spDiagnosticsServiceType.GetProperty(“Local”, BindingFlags.Static | BindingFlags.Public).GetValue(
Activator.CreateInstance(spDiagnosticsServiceType), null);

// ** Get the correct enum value
Type eventSeverityType = assembly.GetType(“Microsoft.SharePoint.Administration.EventSeverity”);
object eventSeverity = eventSeverityType.GetField(eventSeverityName).GetValue(null);
Type traceSeverityType = assembly.GetType(“Microsoft.SharePoint.Administration.TraceSeverity”);
object traceSeverity = traceSeverityType.GetField(traceSeverityName).GetValue(null); ;

// ** Create a new DiagnosticsCategory
Type diagnosticsCategoryType = assembly.GetType(“Microsoft.SharePoint.Administration.SPDiagnosticsCategory”);
Object diagnosticsCategory = Activator.CreateInstance(diagnosticsCategoryType, new Object[] { categoryName,
traceSeverity, eventSeverity});

// ** Set the area
Type diagnosticsAreaType = assembly.GetType(“Microsoft.SharePoint.Administration.SPDiagnosticsArea”);
Object diagnosticsArea = Activator.CreateInstance(diagnosticsAreaType, new Object[] { area, null });
diagnosticsCategoryType.GetProperty(“Area”).SetValue(diagnosticsCategory, diagnosticsArea, null);

// ** Execute the WriteTrace method
spDiagnosticsServiceType.GetMethod(“WriteTrace”).Invoke(service, new object[] { tag, diagnosticsCategory,
traceSeverity, message, null });
}

 

enJoY!

Site last updated September 9, 2014 @ 7:09 pm; This content last updated September 21, 2012 @ 7:45 pm