Custom Logging in SharePoint 2010

On hive 14, we could find logging file from SharePoint 2010. It writes every event that running on server. By looking this file, we might find any error which cause problem on our site. ULSViewer is small tool which help us to read log file easier. Error might bring us to error-page contains correlation ID, sequence number which we can use to identify what problem cause it.

For some reasons, I need to have my own log such as saving exception messages, stack trace, and any information we can store . And it could be done easily, because start in Sharepoint 2010, developer might develop custom logging solution.

Since we need to override class SPDiagnosticsServiceBase, add namespace “Microsoft.SharePoint.Administration” to your solution first.

public class LoggingService : SPDiagnosticsServiceBase
{
    static readonly string productServiceName = "Contoso Product";
    static readonly string categoryName = "Web Parts";
    static LoggingService _logCurrent;

    static LoggingService LogCurrent
    {
       get
       {
         if( _logCurrent == null )
         {
           _logCurrent = new LoggingService();
         }
         return _logCurrent;
       }
    }

    private LoggingService():base("Contoso Logging", SPFarm.Local)
    {
    }

    protected override IEnumerable ProvideAreas()
    {
       List areas = new List
       {
          new SPDiagnosticsArea(productServiceName, new List
          {
             new SPDiagnosticsCategory(categoryName, TraceSeverity.Unexpected, EventSeverity.Error)})
          };

       return areas;
    }

    public static void LogError( string mainArea, string errorMessage )
    {
        errorMessage = '"' + mainArea + '"' + " : " + errorMessage;
        SPDiagnosticsCategory category = LoggingService.LogCurrent.Areas[ productServiceName ].Categories[ categoryName ];
        LoggingService.LogCurrent.WriteTrace( 0, category, TraceSeverity.Unexpected, errorMessage );
    }
}

Then to utilize our custom logging, add method LogError to your code

try
{
  Item.Update();
}
catch (Exception ex)
{
   LoggingService.LogError("Update Item", ex.ToString());
}

Simple isn’t it? šŸ˜€

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s