Nlog / event-properties: how to hint NLog to ignore/skip empty/null properties from the final log entry

Viewed 1515

Basically the title itself kinda explains what i'm trying to achieve but in greater detail:

  1. Let's say the one has similar to the following XML setup for the layout:

    layout="<log level='${level:lowerCase=True}' time='${longdate:universalTime=true}' myCustomProperty1='${event-properties:item=myCustomProperty1}' myCustomProperty2='${event-properties:item=myCustomProperty2}'>${newline} ...."

  2. Now when myCustomProperty1 is set to let's say 'blah1' but myCustomProperty2 is not added to eventInfo.Properties collection the resulting entry looks like following:

    <log level='blah' time='blah' myCustomProperty1='blah1' myCustomProperty2=''> ...

  3. The question is - what can be done (preferably in the config file) to exclude the myCustomProperty2 attribute from finally rendered result so the output looks as following:

    <log level='blah' time='blah' myCustomProperty1='blah1'> ...

Here is the gotcha - the same logger is used by multiple threads so i can't simply alter target's layout configuration at the runtime since it may negatively affect the rest of the threads

Thank you in advance for your suggestions. -K

1 Answers

You could try using When :

  <variables>
    <variable name="var_myCustomProperty1" value="${when:when=length('${event-properties:item=myCustomProperty1}')>0:Inner= myCustomProperty1=&quot;${event-properties:item=myCustomProperty1}&quot;}"/>
    <variable name="var_myCustomProperty2" value="${when:when=length('${event-properties:item=myCustomProperty2}')>0:Inner= myCustomProperty2=&quot;${event-properties:item=myCustomProperty2}&quot;}"/>
  </variables>

  <targets>
    <target name="test" type="Console" layout="&lt;log level='${level:lowerCase=True}' time='${longdate:universalTime=true}'${var_myCustomProperty1}${var_myCustomProperty2} /&gt;" />
  </targets>

NLog 4.6 will include the XmlLayout, that might make things easier:

https://github.com/NLog/NLog/pull/2670

Alternative you can use the JsonLayout, if xml-output is not a requirement (renderEmptyObject="false")

Related