Skip to content
Rolf Kristensen edited this page Oct 29, 2023 · 18 revisions

NLog Layout allows converting a LogEvent into a formatted string, which is highly customizable. The most common used Layout-type is the SimpleLayout which allows one to combine one or many LayoutRenderers to generate customized output.

The default Layout for NLog Target is this:

${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}

Many more LayoutRenderers can be found here: https://nlog-project.org/config/?tab=layout-renderers

Besides SimpleLayout there also exists JsonLayout, XmlLayout, CsvLayout, etc. These are optimized for generating log-output that conforms to the expected dataformat. See also: https://nlog-project.org/config/?tab=layouts

Target Configuration with Layout

NLog Layout are often used (and it is also encouraged) as datatype for NLog Target configuration properties. Forexample the NLog FileTarget has FileName-property. This enables use of LayoutRenderers for specifying relative directory-path, or to find specifc log-directory-path from configuration-files (Ex. ${appsetting} or ${configsetting})

This allows one to keep environment specific configuration away from the pure NLog-configuration, and it instead lookup settings from deployed configuration-files or machine environment-variables using NLog LayoutRenderers.

Example ${configsetting:Options.ConnectionString} can lookup value from appsettings.json:

{
    "Options":{
        "ConnectionString":"UseDevelopmentStorage=true",
    }
}

Typed Layout

NLog 5.0 introduces Layout<T> that makes it even easier to use NLog Layout for configuration-options. Before one usually had to do this:

int eventId = 0;
string renderEventId = EventIdLayout.Render(logEvent);
if (string.IsNullOrEmpty(renderEventId) || !int.TryParse(renderEventId, out eventId))
{
    eventId = 42;   // fallback default value
}

Now with Layout<int> then one can do this:

int eventId = EventIdLayout.RenderValue(logEvent, defaultValue: 42);

Example

An example of a simple layout looks like:

layout="${machinename} ${message}"

This layout is used in the NLog.config file like:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="console" xsi:type="ColoredConsole" 
                layout="${machinename} ${message}"/>
    </targets>

    <rules>
        <logger name="*" minlevel="Trace" writeTo="console" />
    </rules>
</nlog>
Clone this wiki locally