Friday 3 June 2011

SharePoint 2010 writing to the ULS log

With SharePoint 2007 there was no out of the box method to write to the ULS log, 2010 however finally remedies this weakness.
SPDiagnosticsService allows you to write to both the ULS log and the Windows Event Log with a simple WriteTrace or WriteEvent call like this:
var diagnosticService = SPDiagnosticsService.Local;
SPDiagnosticsCategory cat = diagnosticService.Areas["SharePoint Foundation"].Categories["General"];
diagnosticService.WriteTrace(1, cat, TraceSeverity.High, "Something interesting happened in {0}", web.Url);
You can specify the TraceLevel to correspond to your settings in SharePoint diagnostics to filter messages based on importance etc. The Areas and Categories correspond to the equivalent settings in Central Administration -> Diagnostic Logging.

If you find yourself using it a lot you might want to consider implementing your own service based on SPDiagnosticsServiceBase, this enable you to set the category to something more meaningful and manage the logging properly through the diagnostics UI in Central Admin. Jürgen Bäurle has already blogged this here so head over and check it out if you're going down that road.

Writing to the event log requires additional permissions to be granted to the registry keys in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog. Access is needed for the account your app pool runs under. If you get errors along the line of
Error: The source was not found, but some or all event logs could not be searched.  Inaccessible logs: Security.    at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly)
then it's probably the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Security key that needs explicit permissions set as well (it doesn't inherit from the parent).

No comments:

Post a Comment