Using Nlog and writing to file as json

I think I am missing something, because I cannot figure out how to write it to a log file in json format using the NLog setting in the configuration file. The direct rolling file works fine, but not json. The json target function displays a 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> 
+5
source share
2 answers

Since the release of NLog 4.0.0, you can use a layout that displays events as structured JSON documents.

Example from the 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 a link to a specific part of the documentation.

And here is a 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) } }; 

Read the docs for more details.

+8
source

According to the NLog documentation : json-encode will < exit using JSON rules. It will not "convert" the output to JSON. You have to do it yourself.

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

See this question for more details.

+2
source

Source: https://habr.com/ru/post/1206669/


All Articles