Friday, May 4, 2012

SharePoint, How to Implement Logs in my SharePoint Code Easily..

Hi everyone, today I am going to discuss a very important topic of Implementing Logs in SharePoint Code.

As per the scenario the SharePoint Logs which code generates get stores in the 14 hive folder at location:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS

If you try to see this then you can find logs which SharePoint code creates, and also usage reports, next you can use tools like SharePoint Log Viewer to have a Look into these.

So how can we write these logs in our Customizations?

Many People have their own thoughts on Logging; I have myself used several approaches like:
1) Use a text file, deploy it to the Layouts folder and then write the logs into it, benefit with this is we can view these logs from any SharePoint Site url.

2)Use a Custom List on the Specific SharePoint Site  and implement Logging into it.

3)Use SPDiagnosticsServiceBase class  of Microsoft.SharePoint.Administration to create logs in the SharePoint 14 hive folder, the out of box and generic Way.

Here we are going to discuss the general and best approach, approach number 3 as mentioned above.

Tasks we will do:
1)Create a Utility Logger class which inherits from SPDiagnosticsServiceBase.

2)Create a Console Application which will generate the Logs using our Logger.cs  Class.

We will inherit the SPDiagnosticsServiceBase class:
I am trying to re-use the code written here:  SPDiagnosticsServiceBase

Step:1)Code Logger.cs Class.

2) Code for the Console Application/In our Custom Code of SharePoint Solutions:

Finally we can use SharePoint Log Viewer to View the Logs
SharePoint Log Viewer.