LogHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Linq;
  3. using Abp.Collections.Extensions;
  4. using Abp.Dependency;
  5. using Abp.Runtime.Validation;
  6. using Castle.Core.Logging;
  7. namespace Abp.Logging
  8. {
  9. /// <summary>
  10. /// This class can be used to write logs from somewhere where it's a hard to get a reference to the <see cref="ILogger"/>.
  11. /// Normally, use <see cref="ILogger"/> with property injection wherever it's possible.
  12. /// </summary>
  13. public static class LogHelper
  14. {
  15. /// <summary>
  16. /// A reference to the logger.
  17. /// </summary>
  18. public static ILogger Logger { get; private set; }
  19. static LogHelper()
  20. {
  21. Logger = IocManager.Instance.IsRegistered(typeof(ILoggerFactory))
  22. ? IocManager.Instance.Resolve<ILoggerFactory>().Create(typeof(LogHelper))
  23. : NullLogger.Instance;
  24. }
  25. public static void LogException(Exception ex)
  26. {
  27. LogException(Logger, ex);
  28. }
  29. public static void LogException(ILogger logger, Exception ex)
  30. {
  31. var severity = (ex as IHasLogSeverity)?.Severity ?? LogSeverity.Error;
  32. logger.Log(severity, ex.Message, ex);
  33. LogValidationErrors(logger, ex);
  34. }
  35. private static void LogValidationErrors(ILogger logger, Exception exception)
  36. {
  37. //Try to find inner validation exception
  38. if (exception is AggregateException && exception.InnerException != null)
  39. {
  40. var aggException = exception as AggregateException;
  41. if (aggException.InnerException is AbpValidationException)
  42. {
  43. exception = aggException.InnerException;
  44. }
  45. }
  46. if (!(exception is AbpValidationException))
  47. {
  48. return;
  49. }
  50. var validationException = exception as AbpValidationException;
  51. if (validationException.ValidationErrors.IsNullOrEmpty())
  52. {
  53. return;
  54. }
  55. logger.Log(validationException.Severity, "There are " + validationException.ValidationErrors.Count + " validation errors:");
  56. foreach (var validationResult in validationException.ValidationErrors)
  57. {
  58. var memberNames = "";
  59. if (validationResult.MemberNames != null && validationResult.MemberNames.Any())
  60. {
  61. memberNames = " (" + string.Join(", ", validationResult.MemberNames) + ")";
  62. }
  63. logger.Log(validationException.Severity, validationResult.ErrorMessage + memberNames);
  64. }
  65. }
  66. }
  67. }