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
NLog Layout-format recognizes the colon-character :
as option-delimiter, but only when used inside ${
and }
. To avoid unexpected results, then one can escape using back-slash like this: \:
. Ex. ${date:format=HH\:mm\:ss}
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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"> <targets> <target name="console" xsi:type="ColoredConsole" layout="${machinename} ${message}"/> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="console" /> </rules> </nlog>
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4