Change basedir in NLog Targets in runtime programmatically

It's easier to use variables in this case. (${var:...})

For this example:

<variable name="basedir" value="${basedir}" />    <!-- default, optional -->

<targets>
   <target name="asyncFileLog" xsi:type="AsyncWrapper">
     <target name="logfileTrace" xsi:type="File" 
             fileName="${var:basedir}/logs/${shortdate}Trace.log" 
             layout="${longdate} ${message}" lineEnding="Default"/> 
   </target>
   ...

Changing the variable in C#

// create or edit
LogManager.Configuration.Variables["basedir"] = "d:/mybasedir";

No need for LogManager.ReconfigExistingLoggers(); or looping over all the targets!

See also the ${var} documentation

Update: in this case your are reading from .config files, this could be done with only NLog configuration (no C# needed!)

Install NLog.Extended and use ${appsetting:name=..}

e.g.

fileName="${var:basedir}/logs/${appsetting:name=RutaLog}Trace.log" 

See also the ${appsetting} documentation

Tags:

C#

Nlog