NLog 结构化日志记录将所有值转换为字符串

NLog Structured logging converts all values to string

我们正在使用 asp.net 核心的 NLog 集成来管理我们的日志。我们需要生成包含响应时间(持续时间)的 JSON 日志。

代码如下:

logger.LogInformation("Duration {duration}", 122);

配置如下:

<target name="aws" type="Debugger">
  <layout type="JsonLayout">
    <attribute name="level" layout="${level}" />
    <attribute name="msg" layout="${message}" />
    <attribute name="err" layout="${exception:format=tostring}" />
    <attribute name="meta" encode="false">
      <layout type="JsonLayout">
        <attribute name="requestId" layout="${aspnet-traceidentifier}" />
        <attribute name="user" layout="${aspnet-user-identity}" />
        <attribute name="agent" layout="${aspnet-request-useragent}" />
        <attribute name="method" layout="${aspnet-request-method}" />
        <attribute name="url" layout="${aspnet-request-url:IncludeHost=true:IncludePort=true:IncludeQueryString=true}" />
        <attribute name="logger" layout="${logger}" />
        <attribute name="duration" layout="${event-properties:duration}" />
      </layout>
    </attribute>
  </layout>
</target>

始终生成如下所示的输出:

{
    "level": "Info",
    "msg": "Duration 122",
    "meta": {
        "requestId": "0HLKTC2E2B3KL:00000002",
        "agent": "PostmanRuntime\/7.6.0",
        "method": "POST",
        "url": "http:\/\/localhost:20000\/api\/v1\/oauth\/token",
        "logger": "TEC.CoreApi.Application.Features.Authentication.OAuthController",
        "duration": "122"
    }
}

如您所见,持续时间变成了一个字符串,这会阻止我们使用我们的日志解析器 (CloudWatch Logs)。我绝对需要将持续时间作为数值。

知道如何解决这个问题吗?

谢谢 塞巴斯蒂安

尝试替换

<attribute name="duration" layout="${event-properties:duration}"/>

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