Log SharePoint Exception via SPDiagnosticsService

// Need namespace => using Microsoft.SharePoint.Administration;
public static void SPTraceLogError(this Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("My Category Name",
            TraceSeverity.High, EventSeverity.Error),
            TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }

public static void SPTraceLogError(this Exception ex , string keyNote)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("My Category Name",
            TraceSeverity.High, EventSeverity.Error),
            TraceSeverity.Unexpected,keyNote+" : "+ ex.Message, ex.StackTrace);
        }
Example:
                    try
                    {
                      // My Code 
                    }
                    catch (Exception ex)
                    {
                        ex.SPTraceLogError();
                        // OR
                        //ex.SPTraceLogError("My Method Name");
                    }

Description

Log SharePoint Exception via SPDiagnosticsService for Debugging (result : 0000 Unexpected My Method Name : Attempted to divide by zero. 220da18b-1517-4230-90ac-91117ceaea33 )

Details

Double click on the code to select all.

 

;