Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for LogPropertyIgnoreAttribute #113

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class PersonalData
public string? Name { get; set; }
}
```
<sup><a href='/src/Destructurama.Attributed.Tests/LogWithNameAttributeTests.cs#L63-L69' title='Snippet source file'>snippet source</a> | <a href='#snippet-logwithname' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Destructurama.Attributed.Tests/LogWithNameAttributeTests.cs#L64-L70' title='Snippet source file'>snippet source</a> | <a href='#snippet-logwithname' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

## 2. Ignoring a property
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace Destructurama.Attributed
{
public AttributedDestructuringPolicyOptions() { }
public bool IgnoreNullProperties { get; set; }
public bool RespectLogPropertyIgnoreAttribute { get; set; }
}
public interface IPropertyDestructuringAttribute
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Destructurama.Attributed.Tests.Support;
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using Serilog.Events;
using Shouldly;
Expand Down Expand Up @@ -63,6 +64,7 @@ public void AttributesAreConsultedWhenDestructuring()
MutableScalar = new(),
NotAScalar = new(),
Ignored = "Hello, there",
Ignored2 = "Hello, there again",
ScalarAnyway = new(),
AuthData = new()
{
Expand All @@ -71,11 +73,14 @@ public void AttributesAreConsultedWhenDestructuring()
}
};

var evt = DelegatingSink.Execute(customized);
var evt = DelegatingSink.Execute(customized, configure: opt => opt.RespectLogPropertyIgnoreAttribute = true);

var sv = (StructureValue)evt.Properties["Customized"];
var props = sv.Properties.ToDictionary(p => p.Name, p => p.Value);

props.ShouldNotContainKey("Ignored");
props.ShouldNotContainKey("Ignored2");

props["ImmutableScalar"].LiteralValue().ShouldBeOfType<ImmutableScalar>();
props["MutableScalar"].LiteralValue().ShouldBe(new MutableScalar().ToString());
props["NotAScalar"].ShouldBeOfType<StructureValue>();
Expand Down Expand Up @@ -145,6 +150,9 @@ public class Customized
[NotLogged]
public string? Ignored { get; set; }

[LogPropertyIgnore]
public string? Ignored2 { get; set; }

[LogAsScalar]
public NotAScalar? ScalarAnyway { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
<TargetFrameworks Condition="'$(OS)' != 'Windows_NT'">net8.0</TargetFrameworks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<NoWarn>$(NoWarn);1591</NoWarn>
<DefineConstants>$(DefineConstants);CODE_GENERATION_ATTRIBUTES</DefineConstants> <!--Test with LogPropertyIgnoreAttribute requires it.-->
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Telemetry.Abstractions" Version="8.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,27 +68,42 @@

private CacheEntry CreateCacheEntry(Type type)
{
static T GetCustomAttribute<T>(PropertyInfo propertyInfo) => propertyInfo.GetCustomAttributes().OfType<T>().FirstOrDefault();
IPropertyDestructuringAttribute? GetPropertyDestructuringAttribute(PropertyInfo propertyInfo)
{
var attr = propertyInfo.GetCustomAttributes().OfType<IPropertyDestructuringAttribute>().FirstOrDefault();
if (attr != null)
return attr;

if (_options.RespectLogPropertyIgnoreAttribute)
{
// Do not check attribute explicitly to not take dependency from Microsoft.Extensions.Telemetry.Abstractions package.
// https://github.com/serilog/serilog/issues/1984
if (propertyInfo.GetCustomAttributes().Any(a => a.GetType().FullName == "Microsoft.Extensions.Logging.LogPropertyIgnoreAttribute"))
Fixed Show fixed Hide fixed
return NotLoggedAttribute.Instance;
}
Fixed Show fixed Hide fixed

return null;
}

var classDestructurer = type.GetCustomAttributes().OfType<ITypeDestructuringAttribute>().FirstOrDefault();
if (classDestructurer != null)
return new(classDestructurer.CreateLogEventPropertyValue);

var properties = GetPropertiesRecursive(type).ToList();
if (!_options.IgnoreNullProperties && properties.All(pi =>
GetCustomAttribute<IPropertyDestructuringAttribute>(pi) == null
&& GetCustomAttribute<IPropertyOptionalIgnoreAttribute>(pi) == null))
GetPropertyDestructuringAttribute(pi) == null
&& pi.GetCustomAttributes().OfType<IPropertyOptionalIgnoreAttribute>().FirstOrDefault() == null))
{
return CacheEntry.Ignore;
}

var optionalIgnoreAttributes = properties
.Select(pi => new { pi, Attribute = GetCustomAttribute<IPropertyOptionalIgnoreAttribute>(pi) })
.Select(pi => new { pi, Attribute = pi.GetCustomAttributes().OfType<IPropertyOptionalIgnoreAttribute>().FirstOrDefault() })
.Where(o => o.Attribute != null)
.ToDictionary(o => o.pi, o => o.Attribute);

var destructuringAttributes = properties
.Select(pi => new { pi, Attribute = GetCustomAttribute<IPropertyDestructuringAttribute>(pi) })
.Select(pi => new { pi, Attribute = GetPropertyDestructuringAttribute(pi)! })
.Where(o => o.Attribute != null)
.ToDictionary(o => o.pi, o => o.Attribute);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,10 @@ public class AttributedDestructuringPolicyOptions
/// and affected by this property only in case at least one property (or the type itself) has Destructurama attribute applied.
/// </summary>
public bool IgnoreNullProperties { get; set; }

/// <summary>
/// Respect Microsoft.Extensions.Logging.LogPropertyIgnoreAttribute to not include property when destructuring an object for logging.
/// This works the same as when applying <see cref="NotLoggedAttribute"/> to the property but may help if you have no access to it's source code.
/// </summary>
public bool RespectLogPropertyIgnoreAttribute { get; set; }
}
2 changes: 2 additions & 0 deletions src/Destructurama.Attributed/Attributed/NotLoggedAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ namespace Destructurama.Attributed;
[AttributeUsage(AttributeTargets.Property)]
public class NotLoggedAttribute : Attribute, IPropertyDestructuringAttribute
{
internal static readonly NotLoggedAttribute Instance = new();

/// <inheritdoc/>
public bool TryCreateLogEventProperty(string name, object? value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventProperty? property)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ bool IPropertyOptionalIgnoreAttribute.ShouldPropertyBeIgnored(string name, objec
{
if (value != null)
{

if (type.IsValueType)
{
if (!_cache.TryGetValue(type, out CachedValue cachedValue))
Expand Down