Reputation: 311
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?
Upvotes: 1
Views: 1325
Reputation: 19867
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}
.
Upvotes: 1