using Nlog and writing to file as json
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.
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.