Monday, 26 May 2014

Programmatically logging to the Sharepoint ULS

Logging helps one to quickly tracks bugs and evaluate the health of the system under development.
SharePoint 2010 allows to log into ULS for our custom code components.
Logging in SharePoint 2010 ULS is quite easy. Using just a few lines of code, you can log info from your custom components:
[StackOverflow answer ]

     try
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                diagSvc.WriteTrace(123456, new SPDiagnosticsCategory("Category_Name_Here",
TraceSeverity.Monitorable, EventSeverity.Error), TraceSeverity.Monitorable,"{0}:{1}", new object[] { "Method_Name", "Error_Message"});
            });
        }
        catch (Exception ex)
        {
        }


Put above code in some method, and whenever you want to log, just call that method by passing suitable parameters.


If you would like to log with your product name, you can create a custom logger class:
using System.Collections.Generic;
using Microsoft.SharePoint.Administration;

namespace Workflow.Common
{
    public class LoggingService : SPDiagnosticsServiceBase
    {
        public static string DiagnosticAreaName = "Workflow";
        private static LoggingService _Current;
        public static LoggingService Current
        {
            get
            {
                if (_Current == null)
                {
                    _Current = new LoggingService();
                }

                return _Current;
            }
        }

        private LoggingService()
            : base("Workflow Logging Service", SPFarm.Local)
        {

        }

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
            {
                new SPDiagnosticsArea(DiagnosticAreaName, new List<SPDiagnosticsCategory>
                {
                    new SPDiagnosticsCategory("Workflow Info", TraceSeverity.Monitorable, EventSeverity.Information),
                    new SPDiagnosticsCategory("Workflow Error", TraceSeverity.Unexpected, EventSeverity.Error)
                })
            };

            return areas;
        }

        public static void LogError(string projectName, string errorMessage, object[] data)
        {
            SPDiagnosticsCategory category = LoggingService.Current.Areas[DiagnosticAreaName].Categories["Workflow Error"];
            LoggingService.Current.WriteTrace(123456, category, TraceSeverity.Unexpected, projectName + " - " + errorMessage, data);
        }
        public static void LogError(string projectName, string errorMessage)
        {
            SPDiagnosticsCategory category = LoggingService.Current.Areas[DiagnosticAreaName].Categories["Workflow Error"];
            LoggingService.Current.WriteTrace(123456, category, TraceSeverity.Unexpected, projectName + " - " + errorMessage);
        }
        public static void LogInformation(string projectName, string errorMessage, object[] data)
        {
            SPDiagnosticsCategory category = LoggingService.Current.Areas[DiagnosticAreaName].Categories["Workflow Info"];
            LoggingService.Current.WriteTrace(123456, category, TraceSeverity.Monitorable, projectName + " - " + errorMessage, data);
        }
        public static void LogInformation(string projectName, string errorMessage)
        {
            SPDiagnosticsCategory category = LoggingService.Current.Areas[DiagnosticAreaName].Categories["Workflow Info"];
            LoggingService.Current.WriteTrace(123456, category, TraceSeverity.Monitorable, projectName + " - " + errorMessage);
        }
    }
}
 Then you can access this class to log your custom information:
try
{
    //your code
}
catch (Exception ex)
{
    LoggingService.LogError("Workflow", ex.Message);
}