首页 > 解决方案 > NLog 结构化日志记录将所有值转换为字符串

问题描述

我们正在使用 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)。我绝对需要将持续时间作为数值。

关于如何解决这个问题的任何想法?

谢谢塞巴斯蒂安

标签: c#asp.net-coreasp.net-core-2.0nlog

解决方案


尝试更换

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

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

推荐阅读