Question: In my application, I work on several thousand of document a day. I'd like, in some cases some logs, one log by document. Then I'd like for a specific target change the output filename (and only the filename) at runtime.

Around the web I found how to create a target by programming me I'd like just update a the filename by programming. I tried the code below. The error I receive is "LayoutRender cannot be found 'logDirectory'.

Any idea ?

Thanks,

```
var target = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
target.FileName = "${logDirectory}/file2.txt";

LoggingConfiguration config = new LoggingConfiguration();
var asyncFileTarget = new AsyncTargetWrapper(target);
config.AddTarget("logfile", asyncFileTarget);

LogManager.Configuration = config;

```

The config file is :

```
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <variable name="logDirectory" value="C:/MyLogs"/>
    <targets>
      <target name="logfile" xsi:type="File" layout="${date:format=dd/MM/yyyy HH\:mm\:ss.fff}|${level}|${stacktrace}|${message}" fileName="${logDirectory}/file.txt" />
    </targets>

    <rules>
      <logger name="*" minlevel="Info" writeTo="logfile" />
    </rules>    
  </nlog>

```

Answer: 
If not needing to change the LogDirectory at runtime, then you can do this:

```
target.FileName = "${var:logDirectory}\\file2.txt");

```

If needing to modify the logDirectory at runtime, then use the GDC:

<https://github.com/NLog/NLog/wiki/Gdc-layout-renderer>

```
NLog.GlobalDiagnosticsContext.Set("logDirectory","C:\Temp\");

```

Then you can use the following layout:

```
target.FileName = "${gdc:item=logDirectory}\\file2.txt";

```
This worked for me.

```
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;

var target = LogManager.Configuration.FindTargetByName("logfile");
var asyncTarget = target as AsyncTargetWrapper;
var fileTarget = asyncTarget.WrappedTarget as FileTarget;
var file = fileTarget.FileName;
var archiveFile = fileTarget.ArchiveFileName;

```

//FileName and ArchiveFileName are of type Layout. ToString gives the string representaion. We can change it and assign it back. Remember to put .Trim('\'') for removing the extra single quotes that gets added while converting to string.