SharePoint Logging class

12/05/2015 11:34

Here is the content of Logging.cs file, basic SharePoint logging

- Add new class to your project, name it Logging.cs

- Copy following text into it (replace only class definition, leave your namespace as it is)


using Microsoft.SharePoint.Administration;
using System;

namespace MyProject.Codebehind
{
    public static class Logging
    {
        private static string loggingCategoryName = "My Project Category Name";

        public static void LogInformation(string filename, string method, string message)
        {
            string writeMessage = string.Format("Message: {0}, FileName: {1}, Method: {2}", message, filename, method);
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(loggingCategoryName, TraceSeverity.Monitorable, EventSeverity.Information), TraceSeverity.Monitorable, writeMessage, new object[] { "" });
        }

        public static void LogError(string filename, string method, Exception exception)
        {
            string message = string.Format("Message: {0}, FileName: {1}, Method: {2}, Exception: {3}", exception.Message, filename, method, exception.ToString());
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(loggingCategoryName, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, message, new object[] { "" });
        }

public static void LogInformation(string message)
{
 SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(LoggingCategoryName, TraceSeverity.Monitorable, EventSeverity.Information), TraceSeverity.Monitorable, message, new object[] { "" });
}

public static void LogError(Exception exception)
{
 var message = exception.Message;
 var stackTrace = exception.StackTrace;
 SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(LoggingCategoryName, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, message, new object[] { "" });
 SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(LoggingCategoryName, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, stackTrace, new object[] { "" });
}


    }
}