Thursday, December 10, 2015

SharePoint Custom ULS Logging

Here is a working code snippet (C# class) to write custom errors or logs to ULS log.

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;

namespace CustomLogging
{
    class LoggingService : SPDiagnosticsServiceBase
    {
        public static string diagnostcAreaName = "CustomLogging";
        public static string errorPrefix = "CustomLogging: ";

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

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
            {
                new SPDiagnosticsArea(diagnostcAreaName, new List<SPDiagnosticsCategory>
                {
                    new SPDiagnosticsCategory("CustomLogging", TraceSeverity.Unexpected, EventSeverity.Error)
                })
            };

            return areas;
        }

        public static void LogError(string message, EventSeverity eventSeverity)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                SPDiagnosticsService diagnosticService = SPDiagnosticsService.Local;
                diagnosticService.WriteTrace(0, new SPDiagnosticsCategory(diagnostcAreaName, TraceSeverity.Monitorable, eventSeverity),
                   TraceSeverity.Monitorable, errorPrefix + "{0}", new object[] { message });
            });

        }
    }
}

An entry to ULS logs can be written using the below snippet with make use of the above class.
try
{
    //Business logic
}
catch (Exception ex)
{
    LoggingService.LogError(ex.Message + " " + ex.StackTrace + "\r" + ex.Source, (EventSeverity)EventSeverity.Information);
}

No comments:

Post a Comment