How to configure output in NDJSON format with NLog

110 Views Asked by At

I am working on .NET Framework 4.5.2 NDJSON format I require : Nlog config in xml format for ndjson format given below

{
    "timestamp": "[timestamp]",
    "level": "[level]",
    "severity": "[severity]",
    "requestId": "[requestId]",
    "httpMethod": "[httpMethod]",
    "requestUrl": "[requestUrl]",
    "message": "[message]",
    "stackTrace": "[stackTrace]"
}

In the above format the following place holders are showing as empty for

httpMethod,requestId,requestUrl:
requestId": "${mdc:item=requestId}", 
"httpMethod": "${aspnet-request-method}", 
"requestUrl": "${aspnet-request-url}

I already tried an alternative approach to extract the MDC properties and ASP.NET request information directly in the custom layout renderer

Please suggest what method can be used

1

There are 1 best solutions below

0
Rolf Kristensen On

The NLog JsonLayout can be used to produce output in JSON-format:

<nlog>
   <targets>
       <target name="ndjson_console" xsi:type="console">
           <layout xsi:type="jsonlayout">
              <attribute name="timestamp" layout="${date:universalTime=true:format=o}" />
              <attribute name="level" layout="${level}"/>
              <attribute name="message" layout="${message}" />
              <attribute name="stackTrace" layout="${exception:format=tostring}" />
           </layout>
       </target>
   </targets>
   <rules>
       <logger name="*" writeTo="ndjson_console" />
   </rules>
</nlog>

You can use NLog Context for providing additional details, and if your are using NLog.Web.AspNetCore then ${aspnet}-LayoutRenderers are available:

<nlog>
   <targets>
       <target name="ndjson_console" xsi:type="console">
           <layout xsi:type="jsonlayout">
              <attribute name="timestamp" layout="${date:universalTime=true:format=o}" />
              <attribute name="level" layout="${level}"/>
              <attribute name="message" layout="${message}" />
              <attribute name="stackTrace" layout="${exception:format=tostring}" />
              <attribute name="requestId" layout="${aspnet-TraceIdentifier}" />
              <attribute name="httpMethod" layout="${aspnet-request-method}" />
              <attribute name="requestUrl" layout="${aspnet-request-url" />
           </layout>
       </target>
   </targets>
   <rules>
       <logger name="*" writeTo="ndjson_console" />
   </rules>
</nlog>

By default then NLog ConsoleTarget and NLog FileTarget will add newline-delimeter for each LogEvent. Thus automaticaly output in NDJSON format.