Monday, March 15, 2010

Logging 101

I think a decent logging infrastructure is a must-have for software development. So, when I started doing SharePoint work, I searched for the basics. The info's out there, but it's scattered. Here's what I've pulled together.

Reading The Logs

SharePoint 2007 writes its logs to the LOGS folder under the 12 Hive. The logs are text files in Unified Logging Service (ULS) format. The file names are servername-yyyymmdd-hhmm.log. The timestamp is the file creation time.

The first time you look in the LOGS folder, you'll see a lot of logs - probably more than you want on a development machine. Fortunately, you can easily change that. Look at the "Throttle Logging" topic here. My log settings look like this:

Media_http4bpblogspot_kiamy

These settings tell SharePoint to give me as much detail as possible about the last hour, and split it across two log files.

You can read the logs with a text editor, but that's painful. Instead, go to codeplex and search for sharepoint log viewer. You'll find all sorts of freebies. Some are stand-alone; some extend SharePoint's Central Administration site. I'm using the stand-alone SharePoint LogViewer.

Writing To The Logs

This works in MOSS 2007, but not in vanilla WSS: first, make sure your project has a reference to Microsoft.Office.Server - in the Add Reference dialog, browse to C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions12ISAPIMicrosoft.Office.Server.dll.

Then you can use PortalLog.LogString() to write to the SharePoint logs:

...
using Microsoft.Office.Server.Diagnostics;
...
public override void ItemAdded(SPItemEventProperties properties)
{
   string thisClass = this.GetType().Name;
   PortalLog.LogString(thisClass + ": this works");
   PortalLog.LogString("{0}: this works too", thisClass);
   PortalLog.LogString("{0}: and this {1} works",
       new string[] {thisClass, "also"});
}
...

You can use LogViewer to verify that the logging is working. Starting each message with the class name makes it easy to filter:


Media_http4bpblogspot_ybdcj


A couple of caveats:

Officially, PortalLog.LogString() is Microsoft-internal and "not intended to be used directly from your code." This doesn't seem to be stopping anybody.

In some cases, you may also want to write to the Windows Event Log, even if this means you're double-logging. Some organizations have automated monitoring software that scans the Event Log. If it notices your SharePoint application error message ASAP, that's a good thing.

No comments:

Post a Comment