dotnet/extensions

[Logging] TagName and TagProvider attributes don't work when applied to properties

Open

#6,605 建立於 2025年7月14日

在 GitHub 查看
 (5 留言) (0 反應) (2 負責人)C# (2,401 star) (717 fork)batch import
area-telemetrybuggood first issue

描述

Description

The TagName or TagProvider attributes don't work when applied to a class property. The output of a log method that uses these properties is as if you didn't use them.

When fixing this bug we should ensure that the functionality of the attributes also works when you apply them on a property of an object located in an assembly different from the log method. There was a bug #6598 with other log attributes, we should ensure that we'll not have the same bug for the TagName and TagProvider attributes.

Reproduction Steps

Demo.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Telemetry.Abstractions" Version="9.6.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.5" />
  </ItemGroup>
</Project>

Log.cs

using Microsoft.Extensions.Logging;

internal static partial class Log
{
    [LoggerMessage(LogLevel.Information)]
    public static partial void LogObject(this ILogger logger, [LogProperties] ObjectToLog objectToLog);
}

public class ObjectToLog
{
    [TagName("property.to.log")]
    public string? PropertyToLog { get; set; } = "foo";

    [TagProvider(typeof(TagProvider), nameof(TagProvider.RecordTags))]
    public Property Property { get; set; } = new Property();
}

public class Property
{
    public string? Value { get; set; } = "default";
}

internal static class TagProvider
{
    public static void RecordTags(ITagCollector collector, Property property)
    {
        collector.Add("prop-val", property.Value);
    }
}

Program.cs

using Microsoft.Extensions.Logging;

using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
    builder.ClearProviders();
    builder.AddJsonConsole(options => options.JsonWriterOptions = new() { Indented = true });
});

ILogger logger = loggerFactory.CreateLogger("Demo");
logger.LogObject(new ObjectToLog());

Expected behavior

Expected output:

"prop-val": "default",
"objectToLog.property.to.log": "foo"

Actual behavior

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

貢獻者指南