简体   繁体   中英

NLog layout renderers don't seem to work in configuration

Using ASP.NET v4.7.2, in nlog.config I have this target:

<target name="logfile" xsi:type="File" fileName="{gdc:item=logFileName}" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"/>

In Global.asax.cs:Application_Start I have this:

GlobalDiagnosticsContext.Set("logFileName", @"c:\\Temp\\nlog-all-${shortdate}.txt");

And just for good measure:

LogManager.Configuration = LogManager.Configuration.Reload();

Putting a breakpoint on the line immediately following, and digging into the LogManager.Configuration properties, I find that the File log target has this for its FileName property:

FileName="{gdc:item=logFileName}"

When I write to the logger, it creates a file in the application root called--you guessed it-- {gdc:item=logFileName} .

In the Command window, at a breakpoint immediately following the GDC set, I executed the null log action recommended by Mr Kristensen in his answer:

((NLog.Targets.FileTarget)LogManager.Configuration.AllTargets[1]).FileName.Render(NLog.LogEventInfo.CreateNullEvent())

The result was {gdc:item=logFileName}

In other words, it looks like the GDC layout renderer isn't working.

What am I doing wrong here?

Works as intended. FileName-property is a NLog Layout. Means it can resolve its value dynamically depending on LogEvent. When looking at the FileName-property using the debugger then you are not providing a LogEvent.

Try doing this in a debug-watch (Remember to correct {gdc} to ${gdc} )

fileTarget.FileName.Render(NLog.LogEventInfo.CreateNullEvent());

NLog Layout engine allows you to capture all kind of context-information, without adding it to the actual LogEvent. But can also extract context from the LogEvent .

See also https://nlog-project.org/config/?tab=layout-renderers and https://nlog-project.org/config/?tab=layouts

But ${gdc} is intended for global-variables and not for embedding layout-renderers. Instead you could configure like this:

<target name="logfile" xsi:type="File" fileName="${gdc:item=logDirectory}/nlog-all-${shortdate}.txt" ... />

And assign the GDC variable like this:

GlobalDiagnosticsContext.Set("logDirectory", @"c:\\Temp");

If you absolutely need layout-renderer logic embedded in the value, then you should consider using ${var} instead of ${gdc} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM