5
votes

I want to enable developers to log objects as JSON with NLog. To do this I need to implement some logic before sending to nLog OR before sending to target.

I can build my own Target(TargetWithLayout) but I canĀ“t find a way to check the log level from the config for this specific target/logger? Another drawback is that I need to make a new TargetWithLayout class for each target that we will use (EventLog, File, WebService and so on).

Another solution would be to do it in my LogHandler that uses NLog. The only way to know if I should translate the object is probably to read all the loggers from the config file, if any of them is set to log objects then I serialize. I am however not sure if I can check this information from the LogHandler (without doing it manually)?

3

3 Answers

6
votes

You can use the NLog-Logger object to query active logging-rules:

if (myLogger.IsTraceEnabled)
   myLogger.Trace("Hello World");
1
votes

You can use the NLog json layout to write json in you log files, no need to check and do the serialization yourself:

<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>

The log messages formatting is handled by NLog instead of doing it yourself.

release notes nlog

0
votes

To add some theory ;)

Another drawback is that I need to make a new TargetWithLayout class for each target that we will use (EventLog, File, WebService and so on).

That's the reasons there are Layouts in NLog. Those are the layouts that could be used in the target, but those are independent of the target.

(don't get confused with Layout Renderers, those ${..} things.)

There are multiple layouts (plain text, CSV, JSON) (see list) , and you could easily add your own layout, analogous to adding a custom Target / Layout renderer, see the wiki