LoggerExtensions.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using Avalonia.Data;
  3. namespace Avalonia.Logging
  4. {
  5. internal static class LoggerExtensions
  6. {
  7. public static void LogIfError(
  8. this BindingNotification notification,
  9. object source,
  10. AvaloniaProperty property)
  11. {
  12. if (notification.ErrorType == BindingErrorType.Error)
  13. {
  14. if (notification.Error is AggregateException aggregate)
  15. {
  16. foreach (var inner in aggregate.InnerExceptions)
  17. {
  18. LogError(source, property, inner);
  19. }
  20. }
  21. else
  22. {
  23. LogError(source, property, notification.Error);
  24. }
  25. }
  26. }
  27. private static void LogError(object source, AvaloniaProperty property, Exception e)
  28. {
  29. var level = LogEventLevel.Warning;
  30. if (e is BindingChainException b &&
  31. !string.IsNullOrEmpty(b.Expression) &&
  32. string.IsNullOrEmpty(b.ExpressionErrorPoint))
  33. {
  34. // The error occurred at the root of the binding chain: it's possible that the
  35. // DataContext isn't set up yet, so log at Information level instead of Warning
  36. // to prevent spewing hundreds of errors.
  37. level = LogEventLevel.Information;
  38. }
  39. Logger.Log(
  40. level,
  41. LogArea.Binding,
  42. source,
  43. "Error in binding to {Target}.{Property}: {Message}",
  44. source,
  45. property,
  46. e.Message);
  47. }
  48. }
  49. }