Search code examples
c#dictionaryserilog

Log a Dictionary in Serilog, where Value type is a class


I have a Dictionary<string, object> where the values are of different class types. When I try to log the dictionary, the content is not properly displayed.

_logger.LogInformation("Printing Dictionary: {@myDictionary}", myDictionary);

Results in

Printing Dictionary: {"KEY1":{"$type" : "ClassNameOne"}, {"KEY2":{"$type" : "ClassNameTwo"}}

The desired result is {"KEY1":{"ClassOnesFirstProperty" : "PropertyValue","ClassOnesSecondProperty" : "PropertyValue"}, {"KEY2":{"ClassTwosFirstProperty" : "PropertyValue"}}

Or at least something that shows me the actual data. How can I achieve this?


Solution

  • One solution: serialize the dictionary before logging it. So,

    _logger.LogInformation("Printing Dictionary: {@myDictionary}", myDictionary);
    

    Should become

    _logger.LogInformation("Printing Dictionary: {@myDictionary}", JsonConvert.SerializeObject(myDictionary));