NLog - Indented/pretty formatted JSON
Asked Answered
H

1

6

I'm surprised I haven't been able to find an answer to this, but how do I get NLog to write JSON formatted messages in a pretty format, instead of the default one-line version?

Is there a simple setting somewhere or do I need to write a custom renderer?

Basically instead of

{ "date": "2018-11-18 14:21:45.0671", "level": "INFO", "message": "Some message" }

I'd like

{
  "date": "2018-11-18 14:21:45.0671",
  "level": "INFO",
  "message": "Some message"
}
Halide answered 18/11, 2018 at 13:21 Comment(4)
Yes NLog only has support for valid JSON (without newlines). Maybe try JToken.Parse(rawJsonString).ToString()Agnew
@RolfKristensen do you mean try that as part of a custom renderer?Halide
are you looking for this: https://mcmap.net/q/1140570/-using-nlog-and-writing-to-file-as-json ?Melanymelaphyre
@SideriteZackwehdex thanks, but no. This layout is what gives me the one-liner i mentioned. There doesn't seem to be a setting to render it in a pretty format.Halide
A
0

NLog v5.1.4 has been released - https://www.nuget.org/packages/NLog/5.1.4, that extends JsonLayout with the setting indentJson="true":

<nlog>
  <targets>
    <target name="jsonConsole" xsi:type="Console">
      <layout xsi:type="JsonLayout" includeEventProperties="true" indentJson="true">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${level:upperCase=true}" />
        <attribute name="message" layout="${message}" />
      </layout>
    </target>
  </targets>
  <rules>
      <logger name="*" minlevel="Debug" writeTo="jsonConsole" />
  </rules>
</nlog>
Agnew answered 30/4, 2023 at 8:6 Comment(1)
Ah, that's awesome! I'll see if I'll be able to try it out in the near future, but this looks exactly like what I needed.Halide

© 2022 - 2025 — McMap. All rights reserved.