using System; using System.Linq; using Abp.Collections.Extensions; using Abp.Dependency; using Abp.Runtime.Validation; using Castle.Core.Logging; namespace Abp.Logging { /// /// This class can be used to write logs from somewhere where it's a hard to get a reference to the . /// Normally, use with property injection wherever it's possible. /// public static class LogHelper { /// /// A reference to the logger. /// public static ILogger Logger { get; private set; } static LogHelper() { Logger = IocManager.Instance.IsRegistered(typeof(ILoggerFactory)) ? IocManager.Instance.Resolve().Create(typeof(LogHelper)) : NullLogger.Instance; } public static void LogException(Exception ex) { LogException(Logger, ex); } public static void LogException(ILogger logger, Exception ex) { var severity = (ex as IHasLogSeverity)?.Severity ?? LogSeverity.Error; logger.Log(severity, ex.Message, ex); LogValidationErrors(logger, ex); } private static void LogValidationErrors(ILogger logger, Exception exception) { //Try to find inner validation exception if (exception is AggregateException && exception.InnerException != null) { var aggException = exception as AggregateException; if (aggException.InnerException is AbpValidationException) { exception = aggException.InnerException; } } if (!(exception is AbpValidationException)) { return; } var validationException = exception as AbpValidationException; if (validationException.ValidationErrors.IsNullOrEmpty()) { return; } logger.Log(validationException.Severity, "There are " + validationException.ValidationErrors.Count + " validation errors:"); foreach (var validationResult in validationException.ValidationErrors) { var memberNames = ""; if (validationResult.MemberNames != null && validationResult.MemberNames.Any()) { memberNames = " (" + string.Join(", ", validationResult.MemberNames) + ")"; } logger.Log(validationException.Severity, validationResult.ErrorMessage + memberNames); } } } }