/// <summary> /// Write error to file /// </summary> /// <exception cref="ArgumentNullException"> /// When exceptionDetails is null. /// </exception> /// <param name="exceptionDetails">Details of exception</param> private void WriteToLogFile(ExceptionDetails exceptionDetails) { if (exceptionDetails == null) { throw new ArgumentNullException(nameof(exceptionDetails)); } string errorFileFullName = Path.Combine(LogFolderPath, string.Format("ErrorLog_{0}.txt", DateTime.Now.ToString("ddMMyyyy"))); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.Append("\n-----------------------------------------------------------------------\n"); messageBuilder.AppendFormat("Method name: {0}\n", exceptionDetails.MethodName); messageBuilder.AppendFormat("Special ID: {0}\n", exceptionDetails.SpecialID); messageBuilder.AppendFormat("Error message:\n{0}\n", exceptionDetails.ErrorMessage); messageBuilder.AppendFormat("Note: {0}\n", exceptionDetails.Note); messageBuilder.AppendFormat("Error date: {0}\n", exceptionDetails.ErrorDate.ToString("dd.MM.yyyy HH:mm:ss")); messageBuilder.AppendFormat("StackTrace:\n{0}\n", exceptionDetails.StackTrace); messageBuilder.Append("\n=======================================================================\n"); using (StreamWriter writer = new StreamWriter(errorFileFullName, true)) { writer.Write(messageBuilder.ToString()); writer.Flush(); } }
/// <summary> /// Write details of exception to log. /// </summary> /// <exception cref="InvalidOperationException"> /// When EventLog and logFolder. /// </exception> /// <param name="exceptionDetails">Details of exception.</param> public void Log(ExceptionDetails exceptionDetails) { if (EventLog == null && LogFolderPath == null) { throw new InvalidOperationException( "One of EventLog or logFolderLocation must be specified."); } if (EventLog != null) { WriteToWindowsLog(exceptionDetails); } else if (!string.IsNullOrEmpty(LogFolderPath)) { WriteToLogFile(exceptionDetails); } }
/// <summary> /// Write info to windows event log /// </summary> /// <exception cref="ArgumentNullException"> /// When exceptionDetails is null. /// </exception> /// <param name="exceptionDetails">Details of exception</param> private void WriteToWindowsLog(ExceptionDetails exceptionDetails) { if (exceptionDetails == null) { throw new ArgumentNullException(nameof(exceptionDetails)); } if (exceptionDetails != null) { StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendFormat("Method name: {0}\n", exceptionDetails.MethodName); strBuilder.AppendFormat("Special ID: {0}\n", exceptionDetails.SpecialID); strBuilder.AppendFormat("Error message:\n{0}\n", exceptionDetails.ErrorMessage); strBuilder.AppendFormat("Note: {0}\n", exceptionDetails.Note); strBuilder.AppendFormat("StackTrace:\n{0}\n", exceptionDetails.StackTrace); EventLog.WriteEntry(strBuilder.ToString(), System.Diagnostics.EventLogEntryType.Error); } }