-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Layouts
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
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",
}
}
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);
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>
- Troubleshooting Guide - See available NLog Targets and Layouts: https://nlog-project.org/config
- Getting started
- How to use structured logging
- Troubleshooting
- FAQ
- Articles about NLog
-
All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json