Microsoft.Extensions.Logging, LoggerMessageAttribute, and Message Templates structure capturing operator

Viewed 201

Message Templates has a @ structure capturing operator used to provide a hint the argument structure should be preserved. Message Templates claims Microsoft.Extensions.Logging has support for message templates.

Why do I get a compiler error when trying to use the structure capturing operator with LoggerMessageAttribute?

public static partial class Log
{
    LoggerMessage(
        EventId = 9001,
        Level = LogLevel.Error,
        Message = "Something happened at {@point}")]
    public static partial void SomethingHappenedAt(ILogger logger, System.Drawing.Point point);
}
Log.SomethingHappenedAt(_logger, new System.Drawing.Point(1, 2));

Produces the following compiler errors:

SYSLIB1014 Template '@point' is not provided as argument to the logging method

CS0103 The name 'point' does not exist in the current context

Removing the structure capturing operator removes the compiler error but I do not see the Point object being output to the JsonConsole. It looks like ToString() is being used instead.

{
  "Timestamp": "15:26:47 ",
  "EventId": 9001,
  "LogLevel": "Error",
  "Category": "Blah.Blah.Blah",
  "Message": "Something happened at {X=1,Y=2}",
  "State": {
    "Message": "Something happened at {X=1,Y=2}",
    "point": "{X=1,Y=2}",
    "{OriginalFormat}": "Something happened at {point}"
  },
  "Scopes": []
}

How can I keep the structure of point in the JSON and avoid using ToString()?

0 Answers
Related