首页 > 解决方案 > 如何在连接到 MongoDB 的 NLog 中记录复杂对象

问题描述

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

一个例子是:

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

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

有没有内置的解决方案?

标签: c#.net-corenlog

解决方案


将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>

推荐阅读