Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a certain piece optional in a NLog layout pattern?

Tags:

nlog

I have a custom layout renderer named job. It provides several items, which are used like this in our app.config:

<variable name="jobHost" value = "${job:item=host}" />
<variable name="jobService" value = "${job:item=service}" />
<variable name="jobNS" value = "${job:item=ns}" />
<variable name="jobName" value = "${job:item=name}" />
<variable name="jobKind" value = "${job:item=kind}" />
<variable name="jobScheduleId" value = "${job:item=scheduleId}" />
<variable name="jobLayout" value = "[H:${jobHost} S:${jobService} NS:${jobNS} N:'${jobName}' K:${jobKind} S:${jobScheduleId}]" />
<variable name="layout" value = "${longdate} [${threadid}] ${machinename} ${jobLayout} ${uppercase:inner=${level}} ${logger} - ${message} ${onexception:${newline}${exception:format=ToString:innerFormat=ToString:maxInnerExceptionLevel=2}}" />
<targets>
    <target name="ThreadLog" xsi:type="ThreadSpecificTarget" />
    <target xsi:type="SplitGroup" name="AllTargets">
        <target name="TextFile" xsi:type="File" fileName="C:\Log\QuartzBackgroundEngine.txt" layout="${layout}"/>
        <target name="Console" xsi:type="ColoredConsole" layout="${layout}"/>
    </target>
</targets>

When the layout renderer decides that there is no job specific data available, then log messages contain the string [H: S: NS: N:'' K: S:]. I want to exclude it.

So, I tried to replace ${jobLayout} with ${jobLayout:when=jobName!=’’}, but it does not work, because NLog thinks that jobLayout should correspond to a layout renderer, rather than a variable, which is the case here.

How can I change my layout so that ${jobLayout} is only included if ${jobName} is not empty?

like image 463
mark Avatar asked Jun 20 '13 18:06

mark


2 Answers

I ran into a similar problem where I wanted to make to display some special formatting when a variable was not empty.

I took some inspiration from Most useful NLog configurations

${when:when=length('${jobName}') > 0:inner=${jobLayout}}

I'm not sure if this will get you 100% there, but it is a step in the right direction.

like image 191
Richard R Avatar answered Sep 30 '22 12:09

Richard R


Did you try the whenEmpty layout renderer? https://github.com/nlog/NLog/wiki/WhenEmpty-Layout-Renderer

like image 33
erezmk Avatar answered Sep 30 '22 13:09

erezmk