using Nlog and writing to file as json

2020-07-10 03:43发布

问题:

I think I'm missing something as I can't seem to figure out how to have it write to a log file in json format using NLog setup in configuration file. The straight rolling file works fine, but not the json. The json target only outputs the message (not in 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>

回答1:

As of the release of NLog 4.0.0 it is possible to use a layout that renders events as structured JSON documents.

Example taken from 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>

Edit: You can also create it in code.

Here is the link to the specific part of documentation.

And here the copied example:

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)
    }
};

For more info read the docs.



回答2:

As per NLog documentation: json-encode will only escape output of another layout using JSON rules. It will not "convert" the output to JSON. You'll have to do that yourself.

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

Take a look at this question for more details.



标签: json nlog