dotnet/runtime

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

Open

#48,622 建立於 2021年2月22日

在 GitHub 查看
 (7 留言) (0 反應) (1 負責人)C# (5,445 fork)batch import
area-Extensions-Logginghelp wanted

倉庫指標

Star
 (17,886 star)
PR 合併指標
 (平均合併 12天 11小時) (30 天內合併 661 個 PR)

描述

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

貢獻者指南