Category Archives: NLog

NLog embedding runtime variables

Sometimes you’ll want to set your NLog configuration up to output the log files to an environment, i.e. %APPDATA%/MyApp/Logging/UAT – but you’ll only know the selected environment at runtime.

This is where we can embed ${var:NAME}, where NAME is a key to your variable. In our case this will be ENV for environment.

So for example, let’s assume we have this fileName in your NLog configuration like this

fileName="${specialfolder:folder=ApplicationData}/MyApp/Logging/${var:ENV}/logfile_{$shortdate}.log

As you can see from the above, we’ve included the built-in specialfolder and shortdate variables. For the ${var:ENV} we need to supply using “env” variable in our code, for example

LogManager.Configurations.Variables["env"] = GetCurrentEnvironment()