Create a custom entity to save all exception details occurs in Plugins and other CRM related applications.
Entity Name: ls_errordetails
Attributes: Name, Exception Type, Exception Details, Exception Message
Call below method LogErrorInCRM() in your catch blocks to save exception details.
// This method is used to log error details into CRM entity(ls_errordetails) private void LogErrorInCRM(IOrganizationService service, Exception ex) { try { Entity ls_errorDetails = new Entity("ls_errordetails"); ls_errorDetails["ls_name"] = Assembly.GetExecutingAssembly().GetName().Name; ls_errorDetails["ls_exceptiontype"] = ex.GetType().Name; if (ex.InnerException != null) ls_errorDetails["ls_exceptiondetails"] = ex.StackTrace + "\n" + ex.InnerException.ToString(); else ls_errorDetails["ls_exceptiondetails"] = ex.StackTrace; ls_errorDetails["ls_exceptionmessage"] = ex.Message; Guid errorID = service.Create(ls_errorDetails); if (errorID == Guid.Empty) { throw new InvalidPluginExecutionException("Unable to save Error details in CRM " + ex.Message, ex); } } catch (Exception excn) { //Log error details into text file,if there is any exception while saving error details into CRM LogErrorInTextFile(ex); LogErrorInTextFile(excn); } } // This method is used to log error details into Text file private static bool LogErrorInTextFile(Exception objException) { string strException = string.Empty; StreamWriter sw; string strPathName; bool bReturn = false; try { strPathName = GetLogFilePath(); sw = new StreamWriter(strPathName, true); sw.WriteLine("Source : " + objException.Source.ToString().Trim()); sw.WriteLine("Method : " + objException.TargetSite.Name.ToString()); sw.WriteLine("Date : " + DateTime.Now.ToLongTimeString()); sw.WriteLine("Time : " + DateTime.Now.ToShortDateString()); sw.WriteLine("Computer : " + Dns.GetHostName().ToString()); sw.WriteLine("Error : " + objException.Message.ToString().Trim()); sw.WriteLine("Stack Trace : " + objException.StackTrace.ToString().Trim()); sw.WriteLine("^^-------------------------------------------------------------------^^"); sw.Flush(); sw.Close(); bReturn = true; } catch (Exception) { bReturn = false; } return bReturn; } private static string GetLogFilePath() { String strLogFilePath = "C:\\ErrorLog\\PluginErrorLog.txt"; try { // if exists, return the path if (File.Exists(strLogFilePath) == true) return strLogFilePath; //create a text file else { if (CheckDirectory(strLogFilePath) == false) return string.Empty; FileStream fs = new FileStream(strLogFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); fs.Close(); } return strLogFilePath; } catch (Exception) { return string.Empty; } } private static bool CheckDirectory(string strLogPath) { try { int nFindSlashPos = strLogPath.Trim().LastIndexOf("\\"); string strDirectoryname = strLogPath.Trim().Substring(0, nFindSlashPos); if (false == Directory.Exists(strDirectoryname)) Directory.CreateDirectory(strDirectoryname); return true; } catch (Exception) { return false; } }