Log exception in sharepoint using Windows event Log

When ever any exception occurs in sharepoint it will be logged in Logs directory of sharepoint. But when ever we are writing the coding solutions it is better to log our exceptions in some place. So, today I want to show, how to log the entry in the windows event viewer.

We will create with an EventLog class. Following is the solution.


public static void LogException(Exception ex)
 {
  try
  {
       SPSecurity.RunWithElevatedPrivileges(delegate()
       {
         if (!EventLog.SourceExists("MySPSource"))
               EventLog.CreateEventSource("MySPSource", "Application");

         EventLog eventLog = new EventLog();
         eventLog.Source = "MySPSource";
         string message = string.Format("Exception Detail: {0}{1}Stack Trace: Exception occurred {2}", ex.Message.Trim(), Environment.NewLine, ex.StackTrace.Trim());
         eventLog.WriteEntry(message, EventLogEntryType.Error);
       });
  }
   catch (Exception)
   {

   }
 }

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s