LogHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Text;
  3. namespace MediaBrowser.Model.Logging
  4. {
  5. /// <summary>
  6. /// Class LogHelper
  7. /// </summary>
  8. public static class LogHelper
  9. {
  10. /// <summary>
  11. /// Gets the log message.
  12. /// </summary>
  13. /// <param name="exception">The exception.</param>
  14. /// <returns>StringBuilder.</returns>
  15. public static StringBuilder GetLogMessage(Exception exception)
  16. {
  17. if (exception == null)
  18. {
  19. throw new ArgumentNullException("exception");
  20. }
  21. var messageText = new StringBuilder();
  22. messageText.AppendLine(exception.ToString());
  23. messageText.AppendLine(exception.GetType().FullName);
  24. LogExceptionData(messageText, exception);
  25. messageText.AppendLine(exception.StackTrace ?? "No Stack Trace Available");
  26. // Log the InnerExceptions, if any
  27. AppendInnerExceptions(messageText, exception);
  28. messageText.AppendLine(string.Empty);
  29. return messageText;
  30. }
  31. /// <summary>
  32. /// Appends the inner exceptions.
  33. /// </summary>
  34. /// <param name="messageText">The message text.</param>
  35. /// <param name="e">The e.</param>
  36. private static void AppendInnerExceptions(StringBuilder messageText, Exception e)
  37. {
  38. var aggregate = e as AggregateException;
  39. if (aggregate != null && aggregate.InnerExceptions != null)
  40. {
  41. foreach (var ex in aggregate.InnerExceptions)
  42. {
  43. AppendInnerException(messageText, ex);
  44. AppendInnerExceptions(messageText, ex);
  45. }
  46. }
  47. else if (e.InnerException != null)
  48. {
  49. AppendInnerException(messageText, e.InnerException);
  50. AppendInnerExceptions(messageText, e.InnerException);
  51. }
  52. }
  53. /// <summary>
  54. /// Appends the inner exception.
  55. /// </summary>
  56. /// <param name="messageText">The message text.</param>
  57. /// <param name="e">The e.</param>
  58. private static void AppendInnerException(StringBuilder messageText, Exception e)
  59. {
  60. messageText.AppendLine("InnerException: " + e.GetType().FullName);
  61. messageText.AppendLine(e.ToString());
  62. LogExceptionData(messageText, e);
  63. if (e.StackTrace != null)
  64. {
  65. messageText.AppendLine(e.StackTrace);
  66. }
  67. }
  68. /// <summary>
  69. /// Logs the exception data.
  70. /// </summary>
  71. /// <param name="messageText">The message text.</param>
  72. /// <param name="e">The e.</param>
  73. private static void LogExceptionData(StringBuilder messageText, Exception e)
  74. {
  75. foreach (var key in e.Data.Keys)
  76. {
  77. messageText.AppendLine(key + ": " + e.Data[key]);
  78. }
  79. }
  80. }
  81. }