NLog JSON结构化事件属性



这是我的NLog配置:

<layout type="JsonLayout">
<attribute name="businessProcessName" layout="${event-properties:rawMessage:item=BusinessProcess}" />
<attribute name="businessDepartmentName" layout="${event-properties:rawMessage:item=BusinessDepartment}" />
<attribute name="logType" layout="${event-properties:rawMessage:item=logType}" />
<attribute name="queueName" layout="${event-properties:rawMessage:item=QueueName}" />
<attribute name="data" layout="${event-properties:rawMessage:item=LogF_AllTransactionData}" />
</layout>

这给了我以下结果:

{ "businessProcessName": "ACME", "businessDepartmentName": "Lior", "logType": "User", "queueName": "LoggingTest", "data": "{rn  "ExecuterJobGUID": "Studio_05fe3a0e-dc3b-4635-a521-5fe450cdb13e",rn  "LogF_TransactionReference": "MyTransaction",rn  "LogF_StartTransactionTime": "08/02/2022 17:11:33",rn  "LogF_TransactionId": "23031",rn  "LogF_QueueName": "LoggingTest",rn  "LogF_QueueDefinitionId": 545,rn  "LogF_SpecificContent": {rn    "FirstName": "Lior",rn    "LastName": "Hen",rn    "BirthDate": "1989-12-03T00:00:00Z"rn  },rn  "LogF_Progress": "",rn  "LogF_RetryNo": 0,rn  "Gender": "Male",rn  "City": "Ashdod"rn}" }

我有两个问题:

  1. 如何将"data"作为Json而不是字符串
  2. 如何从"data"(如"LogF_TransactionReference"(中引入单个密钥

谢谢!

如果您知道LogEvent属性包含有效的JSON,那么您可以指定encode="false":

<attribute name="data" layout="${event-properties:item=LogF_AllTransactionData}" encode="false" />

那么NLog将不会将LogEvent属性值编码/转义为JSON字符串属性。

NLog${event properties}具有objectpath选项,但它要求您提供原始对象,而不是预先序列化为JSON。

<attribute name="data_id" layout="${event-properties:item=LogF_AllTransactionData:objectpath=Id}" />
<attribute name="data" layout="${event-properties:item=LogF_AllTransactionData:format=@}" encode="false" />

另一种方法是实现自定义布局呈现器,解析JSON对象并输出所需的属性。但它有一个性能惩罚。

另请参阅:https://github.com/NLog/NLog/wiki/How-to-use-structured-logging

最新更新