dotnet/runtime

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

Open

#48.622 aberto em 22 de fev. de 2021

Ver no GitHub
 (7 comments) (0 reactions) (1 assignee)C# (5.445 forks)batch import
area-Extensions-Logginghelp wanted

Métricas do repositório

Stars
 (17.886 stars)
Métricas de merge de PR
 (Mesclagem média 12d 11h) (661 fundiu PRs em 30d)

Description

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

Guia do colaborador