Friday, 11 January 2013

Write Log File for SharePoint Custom Applications :



To debug the SharePoint Custom Code we need to write logs to inspect whether the code is working fine or not. To create logs create a class file in the SharePoint solution & write the below code in the corresponding class file. Now to access this file in other class files we need to declare the namespace in the file which name is declared in the log file.

namespace Intranet_Logs
{
    public class LogManager
    {
    //Give the path of the file where the logs will be written
       private static string _logFolderPath = “E:\Project_Logs”;

       //Function to write log
       public static void WriteLog(string message)
       {
          using (StreamWriter writer = File.AppendText(_logFolderPath + "\\" + "Log_File_Name.txt"))
         {
           writer.Write("\r\nLog Entry : ");
           writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
           DateTime.Now.ToLongDateString());
           writer.WriteLine("  :");
           if (!string.IsNullOrEmpty(message))
           {                     
              writer.WriteLine("  :{0}", message);
           }
           writer.WriteLine("-------------------------------");
           // Update the underlying file.
           writer.Flush();
           // Close the writer and underlying file.
           writer.Close();
         }
       }
    }
}

No comments:

Post a Comment