10000 Var Layout Renderer · NLog/NLog Wiki · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Var Layout Renderer

Rolf Kristensen edited this page May 9, 2025 · 22 revisions

Render a NLog variable. The variable value can be set from the XML config and/or the API.

Platforms Supported: All

Introduced in 4.1, see also news post

⚠️ NLog Config Variables are very similar to global variables. They should stay immutable and not be updated for every logevent. There are better ways to include local context for a single LogEvent.

Performance is better when using NLog variables directly in config file (Ex. ${myvar}), instead of using this layout renderer that always performs dynamic lookup (Ex. ${var:myvar}). But this layout renderer reacts to NLog variables being modified at runtime.

Modifying NLog variables at runtime together with NLog configuration changes/reload can cause unexpected changes to NLog variables and produce unexpected output. Consider using GDC layout renderer for simple values, that doesn't make use of NLog Layout logic.

Configuration Syntax

${var:name=String:default=String}

Parameters

  • name - Name of the NLog variable. Required.
  • default - Default value to be used when the variable is not set. Not used if name is null

Example

<nlog>
  <variable name="user" value="admin" />
  <variable name="password" value="realgoodpassword" />      
  <targets>
    <target name="debug" type="Debug" layout="${message} and ${var:user}=${var:password}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" writeTo="debug" />
  </rules>
</nlog>

API

// create or edit
LogManager.Configuration.Variables["user"] = "admin";
LogManager.Configuration.Variables["password"] = "123";
// or remove
LogManager.Configuration.Variables.Remove("password");

Notes

  • Variables can be changed, deleted and created from the API
  • A default value can be configured for a variable, e.g. ${var:password:default=unknown}
  • The old variables can still be used and so this is completely backwards-compatible.
  • the <variable> is optional if no default is needed
  • Variables configured at runtime will be reset on autoReload="true", unless also using keepVariablesOnReload="true" (Before NLog 5.0 then keepVariablesOnReload was default false)
  • Variables configured at runtime will be reset when new NLog LoggingConfiguration is assigned (This is not the case for GDC layout renderer)
Clone this wiki locally
0