dotnet/runtime

Dictionary types are not property serialized with JSon console logger and LoggerMessage

Open

#48.622 aperta il 22 feb 2021

Vedi su GitHub
 (7 commenti) (0 reazioni) (1 assegnatario)C# (5445 fork)batch import
area-Extensions-Logginghelp wanted

Metriche repository

Star
 (17.886 star)
Metriche merge PR
 (Merge medio 12g 11h) (661 PR mergiate in 30 g)

Descrizione

Description

Dictionary types are not property serialized with JSon console logger when using LoggerMessage.Define

When creating a template function to write parametrized logs dictionary types are not correctly serialized in the JSon logger, this works correctly when directly using the LogXXX methods of the logger

Action<ILogger, Dictionary<string, string>, Exception> _contextAction = LoggerMessage.Define<Dictionary<string, string>>(
            LogLevel.Information,
            new EventId(),
            "context = {Context}");

var logger = loggerFactory.CreateLogger("Default");
logger.LogInformation("context = {Context}", context);
_contextAction(logger, context, null!);

I would expect the above to generate identical output but they are not, in the second case the State doesn't contain the serialized dictionary just the type name

{
  "EventId": 0,
  "LogLevel": "Information",
  "Category": "Default",
  "Message": "context = [User, Jose]",
  "State": {
    "Message": "context = [User, Jose]",
    "Context": "[User, Jose]",
    "{OriginalFormat}": "context = {Context}"
  },
  "Scopes": []
}
{
  "EventId": 0,
  "LogLevel": "Information",
  "Category": "Default",
  "Message": "context = [User, Jose]",
  "State": {
    "Message": "context = [User, Jose]",
    "Context": "System.Collections.Generic.Dictionary\u00602[System.String,System.String]",
    "{OriginalFormat}": "context = {Context}"
  },
  "Scopes": []
}

See full example at https://dotnetfiddle.net/xZ7Dr3

Guida contributor