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

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

我们正在使用适用于 asp.net core 的 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"/>

关于c# - NLog 结构化日志记录将所有值转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54922568/

相关文章:

c# - 反序列化 XmlDocument 的最短方法

C# Winforms bold treeview 节点不显示整个文本

c# - 从多个 WAV 文件中删除 header ,然后将剩余数据连接到一个 RAW 文件中

Docker 中的 ASP.NET 5.0 beta 8 无法启动

c# - Entity Framework Core 读取未提交的问题

c# - 在 Windows 窗体中操作拖放图像 C#

c# - 如何在 oData .Net core 3.1 中启用 $levels

c# - 无法在 Dot Net Core 中使用 System.Management.dll

c# - ASP.Net Core 2.0 Web 应用程序中的本地化

c# - 如何在 .net core 2 启动时访问 IConfigurationRoot?