Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check NLog minlevel before logging?

Tags:

c#

.net

nlog

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

like image 281
Banshee Avatar asked May 30 '16 07:05

Banshee


2 Answers

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

if (myLogger.IsTraceEnabled)
   myLogger.Trace("Hello World");
like image 93
Rolf Kristensen Avatar answered Sep 28 '22 12:09

Rolf Kristensen


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

like image 39
Peter Avatar answered Sep 28 '22 12:09

Peter