dotnet/runtime

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

Open

#48,622 opened on 2021年2月22日

GitHub で見る
 (7 comments) (0 reactions) (1 assignee)C# (5,445 forks)batch import
area-Extensions-Logginghelp wanted

Repository metrics

Stars
 (17,886 stars)
PR merge metrics
 (平均マージ 12d 11h) (30d で 661 merged PRs)

説明

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

コントリビューターガイド