Skip to content

Environment specific NLog Logging Configuration

Rolf Kristensen edited this page Sep 12, 2023 · 35 revisions

Deploy NLog configuration file

NLog scans for its configuration file at multiple file locations. By making sure the installer-process deploys the environment specific NLog configuration-file to the install-folder, then NLog will load it automatically.

There also exists XML transformation tools, that can take a single XML-file and transform it to an environment-specific result-file.

Alternative approach is having a basic NLog.config file, and use the include-feature to apply environment-specific-overrides like this:

<nlog>
    <variable name="flushTimeout" value="60000" />

    <include file="nlog.local.config" ignoreErrors="true" />

    <targets>
       <target timeout="${flushTimeout}" />
    </targets>
</nlog>

And then deploy nlog.local.config that only contains the environment-specific overrides:

<nlog>
    <variable name="flushTimeout" value="30000" />
</nlog>

Include NLog configuration file

If the installer-process cannot decide what NLog configuration-file to deploy, then one can consider using the include-feature of the NLog configuration-file. Then one can have a basic NLog.config with the following contents:

<nlog>
     <include file="nlog_${environment:DOTNET_ENVIRONMENT}.config" ignoreErrors="true" />
</nlog>

It is also possible to setup NLog Global Diagnostic Context (GDC) and use ${gdc:Environment} inside the include="...". Make sure to make the setup before creating the first NLog Logger (as it will automatically load the NLog-configuration).

Explict load NLog configuration

It is possible to skip the automatic loading of NLog configuration by just explicit assigning the NLog configuration. Then one can load the configuration from any file-path:

NLog.LogManager.Setup().LoadConfigurationFromFile("D:/Config/NLog.LIVE.config");

Or load NLog configuration as XML-string, that have been retrieved from remote location/database:

NLog.LogManager.Setup().LoadConfigurationFromXml(xmlString);

See also: Explicit-NLog-configuration-loading

Setup with LoadConfigurationFromAppSettings

When using NLog.Web.AspNetCore then it is recommended to setup NLog Logging configuration early like this:

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");

This will automatically make NLog check these additional file-locations:

  • Looks for "NLog"-section in the appsettings.json file (with override from appsettings.Production.json or environment variables)
  • Looks for nlog.{environment}.config file, where {environment} can be specified as input-parameter to LoadConfigurationFromAppSettings() or automatically extracted from the machine environment-variables (Ex. DOTNET_ENVIRONMENT)

Resolve configuration from environment

The NLog Layouts makes it possible to resolve option-values from external sources. Instead of having environment-specific details as part of the NLog-configuration, then one resolve the value from other source. Ex:

  • ${environment} - From machine environment variables.
  • ${configsetting} - From appsettings.json (with override from appsettings.Production.json or environment variables)
  • ${appsetting} - From app.config with .NET Framework.
  • ${gdc} - From NLog Global Diagnostic Context (GDC), that can be assigned at early stage in the application.
  • Other Layout Renderers

This allows you to place environment specific Urls / API-keys / etc. in environment-specific configuration-files (or other places).

It can be useful to use :whenEmpty=DefaultValue to all specify a fallback value, if no value is available. Ex. ${environment:COMPANY_NAME:whenEmpty=Contoso}.

NLog configuration can also be loaded from appsettings.json, where Microsoft Extension Configuration System supports overrides of the default appsettings.json (Ex. appsettings.Production.json or environment variables)

Conditional NLog Target filters

Instead of maintaining multiple NLog configuration files, then one can consider just have a single NLog.config with conditional target output.

<nlog>
   <variable name="myLevel" value="Warn" />
    <rules>
      <logger minLevel="${var:myLevel}" writeTo="live_target" />
    </rules>
</nlog>

Then depending on the application environment then relevant targets output will be enabled. Ex:

#if DEBUG
LogManager.Configuration.Variables["myLevel"] = "Off";
LogManager.ReconfigExistingLoggers(); // Explicit refresh of Layouts and updates active Logger-objects
#endif

See also: Semi Dynamic Routing Rules

Clone this wiki locally