Skip to content

Strong type support in Microsoft.Extensions.Logging #61947

Closed

Description

@reyang

Problem Description

In a large codebase, there are cases people want to log with existing types defined for business logic (and these types might come from a 3rd party library which is not controlled by the dev), rather than having to invent another type (and do the mapping) or write lots of boilerplate code.

public struct Food
{
    public string Name { get; set; }
    public double Price { get; set; }
}

logger.Eat(new Food { Name = "artichoke", Price = 3.99 });

In order for the above code to work, one has to write the boilerplate code as follows, and will start to hit performance issue if there are more than 6 fields (based on the current implementation).

using System;
using Microsoft.Extensions.Logging;

public static class LoggerExtensions
{
    private static readonly Action<ILogger, Food, Exception> _eat = LoggerMessage.Define<Food>(
        LogLevel.Information,
        new EventId(1, nameof(Eat)),
        "Eat (Food = {food})."); // message template, not interpolated string

    public static void Eat(this ILogger logger, Food food)
    {
        _eat(logger, food, null);
    }
}

The Ask

Provide a vendor agnostic way for the user to log strong typed objects without having to write boilerplate code, yet with good/reasonable performance.

public struct Food
{
    public string Name { get; set; }
    public double Price { get; set; }
}

public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
}

logger.Eat(new Food { Name = "Artichoke", Price = 3.99 });
logger.Log(new Dog { Name = "Labrador Retriever", Age = 2 });

Additional Information

Activity

  1. ghost added
    untriaged
    on Nov 22, 2021
  2. added and removed
    untriaged
    on Nov 23, 2021
  3. added this to the 7.0.0 milestone on Nov 23, 2021
  4. yecril71pl commented on Dec 29, 2021

    @yecril71pl
    Contributor

    The introduction says that named parameters can be used to attach properties to log entries.
    I would like the opposite syntax to work in the following scenarios:

    const string format = "Customer {Name} #{Serial} entered the shop.  {Name} left {Mood}.";
    
    var customer = new { Name = "Joe", Sex = Sex .Male, Age = 50, Serial = 33 };
    logger .LogInformation (format, customer with { Mood = Mood .Satisfied });
    
    var customer = new Customer { Name = "Joe", Sex = Sex .Male, Age = 50, Serial = 33 };
    customer .Mood = Mood .Satisfied;
    logger .LogInformation (format, customer);
    
    var customer = new Dictionary < string, object >
     { ["Name"] = "Joe", ["Sex"] = Sex .Male, ["Age"] = 50, ["Serial"] = 33 };
    customer ["Mood"] = Mood .Satisfied;
    logger .LogInformation (format, customer);

    All these calls should translate to

    logger .Log
     (LogLevel .Information, default, null,
     format, "Joe", 33, "Joe", Mood .Satisfied);

    Implementing this using reflexion bumps into the following problem: support for enumerating parameter islands in a message format string, which was never officially supported, was removed from the public API in ASP.NET 3, so any independent solution would have to rely on undocumented features or contain a copy or a replica of internal code.

  5. modified the milestones: 7.0.0, 6.0.x, Future on Jan 11, 2022
  6. self-assigned this
    on Jan 19, 2022
  7. modified the milestones: Future, 7.0.0 on Jan 19, 2022
  8. maryamariyan commented on Feb 15, 2022

    @maryamariyan
    Contributor

    To add strong type support, consider the Food struct in the issue description. If developer added an annotation like StructuredLogMessage shown below to a partial Foo struct, the logging source generator could potentially code generate the remaining code portion.

    [StructuredLogMessage]
    public partial struct Food
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }
    
    logger.Eat(new Food { Name = "artichoke", Price = 3.99 });
    
    internal partial struct Food : IReadOnlyList<KeyValuePair<string, object?>>
    {
        public int Count => 2;
    
        public KeyValuePair<string, object?> this[int index]
        {
            get => index switch
                {
                    0 => new KeyValuePair<string, object?>(nameof(Name), Name),
                    1 => new KeyValuePair<string, object?>(nameof(Price), Price),
                    _ => throw new IndexOutOfRangeException(nameof(index)),
                };
    
        }
    
        // if developer does not override ToString themselves the generator would generate this as default ToString
        // Name and Price in this case are the public properties presented in Food
        public override string ToString()
        {
            return $"{nameof(Name)}={Name}, {nameof(Price)}={Price}";
        }
    }

    @davidfowl @reyang @noahfalk do you think if we added this to the logging source generator it would be something that could be adopted for open telemetry as-is?

  9. 14 remaining items

  10. KalleOlaviNiemitalo commented on Feb 22, 2022

    @KalleOlaviNiemitalo
    [StructureLogMessage]
    public partial struct FoodLogMessage : LogMessage<Food> { }

    Would LogMessage<> be an interface type there, or are you proposing a C# change as well?

  11. noahfalk commented on Feb 22, 2022

    @noahfalk
    Member

    Would LogMessage<> be an interface type there, or are you proposing a C# change as well?

    No intent to propose a C# change I think (I was part of the offline discussion that came from), it was just handwavy brainstorming. I'm hoping that portion of the problem is sufficiently solved by the pre-existing source generator work that we can do nothing.

    There are really two parts to this, as I see it: 1) Some API on ILogger that lets users pass a complex type to Log/BeginScope calls and 2) some API/feature to pass the complex type to the LoggerProvider(s).

    Different designs might do portions of the serialization work at different stages, for example between the source generator and ILogger, between the ILogger implementation and ILoggerProvider, or in ILoggerProvider. I am hoping we don't need to consider implementation concerns quite yet though. My suggestion is to figure out if users could wave a magic wand at their logging code to serialize data however they wished, what would that serialized output look like?

  12. yecril71pl commented on Feb 23, 2022

    @yecril71pl
    Contributor

    My suggestion is to figure out if users could wave a magic wand at their logging code to serialize data however they wished, what would that serialized output look like?

    The text must not be too long (unless a dedicated log book is used). It should contain key information that is specific, variable and hard to deduce from the context. If there is too much key information, there is a chance that the object itself is too rich and should be split.

  13. tbolon commented on Apr 19, 2022

    @tbolon

    I am not sure if it is really related to your use case, but Serilog (which is one of the defacto logging library for .net) supports '@' prefix in parameter names in logs, and "destructure" the object into the output message:

    var position = new { Latitude = 25, Longitude = 134 };
    var elapsedMs = 34;
    
    log.Information("Processed {@Position} in {Elapsed:000} ms.", position, elapsedMs);

    renders:

    09:14:22 [Information] Processed { Latitude: 25, Longitude: 134 } in 034 ms.

    Tools such as seq can process such objects and make them useable when searching logs.
    Obviously, it heavily makes use of reflection.

    I suppose your goal here is to make more explicit choices about what to log, and get rid of any reflection cost. So my comment will only be there to be sure that you are aware of the ecosystem about object logging :)

  14. p10tyr commented on May 12, 2022

    @p10tyr

    This is not strictly about Strong type support but a request to allow us to add our own Attributes to the LogRecord class

    I understand the States get enumerated and pushed onto repeated opentelemetry.proto.common.v1.KeyValue attributes with the exporter.

    But we have absolutely no way to add our own attributes here when ParseStateValues is false or true.

    The use case in my situation is that I always want to add a tenant attribute to everything Log and Trace for grouping in the APM. I can create my own BaseProcessor<LogRecord and add it as a Processor to LogBuilder.. But honestly.. its quite pointless because I cant add attributes .. easily.

    Even if I were to hand roll out or customise OpentTelemetryLogProvider the OTLPLoggerClass does not really accept any kind of extra attributes.

    It just assumes you are going to use Scopes (which is put on the Scopes Proto Attribute any way) or Provide States which is impractical to do and police on every single line that tries to log.

    If LogRecord has something like .AddAtrribute(KeyValue) and OpenTelemetryLogger passed it along it would be easy to add what is needed with a processor. (Even if Scopes and States are turned off)

    --Edit
    I was helped out with an example on how to leverage Scopes to achieve what I needed. I was just stuck in my own tunnel vision.

    Thank you for the great work on OTLP (and sorry for hijacking this thread a bit)

    I am definitely going to follow this as it does look like a really awesome feature to have!

  15. modified the milestones: 7.0.0, 8.0.0 on May 24, 2022
  16. removed their assignment
    on Jan 9, 2023
  17. modified the milestones: 8.0.0, Future on Feb 1, 2023
  18. obondarenko1 commented on Jan 4, 2024

    @obondarenko1

    Subscribing to this issue, as not being able to have a structured object written out as a JSON using high-performance logging making subsequent log analysis a very unpleasant chore.

  19. geeknoid commented on Jan 4, 2024

    @geeknoid
    Member
  20. reyang commented on Jan 11, 2024

    @reyang
    ContributorAuthor
  21. locked and limited conversation to collaborators on Feb 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-Extensions-Loggingfeature-request

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions