如何在连接到 MongoDB 的 NLog 中记录复杂对象

How to Log Complex Objects in NLog Connected to MongoDB

我正在尝试使用 .NET Core 3.0 中的 NLog 在 MongoDB 中记录自定义复杂对象。

例如:

 var customData = new { myData = "this is my data", test = new { fff = 1 } };

问题是 logEventInfo.Properties 只接受奇怪的字符串值,我必须将 JSON 字符串存储在 MongoDb 中,这使得 MongoDB 无用。

是否有内置解决方案?

使用 JsonSerializer 然后将其存储在 MongoDB 这是你应该做的方式: 使用 Newtonsoft JsonSerializer 或 .Net core 内置序列化器:

var result = JsonConvert.SerializeObject(customData );
// or var result = JsonSerializer.Serialize(customData ); // .Net Core Serializer
logger.Log(result);

https://www.nuget.org/packages/NLog.Mongo 更新到版本 4.6.0.118 或更高版本。然后你可以这样做(注意 bsonType="Object"):

<target xsi:type="Mongo"
        name="mongoCustomJsonProperties"
        includeEventProperties="false"
        connectionString="mongodb://localhost/Logging"
        collectionName="CustomLog"
        cappedCollectionSize="26214400">
    <field name="Properties" bsonType="Object">
      <layout type="JsonLayout" includeAllProperties="true" includeMdlc="true" maxRecursionLimit="10">
        <attribute name="ThreadID" layout="${threadid}" encode="false" />
        <attribute name="ProcessID" layout="${processid}" encode="false" />
        <attribute name="ProcessName" layout="${processname:fullName=false}" />
      </layout>
    </field>
</target>