From 01389bc1d6da9e03f1aa49551af99062b21e1055 Mon Sep 17 00:00:00 2001 From: Ivan Maximov Date: Tue, 23 Jan 2024 20:36:37 +0300 Subject: [PATCH] Support for MetadataTypeAttribute --- .../MetadataTypeTests.cs | 51 +++++++++++++++++++ .../AttributedDestructuringPolicy.cs | 2 + .../Destructurama.Attributed.csproj | 3 +- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/Destructurama.Attributed.Tests/MetadataTypeTests.cs diff --git a/src/Destructurama.Attributed.Tests/MetadataTypeTests.cs b/src/Destructurama.Attributed.Tests/MetadataTypeTests.cs new file mode 100644 index 0000000..b01d5d9 --- /dev/null +++ b/src/Destructurama.Attributed.Tests/MetadataTypeTests.cs @@ -0,0 +1,51 @@ +using System.ComponentModel.DataAnnotations; +using Destructurama.Attributed.Tests.Support; +using NUnit.Framework; +using Serilog; +using Serilog.Events; +using Shouldly; + +namespace Destructurama.Attributed.Tests; + +[TestFixture] +public class MetadataTypeTests +{ + [Test] + public void MetadataType_Should_Be_Respected() + { + LogEvent evt = null!; + + var log = new LoggerConfiguration() + .Destructure.UsingAttributes() + .WriteTo.Sink(new DelegatingSink(e => evt = e)) + .CreateLogger(); + + var customized = new Dto + { + Private = "secret", + Public = "not_Secret" + }; + + log.Information("Here is {@Customized}", customized); + + var sv = (StructureValue)evt.Properties["Customized"]; + var props = sv.Properties.ToDictionary(p => p.Name, p => p.Value); + + props.Count.ShouldBe(1); + props["Public"].LiteralValue().ShouldBe("not_Secret"); + } + + [MetadataType(typeof(DtoMetadata))] + public partial class Dto + { + public string Private { get; set; } + + public string Public { get; set; } + } + + internal class DtoMetadata + { + [NotLogged] + public object Private { get; set; } + } +} diff --git a/src/Destructurama.Attributed/Attributed/AttributedDestructuringPolicy.cs b/src/Destructurama.Attributed/Attributed/AttributedDestructuringPolicy.cs index bfcde45..8b0162b 100644 --- a/src/Destructurama.Attributed/Attributed/AttributedDestructuringPolicy.cs +++ b/src/Destructurama.Attributed/Attributed/AttributedDestructuringPolicy.cs @@ -53,6 +53,8 @@ private CacheEntry CreateCacheEntry(Type type) if (classDestructurer != null) return new(classDestructurer.CreateLogEventPropertyValue); + // TODO: fetch ti.GetCustomAttribute(); and bind to properties + var properties = type.GetPropertiesRecursive().ToList(); if (!_options.IgnoreNullProperties && properties.All(pi => diff --git a/src/Destructurama.Attributed/Destructurama.Attributed.csproj b/src/Destructurama.Attributed/Destructurama.Attributed.csproj index 67453a2..1d4b094 100644 --- a/src/Destructurama.Attributed/Destructurama.Attributed.csproj +++ b/src/Destructurama.Attributed/Destructurama.Attributed.csproj @@ -1,7 +1,7 @@ - netstandard2.0 + netstandard2.0;netstandard2.1 Use attributes to control how complex types are logged to Serilog. Destructurama true @@ -10,6 +10,7 @@ +