-
Notifications
You must be signed in to change notification settings - Fork 1.4k
When Layout Renderer
Only outputs the inner layout when the specified condition has been met. See Conditions.
Platforms Supported: All
${when:when=Condition:inner=Layout:else=Layout}
or by using ambient property to modify output of other layout renderer:
${other:when=Condition}
- when - Condition that must be met for the inner layout to be printed. Condition Required.
- inner - Wrapped layout. Layout
- else - Layout if the condition is not true (introduced in NLog 4.3.5)
print the message when the logger name is equal to "logger":
${message:when=logger=='logger'}
convert a layout string result to a bit (1 or 0) that can be inserted into a SQL bit field.:
${when:when='${aspnet-request:serverVariable=HTTPS}' == 'on':inner=1:else=0}
Write "Good" if the loglevel is trace/debug/info and otherwise "Bad":
${when:when=level<=LogLevel.Info:inner=Good:else=Bad}
Write suffix to property-value when available:
${when:when='${event-properties:item=PropName}'=='':else= ${event-properties:item=PropName} Secs}
Only write the message if it does not start with Published
using a condition function:
${when:when=not starts-with(message, 'Published'):inner=${message}}
When using :
and }
in a internal layout those characters need to be escaped (there is no need to escape \
).
-
:
because it's a value separator. -
}
because it's the end of the layout
Working examples:
${when:when=1 == 1:Inner=Test\: Hello}
${when:when=1 == 1:Inner=Test\\Hello}
${when:when=1 == 1:Inner=Test\Hello}
${when:when=1 == 1:Inner=Test{Hello\}}
The colon (:) character should be wrapped within {literal:text=\:}
instead of placed directly within the inner layout.
Working Example
Configuration | layout="${when:when=1 == 1:inner=Test${literal:text=\:} Hello${literal:text=\:} World}" |
---|---|
Output | Test: Hello: World |
Non-working Example
Configuration | layout="${when:when=1 == 1:inner=Test: Hello: World}" |
---|---|
Output | World |
When the colon character is not wrapped only the last literal instance, in this case the word 'World', appears.
⭐ Workaround identified by: @reedyrm
- Troubleshooting Guide - See available NLog Targets and Layouts: https://nlog-project.org/config
- Getting started
- How to use structured logging
- Troubleshooting
- FAQ
-
All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json