Tuesday, 5 November 2013

Write Custom Log File in SharePoint 2010

 Create new Class file name as(LoggingService.cs) and Add the below code

public class LoggingService : SPDiagnosticsServiceBase
    {
        public static string DiagnosticAreaName = "Portal-Approval Process";
        private static LoggingService _Current;
        public static LoggingService Current
        {
            get
            {
                if (_Current == null)
                {
                    _Current = new LoggingService();
                }

                return _Current;
            }
        }

        private LoggingService()
            : base("Portal-Approval Process Logging Service", SPFarm.Local)
        {

        }

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
        {
            new SPDiagnosticsArea(DiagnosticAreaName, new List<SPDiagnosticsCategory>
            {
                new SPDiagnosticsCategory("Portal - Workflow", TraceSeverity.High, EventSeverity.Error)
            })
        };

            return areas;
        }

        public static void LogError(string categoryName, string errorMessage)
        {
            SPDiagnosticsCategory category = LoggingService.Current.Areas[DiagnosticAreaName].Categories[categoryName];
            LoggingService.Current.WriteTrace(0, category, TraceSeverity.High, errorMessage);
        }
    }

Finally call custom log file in our code, see below example

                try
                {
                    Thread.Sleep(3000);
                    currentItem.SystemUpdate(false);
                }
                catch (Exception ex)
                {
                    LoggingService.LogError("Portal - Workflow", ex.Message);
                }