【问题标题】:using Nlog and writing to file as json使用 Nlog 并以 json 格式写入文件
【发布时间】:2014-11-11 20:33:51
【问题描述】:

我想我遗漏了一些东西,因为我似乎无法弄清楚如何使用配置文件中的 NLog 设置将其写入 json 格式的日志文件。直线滚动文件工作正常,但不是 json。 json 目标只输出消息(不在 json 中)。

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">        
    <targets async="true">
      <target xsi:type="File" name="rollingFile" fileName="${basedir}/logs/${shortdate}.log" archiveFileName="${basedir}/logs/{shortdate}_Archive{###}.log" archiveAboveSize="1000000" archiveNumbering="Sequence" layout="${longdate} ${uppercase:${level}} ${callsite} ${message}" />
      <target xsi:type="File" 
              name="rollingFileJson" 
              fileName="${basedir}/logs/${shortdate}.json" 
              archiveFileName="${basedir}/logs/{shortdate}_Archive{###}.json" 
              archiveAboveSize="1000000" 
              archiveNumbering="Sequence" 
              layout="${json-encode} ${message}">
      </target>

    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="rollingFile" />
      <logger name="*" minlevel="Trace" writeTo="rollingFileJson" />
    </rules>
  </nlog>

【问题讨论】:

    标签: json nlog


    【解决方案1】:

    从 NLog 4.0.0 版本开始,可以使用将事件呈现为结构化 JSON 文档的布局。

    示例取自NLog project site:

    <target name="jsonFile" xsi:type="File" fileName="${logFileNamePrefix}.json">
        <layout xsi:type="JsonLayout">
            <attribute name="time" layout="${longdate}" />
            <attribute name="level" layout="${level:upperCase=true}"/>
            <attribute name="message" layout="${message}" />
        </layout>
    </target>
    

    编辑: 您也可以在代码中创建它。

    Here 是文档特定部分的链接。

    这里是复制的例子:

    var jsonLayout = new JsonLayout
    {
        Attributes =
        {
            new JsonAttribute("type", "${exception:format=Type}"),
            new JsonAttribute("message", "${exception:format=Message}"),
            new JsonAttribute("innerException", new JsonLayout
            {
    
                Attributes =
                {
                    new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                    new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                }
            },
            //don't escape layout
            false)
        }
    };
    

    更多信息请阅读docs

    【讨论】:

    • 以编程方式执行此操作的任何方式?
    • @user3841581 添加了从文档中获取的示例以在代码中执行此操作。
    【解决方案2】:

    根据NLog documentationjson-encode 只会转义输出 使用 JSON 规则的另一个布局。它不会将输出“转换”为 JSON。你必须自己做。

    '{ "date":"${longdate}","level":"${level}","message":${message}}'
    

    查看this question了解更多详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      相关资源
      最近更新 更多