How to use ULS in SharePoint 2010 for Custom Code Exception Logging?

Posted by venkatx5 on Geeks with Blogs See other posts from Geeks with Blogs or by venkatx5
Published on Thu, 09 Dec 2010 05:47:43 GMT Indexed on 2010/12/09 22:14 UTC
Read the original article Hit count: 396

Filed under:

What is ULS in SharePoint 2010?
ULS stands for Unified Logging Service which captures and writes Exceptions/Logs in Log File(A Plain Text File with .log extension). SharePoint logs Each and every exceptions with ULS. SharePoint Administrators should know ULS and it's very useful when anything goes wrong. but when you ask any SharePoint 2007 Administrator to check log file then most of them will Kill you. Because read and understand the log file is not so easy. Imagine open a plain text file of 20 MB in NotePad and go thru line by line.

Now Microsoft developed a tool "ULS Viewer" to view those Log files in easily readable format. This tools also helps to filter events based on exception priority. You can read on this blog to know in details about ULS Viewer .

Where to get ULS Viewer?
ULS Viewer is developed by Microsoft and available to download for free. URL : http://code.msdn.microsoft.com/ULSViewer/Release/ProjectReleases.aspx?ReleaseId=3308
Note: Eventhought this tool developed by Microsoft, it's not supported by Microsoft. Means you can't support for this tool from Microsoft and use it on your own Risk. By the way what's the risk in viewing Log Files?!

How to use ULS in SharePoint 2010 Custom Code?
ULS can be extended to use in user solutions to log exceptions. In Detail, Developer can use ULS to log his own application errors and exceptions on SharePoint Log files. So now all in Single Place (That's why it's called "Unified Logging"). Well in this article I am going to use Waldek's Code (Reference Link). However the article is core and am writing container for that (Basically how to implement the code in Detail). Let's see the steps.

  1. Open Visual Studio 2010 -> File -> New Project -> Visual C# -> Windows -> Class Library -> Name : ULSLogger (Make sure you've selected .net Framework 3.5)
    Create Class Library Project


     
  2. In Solution Explorer Panel, Rename the Class1.cs to LoggingService.cs

     
  3. Right Click on References -> Add Reference -> Under .Net tab select "Microsoft.SharePoint"
    Add Microsoft.SharePoint Reference


     
  4. Right Click on the Project -> Properties. Select "Signing" Tab -> Check "Sign the Assembly".

     
  5. In the below drop down select <New> and enter "ULSLogger", uncheck the "Protect my key with a Password" option.
     
  6. Now copy the below code and paste. (Or Just refer.. :-) )

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    using System.Runtime.InteropServices;
    namespace ULSLogger
    {
    public class LoggingService : SPDiagnosticsServiceBase
    {
    public static string vsDiagnosticAreaName = "Venkats SharePoint Logging Service";
    public static string CategoryName = "vsProject";
    public static uint uintEventID = 700; // Event ID
    private static LoggingService _Current;
    public static LoggingService Current
    {
     get
      {
       if (_Current == null)
        {
          _Current =
    new LoggingService();
        }
       return _Current;
      }
    }
    private LoggingService()
    :
    base("Venkats SharePoint Logging Service", SPFarm.Local)
    {}
    protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
    {
    List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
     {
      new SPDiagnosticsArea(vsDiagnosticAreaName, new List<SPDiagnosticsCategory>
       {
        new SPDiagnosticsCategory(CategoryName, TraceSeverity.Medium, EventSeverity.Error)
       })
      };
    return areas;
    }
    public static string LogErrorInULS(string errorMessage)
    {
    string strExecutionResult = "Message Not Logged in ULS. ";
    try
     
    {
      SPDiagnosticsCategory category = LoggingService.Current.Areas[vsDiagnosticAreaName].Categories[CategoryName];
      LoggingService.Current.WriteTrace(uintEventID, category, TraceSeverity.Unexpected, errorMessage);
      strExecutionResult =
    "Message Logged";
    }
    catch (Exception ex)
    {
     strExecutionResult += ex.Message;
    }
    return strExecutionResult;
    }
    public static string LogErrorInULS(string errorMessage, TraceSeverity tsSeverity)
    {
    string strExecutionResult = "Message Not Logged in ULS. ";
    try
     {
     
    SPDiagnosticsCategory category = LoggingService.Current.Areas[vsDiagnosticAreaName].Categories[CategoryName];
     LoggingService.Current.WriteTrace(uintEventID, category, tsSeverity, errorMessage);
     strExecutionResult =
    "Message Logged";
     }
    catch (Exception ex)
     {
      strExecutionResult += ex.Message;
      }
    return strExecutionResult;
     }
    }
    }

     
  7. Just build the solution and it's ready to use now.

This ULS solution can be used in SharePoint Webparts or Console Application. Lets see how to use it in a Console Application.
SharePoint Server 2010 must be installed in the same Server or the application must be hosted in SharPoint Server 2010 environment. The console application must be set to "x64" Platform target.
 

  1. Create a New Console Application. (Visual Studio -> File -> New Project -> C# -> Windows -> Console Application)
  2. Right Click on References -> Add Reference -> Under .Net tab select "Microsoft.SharePoint"
  3. Open Program.cs add "using Microsoft.SharePoint.Administration;"
  4. Right Click on References -> Add Reference -> Under "Browse" tab select the "ULSLogger.dll" which we created first. (Path : ULSLogger\ULSLogger\bin\Debug\)
  5. Right Click on Project -> Properties -> Select "Build" Tab -> Under "Platform Target" option select "x64".
  6. Open the Program.cs and paste the below code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.Administration;
    using ULSLogger;

    namespace ULSLoggerClient
    {

      class Program
      {
       static void Main(string[] args)
        {

         Console.WriteLine("ULS Logging Started.");

         string strResult = LoggingService.LogErrorInULS("My Application is Working Fine.");
         Console.WriteLine("ULS Logging Info. Result : " + strResult);

         string strResult = LoggingService.LogErrorInULS("My Application got an Exception.", TraceSeverity.High);
         Console.WriteLine("ULS Logging Waring Result : " + strResult);

         Console.WriteLine("ULS Logging Completed.");
         Console.ReadLine();
        }
      }
    }


  7. Just build the solution and execute. It'll log the message on the log file. Make sure you are using Farm Administrator User ID.
    ULS Logging Console Application


You can play with Message and TraceSeverity as required. Now Open ULS Viewer -> File -> Open From -> ULS -> Select First Option to open the default ULS Log.

Select ULS Log File



It's Uls RealTime and will show all log entries in readable table format. Right Click on a row and select "Filter By This Item". Select "Event ID" and enter value "700" that we used in the application.

ULS Log Viewer - Log Filter



Click Ok and now you'll see the Exceptions/Logs which logged by our application.
 

ULS Log Viewer



If you want to see High Priority Messages only then Click Icons except Red Cross Icon on the Toolbar. The tooltip will tell what's the icons used for.

 

© Geeks with Blogs or respective owner