Pages

Wednesday, December 23, 2009

Logging data to the 12 hive log

(the article was "copy-pasted" from http://pointstoshare.spaces.live.com/Blog/cns!AEC42F315B4528B0!3056.entry?wa=wsignin1.0&ppud=4&sa=58367829. In case you don't have or you don't want to sign in MDSN)

This is something that has come up for me a few times in the past - when you are writing something for SharePoint, how do you go about logging what your custom code is doing? I have been on projects in the past that have written custom web services to get logging details, others that have recorded data to the event log, and even a couple of don't log, they just spit data out to the screen when something goes wrong. So if you find yourself wondering how you should do you logging, then you need to be introduced to the PortalLog class.

Microsoft.Office.Server.Diagnostics.PortalLog is the class, and it is in the Microsoft.Office.Server.dll file. This class will allow you to log your debug information straight to the 12 hive logs, just like every other SharePoint component. This has the obvious bonus of meaning that all your logging information is in the one place. The big draw back though is that it is often easy to loose stuff in those log files (they can get quite large) but I personally think the idea of knowing that if something goes wrong it gets logged to the one spot is a pretty decent trade off for that, especially when you see how easy it is to do this - its one line of code!

1: PortalLog.WriteString("My error is {0}", ex.message);

That's it! The WriteString() method is used just like a String.Format() method, where you can put as many parameters on the end as you need to get your message formatted right. Also you can use PortalLog.DebugWriteString() does the same thing, but it allows you to specify the level of the item you are logging (either Critical, Error, Information or Verbose).

There are other ways to write to the SharePoint ULS (unified logging service), but from what I have seen they all involve using some unmanaged code, which is far more effort than this simple one line solution, so why not consider giving this one a go in your next piece of code.

No comments:

Post a Comment