diff --git a/wiki/404.html b/wiki/404.html new file mode 100644 index 000000000..6c6decffc --- /dev/null +++ b/wiki/404.html @@ -0,0 +1,1294 @@ + + + + + + + + NLog Wiki + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • +
  • +
  • +
+
+
+
+
+ + +

404

+ +

Page not found

+ + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + + +
+ + + + + + + + + diff --git a/wiki/All-Event-Properties-Layout-Renderer/index.html b/wiki/All-Event-Properties-Layout-Renderer/index.html new file mode 100644 index 000000000..ccd9f83a3 --- /dev/null +++ b/wiki/All-Event-Properties-Layout-Renderer/index.html @@ -0,0 +1,1339 @@ + + + + + + + + All Event Properties Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Log event all context data.

+
+

Platforms Supported: All

+

Introduced in NLog v4.0.

+
+

To log one property, use ${event-properties}. See also NLog Context.

+

Configuration Syntax

+
${all-event-properties:format=String:separator=String:includeEmptyValues=boolean:includeScopeProperties=boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • format - How key/value pairs will be formatted. The placeholder used to define placement of the key is, [key], and the placeholder for value is, [value].
  • +
  • Default value: [key]=[value]
  • +
  • separator - The string that will be used to separate key/value pairs. Default value: ,
  • +
  • includeCallerInformation - Also render the caller information attributes? Default: false
    +

    Introduced in NLog 4.1. Deprecated with NLog v4.6.8. Removed again with NLog v5 (Net45 required)

    +
    +
  • +
  • includeEmptyValues - include empty values? A value is empty when null or in case of a string, null or empty string. Default value: false
    +

    Introduced in NLog 4.6.4.

    +
    +
  • +
  • exclude - LogEvent property-key-names to exclude from output. List of keys can be passed as comma separated values, e.g.: Key1,Key2
    +

    Introduced in NLog 4.6.8

    +
    +
  • +
  • includeScopeProperties - Include ScopeContext Properties together with LogEvent Properties.
    +

    Introduced in NLog 5.0

    +
    +
  • +
+

Examples

+

See EventProperties-Layout-Renderer

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AppDomain-Layout-Renderer/index.html b/wiki/AppDomain-Layout-Renderer/index.html new file mode 100644 index 000000000..8f72765e4 --- /dev/null +++ b/wiki/AppDomain-Layout-Renderer/index.html @@ -0,0 +1,1333 @@ + + + + + + + + AppDomain Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render the application domain name.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${appdomain:format=Format}
+
+

Parameters

+

Rendering Options

+
    +
  • format - The formating. Default to Long. +possible options:
  • +
  • Long - default. The id as four number digit, colon, friendlyname. E.g. 0003:NLog.UnitTests
  • +
  • Short - Only the id as two number digit, like "03".
  • +
  • Friendly - Just the AppDomain FriendlyName. E.g. NLog.UnitTests + > Introduced with NLog v5.2.7
  • +
  • or custom like {0} - {1}. The first parameter is the"AppDomain.Id", the second is the "AppDomain.FriendlyName". Note: use escaping of the brackets. See examples.
  • +
+

Example

+

Examples in the .config

+
${appdomain} //e.g. 0003:NLog.UnitTests
+${appdomain:format=short} //e.g. 03
+${appdomain:format=long} //e.g. 0003:NLog.UnitTests
+${appdomain:format={1\} - {0\}} //e.g. NLog.UnitTests - 3
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AppSetting-Layout-Renderer/index.html b/wiki/AppSetting-Layout-Renderer/index.html new file mode 100644 index 000000000..4381b4151 --- /dev/null +++ b/wiki/AppSetting-Layout-Renderer/index.html @@ -0,0 +1,1354 @@ + + + + + + + + AppSetting Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Value from the App Settings configuration (app.config / web.config)

+
+

Platforms Supported: Limited (.NET Framework only, when using .NET Core then ${configsetting} can be used to read values from appsettings.json-file)

+

Introduced with NLog 3.0 and with NLog 4.6+ it was included in default NLog-package without needing NLog.Extended.

+
+

Configuration Syntax

+
${appsetting:item=String:default=String}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Key in the apps setting. Required
    +

    Introduced with NLog v4.5, and replaces the Name-option.

    +
    +
  • +
  • Default - Default value if not present. Optional.
  • +
+

Example AppSettings

+

Example .config

+
<configuration>
+  <appSettings>
+    <add key="MyKey" value="MyApplication" />
+  </appSettings>
+</configuration>
+
+

Example renderer: produces MyApplication is this case:

+
${appsetting:item=MyKey:default=mydefault}
+
+

Example#2 renderer: produces mydefault is this case:

+
${appsetting:item=MyKey2:default=mydefault}
+
+

Example ConnectionStrings

+

Introduced with NLog 4.6.5

+
<configuration>
+  <appSettings>
+    <add key="MyKey" value="MyApplication" />
+  </appSettings>
+  <connectionStrings>
+    <add name="ElasticUrl" connectionString="http://localhost:9200"/>
+  </connectionStrings>
+</configuration>
+
+

Example#3 renderer: produces http://localhost:9200 is this case:

+
${appsetting:item=connectionStrings.ElasticUrl}
+
+

Note remember to uninstall/remove NLog.Extended-nuget-package from the application when having upgraded to NLog v4.6.5, else connectionStrings-lookup will not work.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-AppBasePath-layout-renderer/index.html b/wiki/AspNet-AppBasePath-layout-renderer/index.html new file mode 100644 index 000000000..19489288c --- /dev/null +++ b/wiki/AspNet-AppBasePath-layout-renderer/index.html @@ -0,0 +1,1319 @@ + + + + + + + + AspNet AppBasePath layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET AppBasePath (Content Root)

+
+

Platforms Supported: All (Supported in Asp.NET and Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v4.5.0 and NLog.Web v4.5.2

+

See also ${processdir} , ${basedir} , ${aspnet-webrootpath}

+
+

Configuration Syntax

+
${aspnet-appbasepath}
+
+

Remarks

+

Application base path is also known as the content root, while wwwroot-path is root directory for static content.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Environment-layout-renderer/index.html b/wiki/AspNet-Environment-layout-renderer/index.html new file mode 100644 index 000000000..3c31ae074 --- /dev/null +++ b/wiki/AspNet-Environment-layout-renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + AspNet Environment layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET EnvironmentName (ASPNETCORE_ENVIRONMENT)

+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v4.4.0

+
+

Configuration Syntax

+
${aspnet-environment}
+
+

Remarks

+

The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or "environment" as specified in any other configuration source.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-HttpContext-Item-Layout-Renderer/index.html b/wiki/AspNet-HttpContext-Item-Layout-Renderer/index.html new file mode 100644 index 000000000..f391f829d --- /dev/null +++ b/wiki/AspNet-HttpContext-Item-Layout-Renderer/index.html @@ -0,0 +1,1349 @@ + + + + + + + + AspNet HttpContext Item Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Item variable from HttpContext.Items dictionary. Useful for storing state per request basis.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${aspnet-item:variable=String:objectpath=String:format=String}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Key for lookup in Items-dictionary (Required)
    +

    Introduced with NLog.Web v5.1, and replaces the Variable-option

    +
    +
  • +
  • format - Format-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • culture - Culture-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • objectpath - Property path if the value is an object, also supports nested properties (Optional).
    +

    Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties-option

    +
    +
  • +
+

Examples

+

You can set the value of an ASP.NET Item variable by using the following code:

+

Example usage of ${aspnet-item}

+
HttpContext.Items["myvariable"] = 123;
+HttpContext.Items["stringvariable"] = "aaa BBB";
+HttpContext.Items["anothervariable"] = DateTime.Now;
+
+${aspnet-item:variable=myvariable} - produces "123"
+${aspnet-item:variable=anothervariable} - produces "01/01/2006 00:00:00"
+${aspnet-item:variable=anothervariable:culture=pl-PL} - produces "2006-01-01 00:00:00"
+${aspnet-item:variable=myvariable:padding=5} - produces "  123"
+${aspnet-item:variable=myvariable:padding=-5} - produces "123  "
+${aspnet-item:variable=stringvariable:upperCase=true} - produces "AAA BBB"
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-MVC-Action-Layout-Renderer/index.html b/wiki/AspNet-MVC-Action-Layout-Renderer/index.html new file mode 100644 index 000000000..3a7f7432b --- /dev/null +++ b/wiki/AspNet-MVC-Action-Layout-Renderer/index.html @@ -0,0 +1,1319 @@ + + + + + + + + AspNet MVC Action Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET MVC Action-Name by lookup of action-value in HttpContext.Current.GetRouteData

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-mvc-action}
+
+

Remarks

+

Use this layout renderer to insert the Action Method from MVC Pipeline.

+

See also AspNetRequest-RouteParameters-Layout-Renderer for lookup of other Route-Parameter Values.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-MVC-Controller-Layout-Renderer/index.html b/wiki/AspNet-MVC-Controller-Layout-Renderer/index.html new file mode 100644 index 000000000..ca04c3f8e --- /dev/null +++ b/wiki/AspNet-MVC-Controller-Layout-Renderer/index.html @@ -0,0 +1,1319 @@ + + + + + + + + AspNet MVC Controller Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET MVC Controller-Name by lookup of controller-value in HttpContext.Current.GetRouteData

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-mvc-controller}
+
+

Remarks

+

Use this layout renderer to insert the Controller from MVC Pipeline.

+

See also AspNetRequest-RouteParameters-Layout-Renderer for lookup of other Route-Parameter Values.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Bidirectional-Stream-Layout-Renderer/index.html b/wiki/AspNet-Request-Bidirectional-Stream-Layout-Renderer/index.html new file mode 100644 index 000000000..957edd2a8 --- /dev/null +++ b/wiki/AspNet-Request-Bidirectional-Stream-Layout-Renderer/index.html @@ -0,0 +1,1320 @@ + + + + + + + + AspNet Request Bidirectional Stream Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET Request capable of upgrading connection to an opaque, bidirectional stream.

+
    +
  • 1 = Capable / Upgradable
  • +
  • 0 = Not available
  • +
+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-bidirectional-stream}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Client-Certificate-Layout-Renderer/index.html b/wiki/AspNet-Request-Client-Certificate-Layout-Renderer/index.html new file mode 100644 index 000000000..b5a2d16a1 --- /dev/null +++ b/wiki/AspNet-Request-Client-Certificate-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request Client Certificate Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET Request Client Certificate

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-client-certificate}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-ConnectionId-Layout-Renderer/index.html b/wiki/AspNet-Request-ConnectionId-Layout-Renderer/index.html new file mode 100644 index 000000000..1ce95876a --- /dev/null +++ b/wiki/AspNet-Request-ConnectionId-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request ConnectionId Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Http Request Connection Id. The unique identifier that represents the connection.

+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-connection-id}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-ContentLength-Layout-Renderer/index.html b/wiki/AspNet-Request-ContentLength-Layout-Renderer/index.html new file mode 100644 index 000000000..f79680124 --- /dev/null +++ b/wiki/AspNet-Request-ContentLength-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request ContentLength Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request Header Content-Length (Ex. 1234)

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.0.0 and NLog.Web v5.0.0

+
+

Configuration Syntax

+
${aspnet-request-contentlength}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-ContentType-layout-renderer/index.html b/wiki/AspNet-Request-ContentType-layout-renderer/index.html new file mode 100644 index 000000000..b1bb1438d --- /dev/null +++ b/wiki/AspNet-Request-ContentType-layout-renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request ContentType layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Content-Type header (Ex. application/json)

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v4.4.0 and NLog.Web v4.8.0

+
+

Configuration Syntax

+
${aspnet-request-contenttype}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Duration-Layout-Renderer/index.html b/wiki/AspNet-Request-Duration-Layout-Renderer/index.html new file mode 100644 index 000000000..5a0b63a71 --- /dev/null +++ b/wiki/AspNet-Request-Duration-Layout-Renderer/index.html @@ -0,0 +1,1321 @@ + + + + + + + + AspNet Request Duration Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request Duration.

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.0.0 and NLog.Web v5.0.0

+
+

Configuration Syntax

+
${aspnet-request-duration}
+
+

Options

+
    +
  • format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format). string. Default null (Outputs milliseconds)
  • +
  • Culture - The culture used for rendering. Default CultureInfo.InvariantCulture
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-EndPoint-Group-Layout-Renderer/index.html b/wiki/AspNet-Request-EndPoint-Group-Layout-Renderer/index.html new file mode 100644 index 000000000..d91da6a07 --- /dev/null +++ b/wiki/AspNet-Request-EndPoint-Group-Layout-Renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + AspNet Request EndPoint Group Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Http Request EndPoint MetaData Group-Name. The group name of the logical endpoint in the application. Assigned using WithGroupName or [EndpointGroupName].

+
+

Platforms Supported: Limited (Only supported in ASP.NET Core v3+)

+

Introduced with NLog.Web.AspNetCore v6.0.3

+
+

Configuration Syntax

+
${aspnet-request-endpoint-group}
+
+

Notes

+

See also ${aspnet-request-endpoint} and ${aspnet-request-endpoint-name}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-EndPoint-Layout-Renderer/index.html b/wiki/AspNet-Request-EndPoint-Layout-Renderer/index.html new file mode 100644 index 000000000..a574a03eb --- /dev/null +++ b/wiki/AspNet-Request-EndPoint-Layout-Renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + AspNet Request EndPoint Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Http Request EndPoint. The informational display name of the logical endpoint in the application (Ex. HTTP: GET /weatherforecast)

+
+

Platforms Supported: Limited (Only supported in ASP.NET Core v3+)

+

Introduced with NLog.Web.AspNetCore v5.3

+
+

Configuration Syntax

+
${aspnet-request-endpoint}
+
+

Notes

+

See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint-name}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-EndPoint-Name-Layout-Renderer/index.html b/wiki/AspNet-Request-EndPoint-Name-Layout-Renderer/index.html new file mode 100644 index 000000000..84315e3f2 --- /dev/null +++ b/wiki/AspNet-Request-EndPoint-Name-Layout-Renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + AspNet Request EndPoint Name Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Http Request EndPoint MetaData Name. The name of the logical endpoint in the application. Assigned using WithName or [EndpointName].

+
+

Platforms Supported: Limited (Only supported in ASP.NET Core v3+)

+

Introduced with NLog.Web.AspNetCore v6.0.3

+
+

Configuration Syntax

+
${aspnet-request-endpoint-name}
+
+

Notes

+

See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-HTTP-Transport-Type-Layout-Renderer/index.html b/wiki/AspNet-Request-HTTP-Transport-Type-Layout-Renderer/index.html new file mode 100644 index 000000000..8be2ff0ff --- /dev/null +++ b/wiki/AspNet-Request-HTTP-Transport-Type-Layout-Renderer/index.html @@ -0,0 +1,1322 @@ + + + + + + + + AspNet Request HTTP Transport Type Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET supported transport types that the client can use to send HTTP requests (bitwise combination).

+
    +
  • None (0) - Specifies that no transport is used.
  • +
  • WebSockets (1) - Specifies that the web sockets transport is used.
  • +
  • ServerSentEvents (2) - Specifies that the server sent events transport is used.
  • +
  • LongPolling (4) - Specifies that the long polling transport is used.
  • +
+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-http-transport-type}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Has-Posted-Body-Layout-Renderer/index.html b/wiki/AspNet-Request-Has-Posted-Body-Layout-Renderer/index.html new file mode 100644 index 000000000..b1f99624c --- /dev/null +++ b/wiki/AspNet-Request-Has-Posted-Body-Layout-Renderer/index.html @@ -0,0 +1,1320 @@ + + + + + + + + AspNet Request Has Posted Body Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET Http Request includes posted-body payload:

+
    +
  • 1 = CanHaveBody or ContentLength > 0
  • +
  • 0 = Not available
  • +
+
+

Platforms Supported: > Platforms Supported: Limited (Only supported in ASP.NET Core v5+)

+

Introduced with NLog.Web.AspNetCore v5.1.1

+
+

Configuration Syntax

+
${aspnet-request-has-posted-body}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-IP-Layout-Renderer/index.html b/wiki/AspNet-Request-IP-Layout-Renderer/index.html new file mode 100644 index 000000000..e88e8be2d --- /dev/null +++ b/wiki/AspNet-Request-IP-Layout-Renderer/index.html @@ -0,0 +1,1337 @@ + + + + + + + + AspNet Request IP Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render Client IP address

+
+

Platforms Supported: All

+

Introduced in NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0

+
+

Configuration Syntax

+
${aspnet-request-ip}
+
+

Parameters

+
    +
  • +

    CheckForwardedForHeader - Should check value of X-Forwarded-For header (Default = false)

    +
    +

    Introduced with NLog Web.AspNetCore 4.7.1 & NLog.Web 4.7.1

    +
    +
  • +
  • +

    CheckForwardedForHeaderOffset - Should check value of X-Forwarded-For header and specify index-offset from comma-separated-split-array (Default = 0)

    +
    +

    Introduced with NLog Web.AspNetCore 5.2.2

    +
    +
  • +
+

Remarks

+ +

See also AspNetRequest Host Layout Renderer

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Inherent-KeepAlive-Layout-Renderer/index.html b/wiki/AspNet-Request-Inherent-KeepAlive-Layout-Renderer/index.html new file mode 100644 index 000000000..5ae6487ab --- /dev/null +++ b/wiki/AspNet-Request-Inherent-KeepAlive-Layout-Renderer/index.html @@ -0,0 +1,1321 @@ + + + + + + + + AspNet Request Inherent KeepAlive Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET Request using connection transport capable of "inherent keep-alive"

+
    +
  • 1 - Can inform the client whether connection is still active.
  • +
  • 0 = inherent keep-alive not available.
  • +
+

The most common example of this feature is the Long Polling HTTP transport

+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-inherent-keep-alive}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-IsWebSocket-Layout-Renderer/index.html b/wiki/AspNet-Request-IsWebSocket-Layout-Renderer/index.html new file mode 100644 index 000000000..01634a9f6 --- /dev/null +++ b/wiki/AspNet-Request-IsWebSocket-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request IsWebSocket Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request HttpContext.WebSockets.IsWebSocketRequest as 1 or 0

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-is-web-socket}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Local-IP-Layout-Renderer/index.html b/wiki/AspNet-Request-Local-IP-Layout-Renderer/index.html new file mode 100644 index 000000000..971b75e74 --- /dev/null +++ b/wiki/AspNet-Request-Local-IP-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request Local IP Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request HttpContext.Connection.LocalIpAddress

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-local-ip}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Local-Port-Layout-Renderer/index.html b/wiki/AspNet-Request-Local-Port-Layout-Renderer/index.html new file mode 100644 index 000000000..91a41c92f --- /dev/null +++ b/wiki/AspNet-Request-Local-Port-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request Local Port Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request HttpContext.Connection.LocalPort

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-local-port}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Remote-Port-Layout-Renderer/index.html b/wiki/AspNet-Request-Remote-Port-Layout-Renderer/index.html new file mode 100644 index 000000000..418dece73 --- /dev/null +++ b/wiki/AspNet-Request-Remote-Port-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request Remote Port Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request HttpContext.Connection.RemotePort

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-remote-port}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-ServerVariable-Layout-Renderer/index.html b/wiki/AspNet-Request-ServerVariable-Layout-Renderer/index.html new file mode 100644 index 000000000..f931f35b4 --- /dev/null +++ b/wiki/AspNet-Request-ServerVariable-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request ServerVariable Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render ASP.NET Server Variable (Ex. APP_POOL_ID)

+
+

Platforms Supported: All

+

Introduced in NLog Web.AspNetCore 5.1.0 & NLog.Web 5.1.0

+
+

Configuration Syntax

+
${aspnet-request-servervariable:item=APP_POOL_ID}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-StreamId-Layout-Renderer/index.html b/wiki/AspNet-Request-StreamId-Layout-Renderer/index.html new file mode 100644 index 000000000..19d18b30b --- /dev/null +++ b/wiki/AspNet-Request-StreamId-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Request StreamId Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Http Request Stream Id. The unique identifier that represents the reusable socket.

+
+

Platforms Supported: Limited (Only supported in ASP.NET Core v5+)

+

Introduced with NLog.Web.AspNetCore v5.1.1

+
+

Configuration Syntax

+
${aspnet-request-stream-id}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-TLS-Handshake-Layout-Renderer/index.html b/wiki/AspNet-Request-TLS-Handshake-Layout-Renderer/index.html new file mode 100644 index 000000000..40d06061c --- /dev/null +++ b/wiki/AspNet-Request-TLS-Handshake-Layout-Renderer/index.html @@ -0,0 +1,1336 @@ + + + + + + + + AspNet Request TLS Handshake Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET TLS Handshake Features ITlsHandshakeFeature of the connection.

+
+

Platforms Supported: Limited (Only supported in ASP.NET Core)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-tls-handshake:property=Protocol}
+
+

Property Enum

+
    +
  • CipherAlgorithm - Gets the CipherAlgorithmType.
  • +
  • CipherStrength - Gets the cipher strength.
  • +
  • HashAlgorithm - Gets the HashAlgorithmType.
  • +
  • HashStrength - Gets the hash strength.
  • +
  • KeyExchangeAlgorithm - Gets the ExchangeAlgorithmType.
  • +
  • KeyExchangeStrength - Gets the key exchange algorithm strength.
  • +
  • Protocol - Gets the SslProtocols.
  • +
  • HostName - Gets the host name from the "server_name" (SNI) extension. See RFC 6066
    +

    Introduced with NLog.Web.AspNetCore v6.1.0

    +
    +
  • +
  • NegotiatedCipherSuite - Gets the TlsCipherSuite
    +

    Introduced with NLog.Web.AspNetCore v6.1.0

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-TLS-Token-Bindng-Layout-Renderer/index.html b/wiki/AspNet-Request-TLS-Token-Bindng-Layout-Renderer/index.html new file mode 100644 index 000000000..bc9655ea5 --- /dev/null +++ b/wiki/AspNet-Request-TLS-Token-Bindng-Layout-Renderer/index.html @@ -0,0 +1,1325 @@ + + + + + + + + AspNet Request TLS Token Bindng Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET TLS Token Bindings for Provider and Referrer

+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-tls-token-binding:property=provider}
+
+

Options

+
    +
  • Property - Tls Token Binding Source
  • +
  • Provider - Tls Token Binding for Provider
  • +
  • Referrer - Tls Token Binding for Referrer
  • +
  • Format - Tls Token Binding Format
  • +
  • Base64 - Emit the byte array using Convert.ToBase64(byte[])
  • +
  • Hex - Emit the byte array using BitConverter.ToString(byte[])
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Tracking-Consent-Layout-Renderer/index.html b/wiki/AspNet-Request-Tracking-Consent-Layout-Renderer/index.html new file mode 100644 index 000000000..1a5447430 --- /dev/null +++ b/wiki/AspNet-Request-Tracking-Consent-Layout-Renderer/index.html @@ -0,0 +1,1323 @@ + + + + + + + + AspNet Request Tracking Consent Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET Tracking Consent

+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-tracking-consent:property=CanTrack}
+
+

Options

+
    +
  • Property - Enum Values:
  • +
  • CanTrack - Indicates either if consent has been given (1), or if consent is not required (0)
  • +
  • HasConsent - Indicates if consent was given.
  • +
  • IsConsentNeeded - Indicates if consent is required for the given request.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-Trailers-Layout-Renderer/index.html b/wiki/AspNet-Request-Trailers-Layout-Renderer/index.html new file mode 100644 index 000000000..751ea0f28 --- /dev/null +++ b/wiki/AspNet-Request-Trailers-Layout-Renderer/index.html @@ -0,0 +1,1341 @@ + + + + + + + + AspNet Request Trailers Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request Trailers

+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-request-trailersitems=String[]:outputFormat=Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Options

+

Rendering Options

+
    +
  • Items - Trailer names to be rendered. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the TrailerNames-option.

    +
    +
  • +
  • Exclude - Trailer names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-WebSocket-Requested-Protocols-Layout-Renderer/index.html b/wiki/AspNet-Request-WebSocket-Requested-Protocols-Layout-Renderer/index.html new file mode 100644 index 000000000..7eb71c2e6 --- /dev/null +++ b/wiki/AspNet-Request-WebSocket-Requested-Protocols-Layout-Renderer/index.html @@ -0,0 +1,1329 @@ + + + + + + + + AspNet Request WebSocket Requested Protocols Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET Request HttpContext.WebSockets.WebSocketRequestedProtocols

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 (NET46)

+
+

Configuration Syntax

+
${aspnet-request-web-socket-requested-protocols}
+
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • +

    JsonArray - Key-value-pair in JSON-array

    +
  • +
  • +

    itemSeparator Separator between items. Default: ,. Only applies when OutputFormat is Flat.

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Request-posted-body-layout-renderer/index.html b/wiki/AspNet-Request-posted-body-layout-renderer/index.html new file mode 100644 index 000000000..cb7886254 --- /dev/null +++ b/wiki/AspNet-Request-posted-body-layout-renderer/index.html @@ -0,0 +1,1411 @@ + + + + + + + + AspNet Request posted body layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render the posted body, e.g. FORM or Ajax POST

+
+

Platforms Supported: All

+

Introduced in NLog.Web.AspNetCore v5.1.0 using NLogRequestPostedBodyMiddleware, and in NLog.Web v5.1.0 using NLogRequestPostedBodyModule.

+

⚠️ All versions before NLog.Web.AspNetCore v5.1.0 had incorrect implementation of ${aspnet-request-posted-body}, that caused random failures for the Web-Application.

+
+

Configuration Syntax

+
${aspnet-request-posted-body}
+
+

ASP.NET Core Setup

+
    +
  • NLog.Web.AspNetCore 5.1.0+
  • +
  • Register NLogRequestPostedBodyMiddleware as middleware in the Configure method of Startup class
  • +
  • The middelware will activate EnablesBuffering when matching the criteria.
  • +
+
  // needed for  ${aspnet-request-posted-body} with an API Controller.
+  // The options default to only logging a maximum of 30KB, since above that the ASP.NET Core framework
+  // uses a temporary file on disk instead of a memory buffer.  
+  // Also, only content types starting with ‘text/‘, or those ending with ‘xml’, ‘html’, ‘json’, or content types
+  // that have the word ‘charset’ are logged, since we desire to log strings and not binary content
+  // Those can be overridden in the options if necessary.  But typically the default options should be adequate.
+  app.UseMiddleware<NLog.Web.NLogRequestPostedBodyMiddleware>
+        (new NLog.Web.NLogRequestPostedBodyMiddlewareOptions());
+
+

Full Example:

+
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+    {
+        if (env.IsDevelopment())
+        {
+            app.UseDeveloperExceptionPage();
+        }
+        else
+        {
+            app.UseExceptionHandler("/Home/Error");
+            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
+            app.UseHsts();
+        }
+        app.UseHttpsRedirection();
+        app.UseStaticFiles();
+        app.UseRouting();
+        app.UseAuthorization();
+
+        // needed for  ${aspnet-request-posted-body} with an API Controller.
+        app.UseMiddleware<NLog.Web.NLogRequestPostedBodyMiddleware>(
+            new NLog.Web.NLogRequestPostedBodyMiddlewareOptions());
+
+        app.UseEndpoints(endpoints =>
+        {
+            endpoints.MapControllerRoute(
+                name: "default",
+                pattern: "{controller=Home}/{action=Index}/{id?}");
+        });
+
+

NLogRequestPostedBodyMiddleware Options + - int MaxContentLength + - The maximum request posted body that will be captured. Defaults to 30 KB.
+ - HttpRequest.EnableBuffer() is documented as using memory buffer until 30 KB, then this will use temp files on disk, which could have a performance impact.

+
    +
  • +

    IList<KeyValuePair<string,string>> AllowContentTypes

    +
      +
    • The Key is the prefix value such as ‘text’.
    • +
    • The Value is the suffix value such as ‘html’.
    • +
    • The default contents of this property are:
    • +
    • 'application/', 'json'
    • +
    • 'application/', 'xml'
    • +
    • 'application/', 'html'
    • +
    • 'text/', ''
    • +
    • '', 'charset'
    • +
    +
  • +
  • +

    Predicate<HttpContext> ShouldCapture()

    +
      +
    • By default this method returns true if
        +
      • The content length is not null and is <= MaxContentLength
      • +
      • The content type must match one of the entries in the AllowContentTypes List.
      • +
      • For a match the ContentType must StartsWith the Key, case insensitive, and also have an IndexOf the Value, case insensitive.
      • +
      • An empty string for the Key or for the Value acts as a wildcard match.
      • +
      • The method has the HttpContext as the parameter, so a user wishing to override this property should have all the properties required to implement an override.
      • +
      +
    • +
    +
  • +
+

See also: HTTP-Request-Logging

+

ASP.NET Setup

+
    +
  • NLog.Web 5.1.0+
  • +
+

To use this target with NLog.Web, then you need to enable the HttpModule NLogRequestPostedBodyModule:

+
  public class MyGlobalApplication : System.Web.HttpApplication
+  {
+     public static IHttpModule NLogRequestPostedBody = new NLog.Web.NLogRequestPostedBodyModule();
+
+     public override void Init()
+     {
+         base.Init();
+         NLogRequestPostedBody.Init(this);
+     }
+  }
+
+

See also: HTTP-Request-Logging

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Response-ContentLength-Layout-Renderer/index.html b/wiki/AspNet-Response-ContentLength-Layout-Renderer/index.html new file mode 100644 index 000000000..9192bff11 --- /dev/null +++ b/wiki/AspNet-Response-ContentLength-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Response ContentLength Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Response Header Content-Length (Ex. 1234)

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.0.0 and NLog.Web v5.0.0

+
+

Configuration Syntax

+
${aspnet-response-contentlength}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Response-ContentType-Layout-Renderer/index.html b/wiki/AspNet-Response-ContentType-Layout-Renderer/index.html new file mode 100644 index 000000000..026189677 --- /dev/null +++ b/wiki/AspNet-Response-ContentType-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Response ContentType Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Response Header Content-Type (Ex. application/json)

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0

+
+

Configuration Syntax

+
${aspnet-response-contenttype}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Response-Cookie-Layout-Renderer/index.html b/wiki/AspNet-Response-Cookie-Layout-Renderer/index.html new file mode 100644 index 000000000..4d3863981 --- /dev/null +++ b/wiki/AspNet-Response-Cookie-Layout-Renderer/index.html @@ -0,0 +1,1400 @@ + + + + + + + + AspNet Response Cookie Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Renders the Cookie Name and Values stored in the ASP.NET Response Cookies collection.

+
+

Platforms Supported: All

+

Introduced in NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0

+
+

Configuration Syntax

+
${aspnet-response-cookie:items=String[]:outputFormat=Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • items - Cookie key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the cookieNames-option.

    +
    +
  • +
  • exclude - Cookie key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array
  • +
  • +

    JsonDictionary - Key-value-pair as JSON-dictionary.

    +
  • +
  • +

    itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.

    +
  • +
  • valueSeparator - Separator between key and value. Default: =. Only applies when OutputFormat is Flat.
  • +
  • objectSeparator - Separator between object-collections of key-value-pair-items. Default: ;. Only applies when OutputFormat is Flat and Verbose is True.
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1

    +
    +
  • +
  • Verbose - Render additional properties of the HttpCookie-object (Domain, Path, Expires, Secure, HttpOnly).
  • +
+

Examples

+

In C# code:

+
Request.Cookies["key1"] = "value1";
+Request.Cookies["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+ +
${aspnet-response-cookie:CookieNames=key1}
+
+

Will print:

+
"key1=value1"
+
+

Log multiple cookies in default Flat output format

+
${aspnet-response-cookie:items=key1,id}
+
+

Will print:

+
"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+ +
${aspnet-response-cookie:items=key1:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1"}]
+
+

Log multiple cookies in JSON output format

+
${aspnet-response-cookie:items=key1,id:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+ +
${aspnet-response-cookie:items=key1:OutputFormat=JsonDictionary}
+
+

Will print:

+
{"key1":"value1"}
+
+ +
${aspnet-response-cookie:items=key1:ValuesOnly=true}
+
+

Will print:

+
"value1"
+
+ +
${aspnet-response-cookie:items=key1:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1"]
+
+

Log multiple cookies in JSON output format as value only

+
${aspnet-response-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Response-HTTPS-Compression-Layout-Renderer/index.html b/wiki/AspNet-Response-HTTPS-Compression-Layout-Renderer/index.html new file mode 100644 index 000000000..7604e6931 --- /dev/null +++ b/wiki/AspNet-Response-HTTPS-Compression-Layout-Renderer/index.html @@ -0,0 +1,1321 @@ + + + + + + + + AspNet Response HTTPS Compression Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

ASP.NET Response HTTPS Compression Mode

+
    +
  • Default (0) - No value has been specified, use the configured defaults.
  • +
  • DoNotCompress (1) - Opts out of compression over HTTPS. Enabling compression on HTTPS requests for remotely manipulable content may expose security problems.
  • +
  • Compress (2) - Opts into compression over HTTPS. Enabling compression on HTTPS requests for remotely manipulable content may expose security problems.
  • +
+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-response-https-compression}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Response-HasStarted-Layout-Renderer/index.html b/wiki/AspNet-Response-HasStarted-Layout-Renderer/index.html new file mode 100644 index 000000000..616068f78 --- /dev/null +++ b/wiki/AspNet-Response-HasStarted-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet Response HasStarted Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Http Response HasStarted (as 0 or 1)

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 NET46

+
+

Configuration Syntax

+
${aspnet-response-has-started}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Response-Headers-Layout-Renderer/index.html b/wiki/AspNet-Response-Headers-Layout-Renderer/index.html new file mode 100644 index 000000000..ffa9f87ee --- /dev/null +++ b/wiki/AspNet-Response-Headers-Layout-Renderer/index.html @@ -0,0 +1,1396 @@ + + + + + + + + AspNet Response Headers Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Response Headers key/value pairs.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 5.1.0 and NLog.Web.AspNetCore 5.1.0

+
+

Configuration Syntax

+
${aspnet-response-headers:items=String[]:outputFormat=Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • items - Header key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the headerNames-option.

    +
    +
  • +
  • exclude - Header key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1

    +
    +
  • +
+

Remarks

+

Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Response Headers collection.

+

Examples

+

In C# code:

+
Response.Headers["key1"] = "value1";
+Response.Headers["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+

Log single header in default Flat output format

+
${aspnet-response-headers:items=key1}
+
+

Will print:

+
"key1=value1"
+
+

Log multiple headers in default Flat output format

+
${aspnet-response-headers:items=key1,id}
+
+

Will print:

+
"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+

Log single header ie in JSON output format

+
${aspnet-response-headers:items=key1:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1"}]
+
+

Log multiple headers in JSON output format

+
${aspnet-response-headers:items=key1,id:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+

Log single header as JSON dictionary:

+
${aspnet-response-headers:items=key1:OutputFormat=JsonDictionary}
+
+

Will print:

+
{"key1":"value1"}
+
+

Log single header in Flat output format as value only

+
${aspnet-response-headers:items=key1:ValuesOnly=true}
+
+

Will print:

+
"value1"
+
+

Log single header in JSON output format as value only

+
${aspnet-response-headers:items=key1:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1"]
+
+

Log multiple headers in JSON output format as value only

+
${aspnet-response-headers:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-Response-Trailers-Layout-Renderer/index.html b/wiki/AspNet-Response-Trailers-Layout-Renderer/index.html new file mode 100644 index 000000000..bdbcf2ab4 --- /dev/null +++ b/wiki/AspNet-Response-Trailers-Layout-Renderer/index.html @@ -0,0 +1,1341 @@ + + + + + + + + AspNet Response Trailers Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Response Trailers

+
+

Platforms Supported: Limited (Only supported in Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v5.1.0

+
+

Configuration Syntax

+
${aspnet-response-trailers:items=String[]:outputFormat=Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Options

+

Rendering Options

+
    +
  • Items - Trailer names to be rendered. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the TrailerNames-option.

    +
    +
  • +
  • Exclude - Trailer names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-User-Claim-Layout-Renderer/index.html b/wiki/AspNet-User-Claim-Layout-Renderer/index.html new file mode 100644 index 000000000..dc01b607e --- /dev/null +++ b/wiki/AspNet-User-Claim-Layout-Renderer/index.html @@ -0,0 +1,1345 @@ + + + + + + + + AspNet User Claim Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET User Claims authorization values.

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v4.10.0, and with NLog.Web v5.1.0 for NET46

+
+

Configuration Syntax

+
${aspnet-user-claim:ClaimTypes.Name}
+
+

Parameters

+

ClaimType - default parameter. Key to lookup using ClaimsIdentity.FindFirst(string) with fallback to ClaimsPrincipal.FindFirst(string). When value is prefixed with ClaimTypes. (Remember dot) then it will lookup in well-known claim types from ClaimTypes-constants. For example ClaimsTypes.Name

+
+

NLog.Web.AspNetCore v5.3.3 supports outputting all values, when not having specified any ClaimType.

+
+

Formatting options

+

NLog.Web.AspNetCore v5.3.3 supports the following formatting options, when outputting all value by not specifying any ClaimType:

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
  • +
+

Remarks

+

See also ClaimTypes-constants.

+

For Azure Entra Access Tokens then one can resolve the following Entra Claim-values:

+
    +
  • ${aspnet-user-claim:oid} - Azure AccessToken ObjectId
  • +
  • ${aspnet-user-claim:tid} - Azure AccessToken TenantId
  • +
  • ${aspnet-user-claim:appid} - Azure AccessToken ApplicationId
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-User-isAuthenticated-Layout-Renderer/index.html b/wiki/AspNet-User-isAuthenticated-Layout-Renderer/index.html new file mode 100644 index 000000000..d6c3e5c79 --- /dev/null +++ b/wiki/AspNet-User-isAuthenticated-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNet User isAuthenticated Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render if user is authenticated. Renders 0 or 1.

+
+

Platforms Supported: All

+

Introduced in NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0

+
+

Configuration Syntax

+
${aspnet-user-isAuthenticated}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNet-WebRootPath-layout-renderer/index.html b/wiki/AspNet-WebRootPath-layout-renderer/index.html new file mode 100644 index 000000000..28a50b1f0 --- /dev/null +++ b/wiki/AspNet-WebRootPath-layout-renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + AspNet WebRootPath layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET WebRootPath (wwwroot)

+
+

Platforms Supported: All (Supported in Asp.NET and Asp.NetCore)

+

Introduced with NLog.Web.AspNetCore v4.5.0 and NLog.Web v4.5.2

+
+

Configuration Syntax

+
${aspnet-webrootpath}
+
+

Remarks

+

The web root (wwwroot) is the root directory from which static content is served, while the content root is also known as application base path.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetApplication-layout-renderer/index.html b/wiki/AspNetApplication-layout-renderer/index.html new file mode 100644 index 000000000..4cb32fc5f --- /dev/null +++ b/wiki/AspNetApplication-layout-renderer/index.html @@ -0,0 +1,1336 @@ + + + + + + + + AspNetApplication layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Application Dictionary Value.

+
+

Platforms Support: Limited (Not supported in ASP.NET Core - ServerVariables are non-existing in ASP.NET Core. )

+
+

Configuration Syntax

+
${aspnet-application:variable=String}
+
+

Parameters

+
    +
  • item - Key for lookup in Application-Dictionary (Required)
    +

    Introduced with NLog.Web v5.1, and replaces the Variable-option

    +
    +
  • +
  • format - Format-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • culture - Culture-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • objectpath - Property path if the value is an object, also supports nested properties (Optional).
    +

    Introduced with NLog.Web v5.2.1

    +
    +
  • +
+

Remarks

+

Use this layout renderer to output the value of the specified variable stored in the ASP.NET Application dictionary

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetBufferingWrapper-target/index.html b/wiki/AspNetBufferingWrapper-target/index.html new file mode 100644 index 000000000..ab9bbd768 --- /dev/null +++ b/wiki/AspNetBufferingWrapper-target/index.html @@ -0,0 +1,1375 @@ + + + + + + + + AspNetBufferingWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Buffers log events for the duration of ASP.NET request and sends them down to the wrapped target at the end of a request.

+
+

Platforms Supported: All

+

Introduced with NLog.Web.AspNetCore v5.2.1 and NLog.Web v4.0

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="AspNetBufferingWrapper"
+          name="String"
+          bufferGrowLimit="Integer"
+          growBufferAsNeeded="Boolean"
+          bufferSize="Integer">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Buffering Options

+
    +
  • +

    bufferSize - Initial capacity for the buffering of log events. Integer Default: 100

    +
  • +
  • +

    bufferGrowLimit - Maximum number of log events that the buffer can keep, when growing beyond the limit and overflows then it will drop the oldest logevents. Integer Default: 0 (Disable growing)

    +
  • +
  • +

    growBufferAsNeeded - Indicates whether buffer is allow to grow up to bufferGrowLimit. Boolean Default: True

    +
  • +
+

Remarks

+

Typically this target is used in cooperation with PostFilteringTargetWrapper to provide verbose logging for failing requests and normal or no logging for successful requests. We need to make the decision of the final filtering rule to apply after all logs for a page have been generated.

+
<targets>
+    <target xsi:type="AspNetBufferingWrapper" name="aspnetbuffer" bufferGrowLimit="1000">
+        <target xsi:type="PostFilteringWrapper" defaultFilter="level &gt;= LogLevel.Info">
+            <target xsi:type="File" fileName="request-failed-${shortdate}.log" />
+            <when exists="level &gt;= LogLevel.Warn" filter="level &gt;= LogLevel.Debug"/>
+        </target>
+    </target>
+</targets>
+
+

ASP.NET Core Setup

+

To use this target with NLog.Web.AspNetCore, then you need to enable the NLogBufferingTargetWrapperMiddleware in the Startup.cs file

+
using NLog.Web;
+
+   app.UseMiddleware<NLogBufferingTargetWrapperMiddleware>();
+
+

where app is an IApplicationBuilder.

+

ASP.NET Setup

+

To use this target with NLog.Web, then you need to update web.config to register NLogHttpModule:

+
<?xml version="1.0" ?>
+ <configuration>
+  <system.web>       <!-- httpModules for classic mode -->
+   <httpModules>
+    <add name="NLog" type="NLog.Web.NLogHttpModule, NLog.Web"/>
+   </httpModules>
+ </system.web>
+ <system.webServer>  <!-- modules for integrated mode -->
+    <modules>
+      <add name="NLog" type="NLog.Web.NLogHttpModule, NLog.Web" />
+    </modules>
+  </system.webServer>
+</configuration>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetEnvironment-layout-renderer/index.html b/wiki/AspNetEnvironment-layout-renderer/index.html new file mode 100644 index 000000000..c24d4c5bc --- /dev/null +++ b/wiki/AspNetEnvironment-layout-renderer/index.html @@ -0,0 +1,1307 @@ + + + + + + + + AspNetEnvironment layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+ + +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetItem-layout-renderer/index.html b/wiki/AspNetItem-layout-renderer/index.html new file mode 100644 index 000000000..e30ed0d19 --- /dev/null +++ b/wiki/AspNetItem-layout-renderer/index.html @@ -0,0 +1,1349 @@ + + + + + + + + AspNetItem layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Item variable from HttpContext.Items dictionary. Useful for storing state per request basis.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${aspnet-item:item=String:objectpath=String:format=String}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Key for lookup in Items-dictionary (Required)
    +

    Introduced with NLog.Web v5.1, and replaces the Variable-option

    +
    +
  • +
  • format - Format-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • culture - Culture-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • objectpath - Property path if the value is an object, also supports nested properties (Optional).
    +

    Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties-option

    +
    +
  • +
+

Examples

+

You can set the value of an ASP.NET Item variable by using the following code:

+

Example usage of ${aspnet-item}

+
HttpContext.Items["myvariable"] = 123;
+HttpContext.Items["stringvariable"] = "aaa BBB";
+HttpContext.Items["anothervariable"] = DateTime.Now;
+
+${aspnet-item:variable=myvariable} - produces "123"
+${aspnet-item:variable=anothervariable} - produces "01/01/2006 00:00:00"
+${aspnet-item:variable=anothervariable:culture=pl-PL} - produces "2006-01-01 00:00:00"
+${aspnet-item:variable=myvariable:padding=5} - produces "  123"
+${aspnet-item:variable=myvariable:padding=-5} - produces "123  "
+${aspnet-item:variable=stringvariable:upperCase=true} - produces "AAA BBB"
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-Cookie-Layout-Renderer/index.html b/wiki/AspNetRequest-Cookie-Layout-Renderer/index.html new file mode 100644 index 000000000..7e8e17392 --- /dev/null +++ b/wiki/AspNetRequest-Cookie-Layout-Renderer/index.html @@ -0,0 +1,1413 @@ + + + + + + + + AspNetRequest Cookie Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request Cookie key/value pairs.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-request-cookie:items=String[]:outputFormat=Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • items - Cookie key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all).
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the cookieNames-option.

    +
    +
  • +
+
+

With NLog.Web / NLog.Web.AspNetCore v4.9 then all key/value pairs will be rendered, when not specified. +* exclude - Cookie key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 +Introduced with NLog.Web / NLog.Web.AspNetCore v4.9

+
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json)
  • +
  • +

    JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray)

    +
  • +
  • +

    itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.

    +
    +

    Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5

    +
    +
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
    +

    Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5

    +
    +
  • +
  • ValuesOnly Only render the values of the key/value pairs. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore v4.6

    +
    +
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1

    +
    +
  • +
+

Remarks

+

Use this layout renderer to log the value of the specified cookie(s) stored in the ASP.NET Request Cookies collection.

+

Examples

+

In C# code:

+
Request.Cookies["key1"] = "value1";
+Request.Cookies["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+ +
${aspnet-request-cookie:items=key1}
+
+

Will print:

+
"key1=value1"
+
+

Log multiple cookies in default Flat output format

+
${aspnet-request-cookie:items=key1,id}
+
+

Will print:

+
"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+ +
${aspnet-request-cookie:items=key1:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1"}]
+
+

Log multiple cookies in JSON output format

+
${aspnet-request-cookie:items=key1,id:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+ +
${aspnet-request-cookie:items=key1:OutputFormat=JsonDictionary}
+
+

Will print:

+
{"key1":"value1"}
+
+ +
${aspnet-request-cookie:items=key1:ValuesOnly=true}
+
+

Will print:

+
"value1"
+
+ +
${aspnet-request-cookie:items=key1:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1"]
+
+

Log multiple cookies in JSON output format as value only

+
${aspnet-request-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-Form-Layout-Renderer/index.html b/wiki/AspNetRequest-Form-Layout-Renderer/index.html new file mode 100644 index 000000000..d619b7841 --- /dev/null +++ b/wiki/AspNetRequest-Form-Layout-Renderer/index.html @@ -0,0 +1,1381 @@ + + + + + + + + AspNetRequest Form Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request Form key/value pairs.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.7

+
+

Configuration Syntax

+
${aspnet-request-form:items=String[]:exclude=String[]:outputFormat=Enum
+    :itemSeparator=Layout:valueSeparator=Layout
+    :valuesOnly=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • items - Form key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.2, and replaces the include-option.

    +
    +
  • +
  • exclude - Form key name(s) to exclude from the output. A list of keys can be passed as comma separated values, e.g.: Key1,Key2.
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json)
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray)
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
  • +
  • valuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1

    +
    +
  • +
+

Remarks

+

Use this layout renderer to log the ASP.NET Request Form collection.

+

Examples

+

In C# code:

+
httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues>{
+    { "id","1" },
+    { "name","Test Person" },
+    { "token","86abe8fe-2237-4f87-81af-0a4e522b4140" }
+}); 
+
+

Log all Form data from the Request in default Flat output format

+
${aspnet-request-form}
+
+

Will print:

+
"id=1,name=Test Person,token=86abe8fe-2237-4f87-81af-0a4e522b4140"
+
+

Log all Form data from the Request in JSON output format

+
${aspnet-request-form:OutputFormat=JSON}
+
+

Will print:

+
[{"id":"1"},{"name":"Test Person"},{"token":"86abe8fe-2237-4f87-81af-0a4e522b4140"}]
+
+

Log only the specified Form keys from the Request in default Flat output format

+
${aspnet-request-form:items=id,name}
+
+

Will print:

+
"id=1,name=Test Person"
+
+

Log all Form data from the Request except for the specified keys in default Flat output format

+
${aspnet-request-form:Exclude=token}
+
+

Will print:

+
"id=1,name=Test Person"
+
+

Log all Form data from the Request in Flat output format with each item separated by a new line

+
${aspnet-request-form:ItemSeparator=${newline}}
+
+

Will print:

+
"id=1\r\nname=Test Person\r\ntoken=86abe8fe-2237-4f87-81af-0a4e522b4140"
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-Headers-Layout-Renderer/index.html b/wiki/AspNetRequest-Headers-Layout-Renderer/index.html new file mode 100644 index 000000000..fce810b10 --- /dev/null +++ b/wiki/AspNetRequest-Headers-Layout-Renderer/index.html @@ -0,0 +1,1396 @@ + + + + + + + + AspNetRequest Headers Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request Headers key/value pairs.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.9 and NLog.Web.AspNetCore 4.9

+
+

Configuration Syntax

+
${aspnet-request-headers:headerNames=String[]:outputFormat=Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • items - Header key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the headerNames-option.

    +
    +
  • +
  • exclude - Header key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json)
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray)
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1

    +
    +
  • +
+

Remarks

+

Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Request Headers collection.

+

Examples

+

In C# code:

+
Request.Headers["key1"] = "value1";
+Request.Headers["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+

Log single header in default Flat output format

+
${aspnet-request-headers:HeaderNames=key1}
+
+

Will print:

+
"key1=value1"
+
+

Log multiple headers in default Flat output format

+
${aspnet-request-headers:HeaderNames=key1,id}
+
+

Will print:

+
"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+

Log single header ie in JSON output format

+
${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1"}]
+
+

Log multiple headers in JSON output format

+
${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+

Log single header as JSON dictionary:

+
${aspnet-request-headers:HeaderNames=key1:OutputFormat=JsonDictionary}
+
+

Will print:

+
{"key1":"value1"}
+
+

Log single header in Flat output format as value only

+
${aspnet-request-headers:HeaderNames=key1:ValuesOnly=true}
+
+

Will print:

+
"value1"
+
+

Log single header in JSON output format as value only

+
${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1"]
+
+

Log multiple headers in JSON output format as value only

+
${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-Host-Layout-Renderer/index.html b/wiki/AspNetRequest-Host-Layout-Renderer/index.html new file mode 100644 index 000000000..30e1a231f --- /dev/null +++ b/wiki/AspNetRequest-Host-Layout-Renderer/index.html @@ -0,0 +1,1322 @@ + + + + + + + + AspNetRequest Host Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request DNS name of the remote client

+
+

Platforms Supported: All (ASP.NET Core + ASP.NET)

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-request-host}
+
+

Remarks

+
    +
  • ASP.NET Core returns the Host-Header
  • +
  • ASP.NET returns the REMOTE_ADDR-ServerVariable
  • +
+

See also AspNet Request IP Layout Renderer

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-Method-Layout-Renderer/index.html b/wiki/AspNetRequest-Method-Layout-Renderer/index.html new file mode 100644 index 000000000..312f4dbd7 --- /dev/null +++ b/wiki/AspNetRequest-Method-Layout-Renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + AspNetRequest Method Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET HTTP Method. GET/POST/PUT etc.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-request-method}
+
+

Remarks

+

Use this layout renderer to insert the HTTP Request Method.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-QueryString-Layout-Renderer/index.html b/wiki/AspNetRequest-QueryString-Layout-Renderer/index.html new file mode 100644 index 000000000..c51a248c6 --- /dev/null +++ b/wiki/AspNetRequest-QueryString-Layout-Renderer/index.html @@ -0,0 +1,1412 @@ + + + + + + + + AspNetRequest QueryString Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request Query String key/value pairs.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-request-querystring:items=String:outputFormat:Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • items - Query String key(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the queryStringKeys-option.

    +
    +
  • +
+
+

With NLog.Web / NLog.Web.AspNetCore v4.3.1 then all key/value pairs will be rendered, when not specified.

+
+
    +
  • exclude - Query String key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2
    +

    Introduced with NLog.Web v5.2.2

    +
    +
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json)
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray)
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
    +

    Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5

    +
    +
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
    +

    Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5

    +
    +
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore v4.6

    +
    +
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1

    +
    +
  • +
+

Remarks

+

Use this layout renderer to insert the value of the specified query string parameters stored in the ASP.NET Query String collection.

+

Examples

+

In C# code:

+
Response.Redirect("myPage.aspx?key1=value1&id=d4b20a34-6231-4201-83a6-c72599e41164");
+
+

Log single query string key/value pair in default Flat output format

+
${aspnet-request-querystring:items=key1}
+
+

Will print:

+
"key1=value1"
+
+

Log multiple query string key/value pairs in default Flat output format

+
${aspnet-request-querystring:items=key1,id}
+
+

Will print:

+
"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+

Log single query string key/value pair in JSON output format

+
${aspnet-request-querystring:items=key1:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1"}]
+
+

Log multiple query string key/value pairs in JSON output format

+
${aspnet-request-querystring:items=key1,id:OutputFormat=JSON}
+
+

Will print:

+
[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+

Log single query string key/value pair as JSON dictionary:

+
${aspnet-request-querystring:items=key1:OutputFormat=JsonDictionary}
+
+

Will print:

+
{"key1":"value1"}
+
+

Log single query string key/value pair in Flat output format as value only

+
${aspnet-request-querystring:items=key1:ValuesOnly=true}
+
+

Will print:

+
"value1"
+
+

Log single query string key/value pair in JSON output format as value only

+
${aspnet-request-querystring:items=key1:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1"]
+
+

Log multiple query string key/value pairs in JSON output format as value only

+
${aspnet-request-querystring:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+

Will print:

+
["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-Referrer-Renderer/index.html b/wiki/AspNetRequest-Referrer-Renderer/index.html new file mode 100644 index 000000000..23d7e032f --- /dev/null +++ b/wiki/AspNetRequest-Referrer-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNetRequest Referrer Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request HTTP URL Referrer.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-request-referrer}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-RequestAborted-Layout-Renderer/index.html b/wiki/AspNetRequest-RequestAborted-Layout-Renderer/index.html new file mode 100644 index 000000000..ddf471b86 --- /dev/null +++ b/wiki/AspNetRequest-RequestAborted-Layout-Renderer/index.html @@ -0,0 +1,1314 @@ + + + + + + + + AspNetRequest RequestAborted Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +
<logger name="*" minlevel="Error" writeTo="appFile">
+  <filters defaultAction="Log">
+    <when condition="equals('${aspnet-request-aborted}', '1')" action="Ignore" />
+  </filters>
+</logger>
+
+

Notice request-aborted can be a symptom of slow performance, which can be relevant to investigate if app-performance is important (and not to be swept under the carpet)

+

Introduced in NLog.Web and NLog.Web.AspNetCore 6.3.0

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-RouteParameters-Layout-Renderer/index.html b/wiki/AspNetRequest-RouteParameters-Layout-Renderer/index.html new file mode 100644 index 000000000..0f8f0d31a --- /dev/null +++ b/wiki/AspNetRequest-RouteParameters-Layout-Renderer/index.html @@ -0,0 +1,1391 @@ + + + + + + + + AspNetRequest RouteParameters Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request RouteParameters key/value pairs.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 5.0 and NLog.Web.AspNetCore 5.0

+
+

Configuration Syntax

+
${aspnet-request-routeparameters:items=String:outputFormat=Enum
+    :itemSeparator=String:valueSeparator=String
+    :valuesOnly=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • items - RouteParameter key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all)
    +

    Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the RouteParameterKeys-option.

    +
    +
  • +
+

Formatting options

+
    +
  • outputFormat - Renders as flat string or as JSON. Default: Flat.
  • +
  • Flat - Key-value-pair as standard string
  • +
  • JsonArray - Key-value-pair in JSON-array
  • +
  • JsonDictionary - Key-value-pair as JSON-dictionary
  • +
  • itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
  • +
  • valueSeparator - Separator between value and key. Default: =. Only applies when OutputFormat is Flat.
  • +
  • ValuesOnly - Only render the values of the key/value pairs. Default: false.
  • +
  • LowerCaseKeys - Convert Keys to lowercase. Default: false.
    +

    Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1

    +
    +
  • +
+

Remarks

+

Use this layout renderer to log the value of the specified route-parameter(s) stored in the ASP.NET GetRouteData() Values collection.

+

Examples

+

Log single route-parameter in default Flat output format

+
${aspnet-request-routeparameters:Items=key1}
+
+

Will print:

+
"key1=value1"
+
+

Log multiple route-parameters in default Flat output format

+
${aspnet-request-routeparameters:items=key1,id}
+
+

Will print:

+
"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+

Log single route-parameter in JSON output format

+
${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray}
+
+

Will print:

+
[{"key1":"value1"}]
+
+

Log multiple route-parameters in JSON output format

+
${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray}
+
+

Will print:

+
[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+

Log single route-parameter as JSON dictionary:

+
${aspnet-request-routeparameters:items=key1:OutputFormat=JsonDictionary}
+
+

Will print:

+
{"key1":"value1"}
+
+

Log single route-parameter in Flat output format as value only

+
${aspnet-request-routeparameters:items=key1:ValuesOnly=true}
+
+

Will print:

+
"value1"
+
+

Log single route-parameter in JSON output format as value only

+
${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray:ValuesOnly=true}
+
+

Will print:

+
["value1"]
+
+

Log multiple route-parameters in JSON output format as value only

+
${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray:ValuesOnly=true}
+
+

Will print:

+
["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-Url-Layout-Renderer/index.html b/wiki/AspNetRequest-Url-Layout-Renderer/index.html new file mode 100644 index 000000000..05a0595c2 --- /dev/null +++ b/wiki/AspNetRequest-Url-Layout-Renderer/index.html @@ -0,0 +1,1354 @@ + + + + + + + + AspNetRequest Url Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request URL

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-request-url:IncludeHost=boolean:IncludePort=boolean:IncludeQueryString=boolean:IncludeScheme=boolean}
+
+

Parameters

+
    +
  • Properties - Controls what parts of the Url to output. Default =Scheme, Host, Path
    +

    Introduced with NLog v5.1.1

    +
    +
  • +
  • Property Enum Values:
      +
    • Scheme
    • +
    • Host
    • +
    • Port
    • +
    • Path
    • +
    • Query
    • +
    +
  • +
  • IncludeHost - Include the host name? (Assigns Properties |= Host). Default is true.
  • +
  • IncludePort - Include the port number? (Assigns Properties |= Port). Default is false.
  • +
  • IncludeQueryString - include the querystring. (Assigns Properties |= Query). Default is false.
  • +
  • IncludeScheme - Includes the sheme? (Ex. http:// or https://) (Assigns Properties |= Scheme). Default is true.
    +

    Introduced in NLog.Web.AspNetCore v4.4.1 and NLog.Web v4.5.1.

    +
    +
  • +
  • IncludePath - Include the path? (Assigns Properties |= Path). Default is true.
    +

    Introduced in NLog.Web.AspNetCore v5.0 and NLog.Web v5.0.

    +
    +
  • +
  • UseRawTarget - Extract the path from IHttpRequestFeature.RawTarget? Default is false.
    +

    Introduced in NLog.Web.AspNetCore v4.9.2 (Not supported for NLog.Web)

    +
    +
  • +
+

Examples

+
${aspnet-request-url:IncludeQueryString=true} - produces http://www.exmaple.com/?t=1
+${aspnet-request-url:IncludeQueryString=false} - produces http://www.exmaple.com/
+${aspnet-request-url:IncludePort=true} - produces http://www.exmaple.com:80/
+${aspnet-request-url:IncludePort=false} - produces http://www.exmaple.com/
+${aspnet-request-url:IncludePort=true:IncludeQueryString=true} - produces http://www.exmaple.com:80/?t=1
+${aspnet-request-url:IncludeScheme=false} - produces www.exmaple.com 
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-UserAgent-Layout-Renderer/index.html b/wiki/AspNetRequest-UserAgent-Layout-Renderer/index.html new file mode 100644 index 000000000..3f57646c8 --- /dev/null +++ b/wiki/AspNetRequest-UserAgent-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + AspNetRequest UserAgent Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Renders the ASP.NET UserAgent from HTTP Request.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.3

+
+

Configuration Syntax

+
${aspnet-request-useragent}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetRequest-layout-renderer/index.html b/wiki/AspNetRequest-layout-renderer/index.html new file mode 100644 index 000000000..937234fc7 --- /dev/null +++ b/wiki/AspNetRequest-layout-renderer/index.html @@ -0,0 +1,1364 @@ + + + + + + + + AspNetRequest layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Request variable.

+
+

Platforms Supported: All

+
+

ASP.NET Core

+

This layout renderer is broken down to separate layout renders who are more ASP.NET Core compatible / future proof:

+ +

And there are many more NLog LayoutRenderers to choose from

+

Configuration Syntax

+
${aspnet-request:cookie=String:serverVariable=String:queryString=String
+                :item=String:form=String:header=String}
+
+

Parameters

+

Rendering Options

+
    +
  • cookie - Cookie to be rendered.
  • +
  • header - Request header to be rendered. Introduced in NLog.Web 4.2
  • +
  • serverVariable - ServerVariables item to be rendered. See for possible options: msdn.
    +

    Not supported on ASP.NET Core until NLog.Web.AspNetCore v5.1

    +
    +
  • +
  • queryString - QueryString variable to be rendered.
  • +
  • item - HttpConterxt Item name to be rendered.
  • +
  • form - Form variable to be rendered. Note: The Form property is populated when the HTTP request Content-Type value is either "application/x-www-form-urlencoded" or "multipart/form-data". (see msdn)
  • +
+

Remarks

+

Use this layout renderer to insert the value of the specified parameter of the ASP.NET Request object. This renderer requires the NLog.Web package.

+

Examples

+

Full URL

+

Full URL without domain, eg default.aspx?id=512

+

${aspnet-request:serverVariable=HTTP_URL}${aspnet-request:queryString}

+

Referer

+

URL doing the request. Including schema (e.g https://) and querystring

+

${aspnet-request:header=Referer}

+

Content-Type

+

Content-Type like application/json; charset=UTF-8

+

${aspnet-request:header=Content-Type}

+

Method

+

Method like PUT, POST, GET etc

+

${aspnet-request:serverVariable=REQUEST_METHOD}

+

User agent

+

user agent, like Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

+

${aspnet-request:serverVariable=HTTP_USER_AGENT}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetResponse-StatusCode-Layout-Renderer/index.html b/wiki/AspNetResponse-StatusCode-Layout-Renderer/index.html new file mode 100644 index 000000000..7d85ef07a --- /dev/null +++ b/wiki/AspNetResponse-StatusCode-Layout-Renderer/index.html @@ -0,0 +1,1323 @@ + + + + + + + + AspNetResponse StatusCode Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Response Status Code.

+
+

Platforms Supported: All

+

Introduced in NLog.Web 4.9

+
+

Configuration Syntax

+
${aspnet-response-statuscode:format=d}
+
+

Parameters

+
    +
  • Format - Enumeration Format string specifier. Ex. G for string-value and D for integer-value. Default: D
    +

    Introduced with NLog.Web 5.2.2

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetSession-Layout-Renderer/index.html b/wiki/AspNetSession-Layout-Renderer/index.html new file mode 100644 index 000000000..c159f5bba --- /dev/null +++ b/wiki/AspNetSession-Layout-Renderer/index.html @@ -0,0 +1,1379 @@ + + + + + + + + AspNetSession Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Item Variable from Session Dictionary

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${aspnet-session:item=String:objectpath=String:format=String:ValueType=String|Int32}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Key for lookup in Session-dictionary (Required)
    +

    Introduced with NLog.Web v5.1, and replaces the Variable-option

    +
    +
  • +
  • format - Format-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • culture - Culture-specifier for converting the value as string (Optional)
    +

    Introduced with NLog.Web v5.0

    +
    +
  • +
  • objectpath - Property path if the value is an object, also supports nested properties (Optional).
    +

    Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties-option

    +
    +
  • +
  • ValueType - Only for ASP.NET Core. Type of the value. String (default) or Int32.
    +

    Introduced in NLog.Web.AspNetCore 4.9.3. Please note: you won't get an error when retrieving a int (set with Session.SetInt32(..)) with valuetype string, but an incorrect value. We can't unfortunately recognize the type of the value inside the ASP.NET Core session.

    +
    +
  • +
+

See also Configure session state

+

Examples

+

Log the username in the session.

+

In the C# code:

+
Session["username"] = "JohnDoe";
+
+

Config:

+
<?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="logfile" xsi:type="File" fileName="file.txt" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Info" writeTo="logfile" layout="${aspnet-session:item=username}" />
+    </rules>
+</nlog>
+
+

Will print "JohnDoe"

+

ObjectPath

+

In the C# code:

+
Session["user"] = new UserInfo { Name= "JohnDoe", Id = 100};
+
+

Config:

+
<?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="logfile" xsi:type="File" fileName="file.txt" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Info" writeTo="logfile" layout="${aspnet-session:item=user:ObjectPath=Name}" />
+    </rules>
+</nlog>
+
+

Will print nested property-value "JohnDoe"

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetSessionId-Layout-Renderer/index.html b/wiki/AspNetSessionId-Layout-Renderer/index.html new file mode 100644 index 000000000..f38d686a1 --- /dev/null +++ b/wiki/AspNetSessionId-Layout-Renderer/index.html @@ -0,0 +1,1338 @@ + + + + + + + + AspNetSessionId Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Session ID.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${aspnet-sessionid}
+
+

Enable sessions in ASP.NET Core

+

Add line to ConfigureServices() in Startup.cs

+
public void ConfigureServices(IServiceCollection services)
+{
+     ...
+    services.AddMvc();
+    services.AddSession(); // After AddMvc()
+    services.AddHttpContextAccessor();
+     ...
+}
+
+

Add line to Configure() in Startup.cs

+
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
+{
+     ...
+    app.UseSession();  // Before UseMvc()
+    app.UseMvc();
+     ...
+}
+
+

See also Configure session state

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetTrace-target/index.html b/wiki/AspNetTrace-target/index.html new file mode 100644 index 000000000..976c5f5f9 --- /dev/null +++ b/wiki/AspNetTrace-target/index.html @@ -0,0 +1,1372 @@ + + + + + + + + AspNetTrace target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to the ASP.NET Trace using TraceContext from HttpContext.

+
+

Platforms Supported: Limited - .NET Framework only and requires nuget-package NLog.Web

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="AspNetTrace" name="String" layout="Layout" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target
  • +
+

Layout Options

+
    +
  • layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
  • +
+

Remarks

+

Log entries can then be viewed by navigating to http://server/path/Trace.axd.

+

AspNetTrace uses the HttpContext.Current. Therefore async/buffered writing does not works for AspNetTrace due to different thread.

+

Examples

+

In order to use this target, put the following code in the configuration file such as Web.nlog or NLog.config:

+
<?xml version="1.0" ?>
+<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="aspnet" xsi:type="ASPNetTrace" layout="${logger} ${message}" />
+    </targets>
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="aspnet" />
+    </rules>
+</nlog>
+
+

You can also configure the target programmatically, by putting the code in Application_Start event handler or similar:

+
using System;
+using System.Web;
+
+using NLog;
+using NLog.Web.Targets;
+
+namespace SomeWebApplication
+{
+    public class Global : System.Web.HttpApplication
+    {
+        //
+        // this event handler is executed at the very start of the web application
+        // so this is a good place to configure targets programmatically
+        // 
+        // alternative you could place this code in a static type constructor
+        //
+        protected void Application_Start(Object sender, EventArgs e)
+        {
+            NLog.Web.Targets.AspNetTraceTarget target = new NLog.Web.Targets.AspNetTraceTarget() { Name = "AspNetTrace" };
+            target.Layout = "${logger} ${message}";
+
+            NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
+            config.AddRuleForAllLevels(target)
+            NLog.LogManager.Configuration = config;
+        }
+    }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetTraceIdentifier-Layout-Renderer/index.html b/wiki/AspNetTraceIdentifier-Layout-Renderer/index.html new file mode 100644 index 000000000..13cfba992 --- /dev/null +++ b/wiki/AspNetTraceIdentifier-Layout-Renderer/index.html @@ -0,0 +1,1330 @@ + + + + + + + + AspNetTraceIdentifier Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET Trace Identifier

+
+

Platforms Supported: All (Supported in ASP.NET Core and ASP.NET)

+

Introduced in NLog.Web.AspNetCore ver. 4.3.1 and NLog.Web ver. 4.7.1

+
+

Configuration Syntax

+
${aspnet-TraceIdentifier:ignoreActivityId=boolean}
+
+

Options:

+
    +
  • ignoreActivityId: Only ASP.NET Core. Use HttpContext.TraceIdentifier instead of System.Diagnostics.Activity.Current.Id
  • +
+

Notes

+

Which TraceIdentifier is used?

+
    +
  • ASP.NET Core 3: by default System.Diagnostics.Activity.Current.Id.
  • +
  • ASP.NET Core 1+2: HttpContext.TraceIdentifier
  • +
  • ASP.NET: HttpWorkerRequest.RequestTraceIdentifier.
  • +
  • Requires IIS ETW feature enabled, see Microsoft docs
  • +
  • Alternative could use ${activityid} together with CorrelationManager.ActivityId.
  • +
+

See code

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetUserAuthType-Layout-Renderer/index.html b/wiki/AspNetUserAuthType-Layout-Renderer/index.html new file mode 100644 index 000000000..b8ee64fe1 --- /dev/null +++ b/wiki/AspNetUserAuthType-Layout-Renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + AspNetUserAuthType Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET HttpContext User.Identity.AuthenticationType

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${aspnet-user-authtype}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspNetUserIdentity-Layout-Renderer/index.html b/wiki/AspNetUserIdentity-Layout-Renderer/index.html new file mode 100644 index 000000000..67cb61b58 --- /dev/null +++ b/wiki/AspNetUserIdentity-Layout-Renderer/index.html @@ -0,0 +1,1330 @@ + + + + + + + + AspNetUserIdentity Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP.NET HttpContext User.Identity.Name

+
+

Platforms Supported: All

+
+

Similar to AUTH_USER / REMOTE_USER / LOGON_USER in Server Variables.

+

Configuration Syntax

+
${aspnet-user-identity}
+
+

ASP.NET Core Details

+

Adding Identity in ASP.NET Core 2.2 using IServiceCollection in ConfigureServices:

+
services.AddIdentity<IdentityUser, IdentityRole>()
+    .AddRoles<IdentityRole>()
+    .AddDefaultTokenProviders()
+    .AddDefaultUI();
+
+

See also Introduction to Identity on ASP.NET Core (Configuring IdentityOptions)

+

User Identity Claims

+

For additional details about the user identity, then one can also use ${aspnet-user-claim}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspRequest-layout-renderer/index.html b/wiki/AspRequest-layout-renderer/index.html new file mode 100644 index 000000000..5b5ae088b --- /dev/null +++ b/wiki/AspRequest-layout-renderer/index.html @@ -0,0 +1,1307 @@ + + + + + + + + AspRequest layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+ +
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspResponse-target/index.html b/wiki/AspResponse-target/index.html new file mode 100644 index 000000000..54527f0ec --- /dev/null +++ b/wiki/AspResponse-target/index.html @@ -0,0 +1,1339 @@ + + + + + + + + AspResponse target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Outputs log messages through the ASP Response object.

+

Supported in .NET and Mono

+

Configuration Syntax

+
<targets>
+  <target xsi:type="AspResponse" name="String" addComments="Boolean" layout="Layout" />
+</targets>
+
+

Read more about using the configuration file.

+

Parameters

+

General Options

+
    +
  • name - Name of the target
  • +
+

Layout Options

+
    +
  • addComments - Indicates whether to add <!-- --> comments around all written texts. Boolean
  • +
  • layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
  • +
+

Examples

+

This target is usable when using classic ASP (not ASP.NET). In order to use this target, put the following code in the configuration file which is loaded into the web server process:

+
<?xml version="1.0" ?>
+<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="aspnet" xsi:type="ASPResponse" layout="${logger} ${message}" />
+    </targets>
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="aspnet" />
+    </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AspSession-layout-renderer/index.html b/wiki/AspSession-layout-renderer/index.html new file mode 100644 index 000000000..21bda5611 --- /dev/null +++ b/wiki/AspSession-layout-renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + AspSession layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ASP Session variable.

+

Supported in .NET and Mono

+

Configuration Syntax

+
${asp-session:variable=String}
+
+

Parameters

+

Rendering Options

+
    +
  • variable - Session variable name. Required.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AssemblyVersion-Layout-Renderer/index.html b/wiki/AssemblyVersion-Layout-Renderer/index.html new file mode 100644 index 000000000..8fdf75305 --- /dev/null +++ b/wiki/AssemblyVersion-Layout-Renderer/index.html @@ -0,0 +1,1376 @@ + + + + + + + + AssemblyVersion Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Renders assembly version information from the entry assembly or a named assembly.

+
+

Platforms Supported: All

+

Introduced for ASP.NET / ASP.NET Core in NLog.Web 4.5.0 / NLog.Web.AspNetCore 4.4.0.

+
+

Configuration Syntax

+
${assembly-version:name=string:type=Enum:format=string}
+
+

Parameters

+
    +
  • +

    Name - Display name of the assembly to retrieve a version from, as determined by its FullName property. The assembly will be loaded if needed. If not specified, will use the entry assembly (this did not function correctly for .NET Core until NLog.Web.AspNetCore 4.6). Introduced in NLog 4.3.7.

    +
  • +
  • +

    Type - Type of the assembly version value to retrieve. Default: Assembly.

    +
    +

    Introduced with NLog v4.5.

    +
    +
  • +
+
+

Introduced for ASP.NET with NLog.Web / NLog.Web.AspNetCore v4.6.

+
+

Possible enum values: + * Assembly - Assembly version. Value for AssemblyVersion attribute.

+
Note: UWP earlier than .NET Standard 1.5 uses value for `ApplicationVersion`
+
+
    +
  • +

    File - File version. Value for AssemblyFileVersion attribute.

    +

    Notes: +- UWP earlier than .NET Standard 1.5 uses Assembly instead unless a value is given for the name parameter

    +
  • +
  • +

    Informational - Product Version extracted from AssemblyInformationalVersion attribute.

    +

    Notes: +- UWP earlier than .NET Standard 1.5 uses Assembly instead unless a value is given for the name parameter

    +
  • +
  • +

    Format - Custom format of the assembly version output. Default: major.minor.build.revision + Supported placeholders are 'major', 'minor', 'build' and 'revision'. The default .NET template for version numbers is 'major.minor.build.revision'. + See https://docs.microsoft.com/en-gb/dotnet/api/system.version?view=netframework-4.7.2#remarks for details.

    +
    +

    Introduced with NLog 4.6

    +
    +
  • +
  • +

    Default - Custom value to output when assembly version cannot be found, is empty or matches 0.0.0.0

    +
    +

    Introduced with NLog 5.0.2

    +
    +
  • +
+

Remarks

+

As this layout renderer uses reflection and version information is unlikely to change during application execution, it is recommended to use it in conjunction with the CachedLayoutRendererWrapper. The entry assembly can't be found in some cases e.g. ASP.NET, unit tests, etc.

+

Examples

+

Retrieve assembly version for entry assembly:

+
${assembly-version}
+
+

Retrieve assembly version for assembly name NLogAutloadExtension:

+
${assembly-version:NLogAutloadExtension}
+
+

Retrieve file version for entry assembly:

+
${assembly-version:type=File}
+
+

Retrieve informational version for assembly name NLogAutloadExtension:

+
${assembly-version:name=NLogAutloadExtension:type=Informational}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AsyncWrapper-target/index.html b/wiki/AsyncWrapper-target/index.html new file mode 100644 index 000000000..89a932fc4 --- /dev/null +++ b/wiki/AsyncWrapper-target/index.html @@ -0,0 +1,1400 @@ + + + + + + + + AsyncWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Enables asynchronous logging, so the application-thread will have minimal logging overhead, and only needs to capture thread-context if needed (Ex. ${threadid}). Activates batch-writing of log events for even better performance.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="AsyncWrapper"
+          name="String"
+          queueLimit="Integer"
+          timeToSleepBetweenBatches="Integer"
+          batchSize="Integer"
+          overflowAction="Enum">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Buffering Options

+
    +
  • +

    queueLimit - Limit on the number of requests the background-writer thread can have in the queue. Integer Default: 10000

    +
  • +
  • +

    timeToSleepBetweenBatches - Time in milliseconds to sleep between batches. Integer Default: 1 (NLog 4.6 changed default from 50 to 1). When set to '0' or '1', then it will only trigger timer when something is logged (Less timer activity when idle, Faster logging and improved garbage collection behavior).

    +
  • +
  • +

    batchSize - Number of log events that should be processed in a batch by the background-writer thread. Integer Default: 100 (NLog 4.4.2 and newer has Default: 200)

    +
  • +
  • +

    fullBatchSizeWriteLimit - Max number of consecutive full batchSize writes to perform within the same timer event. Integer Default: 5. Introduced in NLog 4.4.2

    +
  • +
  • +

    overflowAction - Action to be taken when in-memory-queue becomes full (Reached queueLimit). This means the background-writer is falling behind, and cannot keep up with the application-threads logging. Default: Discard
    +Possible values:

    +
  • +
  • Discard - The application-thread will discard logevent to avoid becoming blocked or causing out-of-memory issues. If memory and large-object-heap usage is not an issue, then one can consider increasing queueLimit to 100.000. (Default)
  • +
  • Block - The application-thread will block until the background-writer-thread has taken the next batch. Avoids loosing important logevents, but can block all application-threads. Consider to throttle active thread count, by limiting number of concurrent inbound requests.
  • +
  • +

    Grow - The application-thread will ignore the queueLimit, and will just allocate more memory. Can cause the entire application to experience out-of-memory-issues.

    +
  • +
  • +

    ForceLockingQueue - Force thread synchronization with monitor-lock, instead of using .NET ConcurrentQueue. Legacy NetFramework application will by default use monitor-lock (Default=true). .NET Standard 2.0 will by default use of the .NET lock-free ConcurrentQueue for improved concurrency (Default=false).

    +
    +

    Introduced in NLog 4.6

    +
    +
  • +
+

Remarks

+

Remember to Flush

+

Remember to Flush before application exit, is very important when enabling use of the Asynchronous target wrapper.

+

Async attribute

+

Asynchronous target wrapper allows the logger code to execute more quickly, by queuing messages for processing by background writer-thread. You should wrap targets that spend a non-trivial amount of time in their Write() method with asynchronous target to speed up logging. Because asynchronous logging is quite a common scenario, NLog supports a shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to the <targets/> element in the configuration file.

+

Example:

+
<targets async="true"> 
+  ... your targets go here ...
+</targets>
+
+

Async attribute will discard by default

+

The async attribute is a shorthand for:

+
xsi:type="AsyncWrapper overflowAction="Discard" queueLimit="10000" batchSize="200" timeToSleepBetweenBatches="1"
+
+

So if you write a lot of messages (more then 10000) in a short time, it's possible that messages will be lost. This is intended behavior as keeping all the messages or waiting for all the messages to be written, could have impact on the performance of your program.

+

If you need all the log messages, then you can change from <targets async="true"> to using <default-wrapper>:

+
<targets>
+    <default-wrapper xsi:type="AsyncWrapper" overflowAction="Block" />
+
+    ... your targets go here ...
+</targets>
+
+

AsyncWrapper and <rules>

+

When using the AsyncWrapper, do write to the wrapper in your <rules> section! In the following example: do write to +"target2". If the <logger> is writing to "target1", the messages are not written asynchronously!

+
   <targets>
+      <target name="target2" xsi:type="AsyncWrapper">
+        <target name ="target1" xsi:type="File"
+                    fileName="c:/temp/test.log" layout="${message}"
+                    keepFileOpen="true" />
+      </target>
+    <rules>
+      <logger name="*" minlevel="Info" writeTo="target2"/>
+    </rules>
+  </targets> 
+
+

Asynchronously writing and custom targets

+

When messages are written asynchronously, then writing is performed by the background-writer-thread. There can be custom NLog targets that requires writing to happen on the application-thread for proper context capture. When used together with AsyncWrapper then asynchronous writing is used and context information can be lost.

+

By default all standard NLog targets supports use of AsyncWrapper. Custom NLog targets that inherits from TargetWithContext should also by default work correctly with AsyncWrapper.

+

BufferingWrapper and Async

+

The BufferingWrapper can also be asynchronously when having configured FlushTimeout. AsyncWrapper is intended for improving performance, where BufferingWrapper is intended for throttling or even discarding LogEvents. AsyncWrapper has an internal buffer optimized to handle many concurrent threads.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Atomic-File-Target/index.html b/wiki/Atomic-File-Target/index.html new file mode 100644 index 000000000..8fcd32885 --- /dev/null +++ b/wiki/Atomic-File-Target/index.html @@ -0,0 +1,1336 @@ + + + + + + + + Atomic File Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes LogEvents to file using operating system API for atomic file appending (O_APPEND), so multiple processes can write concurrently to the same file, by extending the standard NLog File Target.

+
+

Platforms Supported: NET8 or .NET Framework - Requires nuget-package NLog.Targets.AtomicFile

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="AtomFile"
+          name="string"
+          fileName="Layout"
+          layout="Layout"
+          concurrentWrites="boolean"
+          keepFileOpen="boolean"
+  />
+</targets>
+
+

Parameters

+
    +
  • fileName - Name of the file to write to. Layout Required.
  • +
  • layout - Text to be rendered. Layout Required.
    +

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

    +
    +
  • +
  • concurrentWrites - Whether to enable atomic file appends. Default: true
  • +
  • keepFileOpen - Disables atomic file appends when configured to false. Default: true
  • +
+

Also inherits all parameters from the standard File-Target.

+

Linux Support

+

Uses libc open() with O_APPEND flag, which is supported on Linux and other Unix-like operating systems.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/AutoFlushWrapper-target/index.html b/wiki/AutoFlushWrapper-target/index.html new file mode 100644 index 000000000..c2bc7f8e0 --- /dev/null +++ b/wiki/AutoFlushWrapper-target/index.html @@ -0,0 +1,1373 @@ + + + + + + + + AutoFlushWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Causes a flush on a wrapped target if LogEvent satisfies provided condition.
+If condition isn't set, a flush will occur after each successful write.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="AutoFlushWrapper" name="String" condition="Condition">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
  • condition - Condition is expression used to determine if flush must be executed.
    +

    Introduced in NLog 4.4

    +
    +
  • +
  • asyncFlush - Delay the flush until the LogEvent has been confirmed as written. Default true.
    +

    Introduced in NLog 4.4.6 where BufferingWrapper-target defaults to false, to avoid waiting long time (forever) to flush

    +
    +
  • +
+
+

NLog 4.7 implements same behavior for AsyncTaskTarget so it defaults to false, to reduce waiting time for flush.

+
+
    +
  • flushOnConditionOnly - Ignores explicit flush operations caused by calling NLog.LogManager.Flush() or NLog.LogManager.Shutdown(). Useful when combined with BufferingWrapper and overflowAction=Discard.
    +

    Introduced in NLog 4.6.6

    +
    +
  • +
+

Examples

+

Flush into target on each write

+
<?xml version="1.0" ?>
+<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="file" xsi:type="AutoFlushWrapper">
+            <target xsi:type="File" fileName="${basedir}/file.txt" />
+        </target>
+    </targets>
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

Flush into target, if LogEvent level >= Warn (introduced in NLog 4.4)

+
<?xml version="1.0" ?>
+<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="file" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Warn">
+            <target xsi:type="bufferingWrapper" overflowAction="Discard">
+               <target xsi:type="File" fileName="${basedir}/file.txt" />
+            </target>
+        </target>
+    </targets>
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Basedir-layout-renderer/index.html b/wiki/Basedir-layout-renderer/index.html new file mode 100644 index 000000000..3d1ff7ec7 --- /dev/null +++ b/wiki/Basedir-layout-renderer/index.html @@ -0,0 +1,1331 @@ + + + + + + + + Basedir layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The current application AppDomain.BaseDirectory, and usually the location of application-binaries.

+
+

Platforms Supported: All

+

See also ${processdir}, ${specialfolder}, ${currentdir}, ${tempdir}

+
+

Configuration Syntax

+
${basedir:dir=String:file=String:processDir=boolean}
+
+

Parameters

+

Advanced Options

+
    +
  • dir - Name of the directory to be Path.Combine()'d with the base directory.
  • +
  • file - Name of the file to be Path.Combine()'d with the base directory.
  • +
  • processDir - Introduced in NLog 4.4.2. Render the base directory of the current process? Default false.
    +

    Alternative one can use the ${processdir} introduced with NLog v4.7.1

    +
    +
  • +
  • fixTempDir - Enable automatic fallback to processDir when detecting AppDomain.BaseDirectory is temp-directory. Workaround for single-file-publish on NetCore 3.1, and no longer needed with .NET 6.
    +

    Introduced with NLog v4.6.8

    +
    +
  • +
+

See also: FileTarget FileName Directory

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/BufferingWrapper-target/index.html b/wiki/BufferingWrapper-target/index.html new file mode 100644 index 000000000..3d0c4a215 --- /dev/null +++ b/wiki/BufferingWrapper-target/index.html @@ -0,0 +1,1365 @@ + + + + + + + + BufferingWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A target that buffers log events and sends them in batches to the wrapped target. This wrapper is mostly to help throttle and filter log events. For high-performance logging use AsyncWrapper-target.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="BufferingWrapper"
+          name="String"
+          bufferSize="Integer"
+          flushTimeout="Integer"
+          slidingTimeout="Boolean"
+          overflowAction="Enum">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Buffering Options

+
    +
  • +

    bufferSize - Number of log events to be buffered. When the limit is reached, then a synchronous flush is performed. Integer Default: 100

    +
  • +
  • +

    flushTimeout - Timeout (in milliseconds) after a write, until the entire buffer is asynchronously flushed. Use -1 to disable timed flushes. Integer Default: -1

    +
  • +
  • +

    slidingTimeout - Indicates whether to use sliding flushTimeout. Boolean Default: True
    +This value determines how the inactivity period is determined. If sliding timeout is enabled, the inactivity timer is reset after each write, if it is disabled - inactivity timer will count from the first event written to the buffer.

    +
  • +
  • +

    overflowAction - Action to be taken when the buffer exceeds the set bufferSize. Enum Default: Flush. Introduced in NLog 4.5
    +Possible values:

    +
  • +
  • Flush - All the log events in the buffer will be written in the wrapped target.
  • +
  • Discard - The oldest log event will be removed from the buffer. If this setting is used, the Flush action will need to be triggered manually using another wrapper like the AutoFlushWrapper or by using the flushTimeout option.
  • +
+

Remarks

+

Buffering and custom targets

+

When messages are written into the BufferingWrapper, then LogEvents are queued for writing at a later stage. There can be custom NLog targets that requires writing to happen on the main thread for proper context capture (without being queued). When used together with BufferingWrapper then context information can be lost.

+

By default all standard NLog targets supports use of BufferingWrapper. Custom NLog targets that inherits from TargetWithContext should also by default work correctly with BufferingWrapper.

+

Buffer and asynchronously writing

+

If flushTimeout is larger than 0, then the messages are written asynchronously. If the buffer is filled before the flushTimeout fires and triggers the asynchronous flush, then the logging thread will be performing the flush, and be blocked by the operation.

+

Because the BufferingWrapper is not intended for performance optimization, but for throttling or even discarding LogEvents. Then it can be a good idea to make use of the async attribute or the AsyncWrapper.

+

Send batch when triggered by event

+

This will send the last 50 messages to the myTargetType, when an Error occurs:

+
  <target name="String" xsi:type="AutoFlushWrapper"
+          condition="level >= LogLevel.Error"
+          flushOnConditionOnly="true">
+     <target xsi:type="BufferingWrapper" bufferSize="50" overflowAction="Discard">
+         <target xsi:type="myTargetType" ...target properties... />
+     </target>
+  </target>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Cached-Layout-Renderer/index.html b/wiki/Cached-Layout-Renderer/index.html new file mode 100644 index 000000000..77bc7f607 --- /dev/null +++ b/wiki/Cached-Layout-Renderer/index.html @@ -0,0 +1,1347 @@ + + + + + + + + Cached Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Applies caching to another layout output.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${cached:cached=Boolean:clearCache=ClearCacheOption:inner=Layout:cacheKey=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:cached=Boolean}
+
+

Parameters

+

Caching Options

+
    +
  • cached - Indicates whether this CachedLayoutRendererWrapper is enabled. Boolean Default: True
  • +
  • clearCache - Indicates when the cache is cleared. Possible options: None, OnInit, Onclose. ClearCacheOption Default: OnInit, OnClose.
    +

    Introduced in NLog 4.2.

    +
    +
  • +
  • cacheKey - the layout to be checked if the cache is still valid. For example, the current day. Default: null.
    +

    Introduced in NLog 4.3.9

    +
    +
  • +
  • cachedSeconds - Cached value will expire after timeout. Default: infinite
    +

    Introduced in NLog 4.6.8

    +
    +
  • +
+

Transformation Options

+
    +
  • inner - Wrapped layout. Layout
  • +
+

Examples

+
    +
  • ${cached:cached=true:clearCache=OnInit,OnClose:inner=l}: The value of l is cached and the cache will be cleared when the layout renderer is initialized or when it is closed. This is the same as ${cached:cached=true:inner=l}.
  • +
  • ${cached:cached=true:clearCache=None:inner=l}: The value of l is cached and the cache will not be cleared.
  • +
  • filename="${cached:cached=true:Inner=${date:format=yyyy-MM-dd hh.mm.ss}:CacheKey=${shortdate}}.log" - Use the first logtime and day in the file name, only one file per day.
  • +
+

Remarks

+

The value of the inner layout will be rendered only once and reused subsequently.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Callsite-file-name-layout-renderer/index.html b/wiki/Callsite-file-name-layout-renderer/index.html new file mode 100644 index 000000000..ea70612d8 --- /dev/null +++ b/wiki/Callsite-file-name-layout-renderer/index.html @@ -0,0 +1,1326 @@ + + + + + + + + Callsite file name layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The call site source file name. For full callsite use CallSiteLayoutRenderer

+

Introduced in NLog v4.5

+

Supported in .NET and Mono.

+

Configuration Syntax

+
${callsite-filename:includeSourcePath=Boolean:skipFrames=Integer}
+
+

Parameters

+

Rendering Options

+
    +
  • includeSourcePath - Shows the full path of the source file. Boolean Default: True
  • +
  • skipFrames - The number of frames to skip. Integer Default: 0
  • +
  • captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true
    +

    Introduced with NLog 4.7.1

    +
    +
  • +
+

Notes

+

Please also note that this infers heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Callsite-layout-renderer/index.html b/wiki/Callsite-layout-renderer/index.html new file mode 100644 index 000000000..29e95289b --- /dev/null +++ b/wiki/Callsite-layout-renderer/index.html @@ -0,0 +1,1362 @@ + + + + + + + + Callsite layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

CallSite outputs the source-file-name and source-line-number where a LogEvent occurred. NLog scans the callstack and output the method-stackframe just before the NLog Logger takes over.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${callsite:className=Boolean:fileName=Boolean:includeSourcePath=Boolean:methodName=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • className - Indicates whether to render the class name. Boolean Default: True
  • +
  • includeNamespace - Include namespace in class name. Boolean Default: True
    +

    Introduced with NLog v4.4

    +
    +
  • +
  • fileName - Indicates whether to render the source file name and line number.Boolean Default: False
  • +
  • includeSourcePath - Indicates whether to include source file path.Boolean Default: True
  • +
  • methodName - Indicates whether to render the method name.Boolean Default: True
  • +
  • cleanNamesOfAnonymousDelegates - Indicates whether the method name will be cleaned up if it is detected as an anonymous delegate. Boolean Default: True
    +

    Introduced with NLog v4.3.9. Before NLog 5.0 the default value was False.

    +
    +
  • +
  • cleanNamesOfAsyncContinuations - Indicates whether the method and class names will be cleaned up if it is detected as an async continuation. Boolean Default: True
    +

    Introduced with NLog v4.5. Before NLog 5.0 the default value was False.

    +
    +
  • +
  • skipFrames - The number of frames to skip. Integer Default: 0
  • +
  • captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true
    +

    Introduced with NLog 4.7.1

    +
    +
  • +
+

Notes

+

The Callsite-LayoutRenderer infers a heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message. NLog 5.0 makes it possible to skip the StackTrace-capture, when using LogEventInfo.SetCallerInfo(...) with input from Caller Information-attributes.

+

NLog 5.0 provides Fluent-Logger-API for easy capture of caller-information, and provides fast logging when using ${callsite:captureStackTrace=false}:

+
_logger.ForInfoEvent()
+       .Message("This is a fluent message {0}", "test")
+       .Property("PropertyName", "PropertyValue")
+       .Log();
+
+

If using Custom wrapper for NLog Logger, then make sure to provide the typeof(OwnWrapper) as input, when calling NLog Logger:

+
Logger.Log(Type wrapperType, LogEventInfo logEvent)
+
+

Alternative if the custom Logger-wrapper comes from its own dedicated Assembly, then one can exclude the entire Assembly:

+
NLog.LogManager.AddHiddenAssembly(typeof(OwnWrapper).Assembly);
+
+

If symbol information is not available, then it will not be able to output source-code filename or line-number. Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause "unexpected" line-numbers.

+

If using Deterministic builds then it will generate symbol information with relative paths:

+
  <PropertyGroup>
+    <Deterministic>true</Deterministic>
+    <PathMap>$(SolutionDir)=./</PathMap>
+    <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
+  </PropertyGroup>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Callsite-line-number-layout-renderer/index.html b/wiki/Callsite-line-number-layout-renderer/index.html new file mode 100644 index 000000000..d9fd1d5fe --- /dev/null +++ b/wiki/Callsite-line-number-layout-renderer/index.html @@ -0,0 +1,1328 @@ + + + + + + + + Callsite line number layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The call site source-code line-number. For full callsite use ${callsite}

+
+

Platforms Supported: All

+

Introduced in NLog v4.1

+
+

Configuration Syntax

+
${callsite-linenumber:skipFrames=Integer}
+
+

Parameters

+

Rendering Options

+
    +
  • skipFrames - The number of frames to skip. Integer Default: 0
  • +
  • captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true
    +

    Introduced with NLog 4.7.1

    +
    +
  • +
+

Notes

+

Please also note that this infers heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message.

+

If symbol symbol information is not available, then it will only output source-code line-number 0. Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause "unexpected" line-numbers.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Chainsaw-target/index.html b/wiki/Chainsaw-target/index.html new file mode 100644 index 000000000..14424f9f2 --- /dev/null +++ b/wiki/Chainsaw-target/index.html @@ -0,0 +1,1531 @@ + + + + + + + + Chainsaw target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to the remote instance of Log4J XML Viewer applications (Like Chainsaw).

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6

+
+

This target inherits from the Network Target, and so it has also all the properties of the Network Target available. Using the Log4JXmlEventLayout to produce Log4J XML output.

+

ℹ️ NLog v6 has merged NLogViewer-Target and ChainSaw-Target into Log4JXml-Target

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Chainsaw"
+          name="String"
+          address="Layout"
+          newLine="Boolean"
+          onOverflow="Enum"
+          maxMessageSize="Integer"
+          encoding="Encoding"
+          connectionCacheSize="Integer"
+          lineEnding="CRLF|LF|CR|None"
+          maxConnections="Integer"
+          maxQueueSize="Integer"
+          keepConnection="Boolean"
+          onConnectionOverflow="Enum"
+          includeSourceInfo="Boolean"
+          includeCallSite="Boolean"
+          appInfo="String"
+          ndcItemSeparator="String"
+          includeNdc="Boolean">
+    <parameter layout="Layout" name="String"/><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • +

    layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout

    +
  • +
  • +

    encoding - Encoding to be used. Encoding Default: utf-8

    +
  • +
  • +

    newLine - Indicates whether to append newline at the end of log message. Boolean Default: False

    +
  • +
  • +

    lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF. Not used if newLine is false. Introduced in 4.3.8. +Possible values:

    +
  • +
  • CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default)
  • +
  • CR - Carriage Return (ASCII 13).
  • +
  • LF - Line Feed (ASCII 10).
  • +
  • NULL - Null terminator (ASCII 0)
  • +
  • +

    None - No end of line characters.

    +
  • +
  • +

    maxMessageSize - Maximum message size in bytes. Integer Default: 65000

    +
  • +
  • +

    onOverflow - Action that should be taken if the message-size is larger than maxMessageSize. +Possible values:

    +
  • +
  • Discard - Discard the entire message.
  • +
  • Error - Report an error.
  • +
  • Split - Split the message into smaller pieces (Default)
  • +
+

Connection Options

+
    +
  • +

    connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5

    +
  • +
  • +

    address - Network address. Layout +The network address can be:

    +
  • +
  • tcp://host:port - TCP (auto select IPv4/IPv6)
  • +
  • tcp4://host:port - force TCP/IPv4
  • +
  • tcp6://host:port - force TCP/IPv6
  • +
  • udp://host:port - UDP (auto select IPv4/IPv6)
  • +
  • udp4://host:port - force UDP/IPv4
  • +
  • udp6://host:port - force UDP/IPv6
  • +
  • http://host:port/pageName - HTTP using POST verb
  • +
  • +

    https://host:port/pageName - HTTPS using POST verb +For SOAP-based webservice support over HTTP use WebService target.

    +
  • +
  • +

    keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True

    +
  • +
  • +

    maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16. Not used if keepConnection is true.

    +
    +

    Introduced with NLog v4.2.1. Default became 16 with NLog v4.5 (Before 0)

    +
    +
  • +
  • +

    onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections.

    +
    +

    Introduced with NLog v4.2.1. Default became Block with NLog v4.5 (Before AllowNewConnnection)

    +
    +
  • +
+

Possible enum values: + * Discard - Discard new messages when reaching limit (Default) (Before NLog 5.0 it was enum value DiscardMessage) + * Grow - Send message and ignore limit (Before NLog 5.0 it was enum value AllowNewConnnection) + * Block - Block until pending connections has beeen freed.

+
    +
  • +

    maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer. Default: 10000 (Before NLog 5.0 the default was 0)

    +
    +

    NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. +NLog 5.0.0 enabled queue-support for UDP.

    +
    +
  • +
  • +

    onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize.

    +
    +

    Introduced with NLog 5.0

    +
    +
  • +
  • Discard - Discard the entire message (Default)
  • +
  • Grow - Ignore limit and grow the queue.
  • +
  • Block - Block until queue is below limit.
  • +
+

Payload Options

+
    +
  • +

    IncludeEventProperties - Include all events properties of a logevent? Default: true.

    +
    +

    Before NLog 5.0 option was named IncludeAllProperties and had default false.

    +
    +
  • +
  • +

    IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeMdlc or IncludeMdc

    +
    +
  • +
  • +

    includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean

    +
  • +
  • +

    includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean

    +
  • +
  • +

    IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeNdlc

    +
    +
  • +
  • +

    ScopeNestedSeparator - NDC item separator. Default:

    +
    +

    Before NLog 5.0 option was named NdlcItemSeparator

    +
    +
  • +
  • +

    includeNdc - Indicates whether to include ScopeNested-Layout-Renderer. Default: false.

    +
  • +
  • +

    ndcItemSeparator - NDC item separator. Default:

    +
  • +
  • +

    appInfo - AppInfo field. By default it's the friendly name of the current AppDomain.

    +
  • +
  • +

    loggerName - Logger field. By default it's the output of ${logger}

    +
    +

    Introduced in NLog 4.5

    +
    +
  • +
  • +

    formattedMessage - Message field. By default it's the output of ${message}

    +
    +

    Introduced in NLog 5.3

    +
    +
  • +
  • +

    parameter - Additional context properties that should be included.

    +
  • +
  • name - Name of Parameter. Required.
  • +
  • layout - The layout for the Parameter-Value. Required.
  • +
+

Example

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <targets>
+    <target name="log4j" xsi:type="Chainsaw" address="udp://127.0.0.1:5001" />
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="log4j" />
+  </rules>
+</nlog>
+
+

Available Log4J-XML viewers (See also LogViewer Tools) +- Sentinel - Avoid using TCP since not complete. +- Log2Console +- Logazmic +- Loginator +- Logbert +- LogViewer +- Lilith +- OtrosLogViewer

+

Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this:

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <targets>
+    <target name="throttle_log4j" type="AsyncWrapper" timeToSleepBetweenBatches="100" batchSize="1" overflowAction="Block">
+      <target name="log4j" type="Chainsaw" address="tcp://127.0.0.1:5001" newline="true" />
+    </target>
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="throttle_log4j" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ColoredConsole-target/index.html b/wiki/ColoredConsole-target/index.html new file mode 100644 index 000000000..ef5e6578c --- /dev/null +++ b/wiki/ColoredConsole-target/index.html @@ -0,0 +1,1597 @@ + + + + + + + + ColoredConsole target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to the console with customizable coloring.

+
+

Platforms Supported: All

+
+

There is also the simple Console-Target without any overhead from coloring.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="ColoredConsole"
+          name="String"
+          encoding="Encoding"
+          layout="Layout"
+          header="Layout"
+          footer="Layout"
+          useDefaultRowHighlightingRules="Boolean"
+          stderr="Boolean"
+          enableAnsiOutput="Boolean"
+          detectConsoleAvailable="Boolean"
+          detectOutputRedirected="Boolean">
+    <highlight-row condition="Condition" backgroundColor="Enum" foregroundColor="Enum"/><!-- repeated -->
+    <highlight-word text="String" condition="Condition" backgroundColor="Enum" foregroundColor="Enum"
+                    ignoreCase="Boolean" wholeWords="Boolean" /><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • +

    name - Name of the target.

    +
  • +
  • +

    encoding - File encoding name like "utf-8", "ascii" or "utf-16". See Encoding class on MSDN. Defaults to Encoding.Default.

    +
    +

    Introduced with NLog 4.0

    +
    +
  • +
+

Layout Options

+
    +
  • layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message}
  • +
  • header - Header. Layout
  • +
  • footer - Footer. Layout
  • +
+

Output Options

+
    +
  • +

    StdErr - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). Layout Default: False

    +
    +

    Before NLog v5.0 the property was named errorStream. +NLog 6.0 changed property from boolean to NLog Layout

    +
    +
  • +
  • +

    detectConsoleAvailable - Indicates whether the console target should disable itself when no console detected. Boolean Default: false

    +
    +

    Introduced in NLog 4.3.10 with default: true, then NLog 4.4 changed default to false.

    +
    +
  • +
  • +

    detectOutputRedirected - Indicates whether the console target should disable coloring when it detects that Console.IsOutputRedirected = true (Skip coloring when pipe to file)

    +
    +

    Introduced in NLog 4.6.7

    +
    +
  • +
  • +

    noColor - Incicates whether console target should disable coloring when detecting environment-variable NO_COLOR=1

    +
    +

    Introduced with NLog v5.4

    +
    +
  • +
  • +

    enableAnsiOutput - Enables output using ANSI Color Codes. Needed for e.g. Visual Studio Code. Boolean Default: false

    +
    +

    Introduced in NLog 4.6

    +
    +
  • +
  • +

    autoFlush - Performs explicit flush after every console write. Useful if having redirected to custom console-stream that doesn't has autoflush enabled. Boolean. Default = False.

    +
    +

    Introduced in NLog 4.6.3

    +
    +
  • +
+

Highlighting Rules

+
    +
  • useDefaultRowHighlightingRules - Indicates whether to use default row highlighting rules. Boolean Default: True
  • +
+

NLog v6 changed the default rules not use yellow for Error and maganta for Warn Colors :

+ + + + + + + + + + + + +
ConditionForeground ColorBackground Color
level == LogLevel.FatalRedNoChange
level == LogLevel.ErrorRedNoChange
level == LogLevel.WarnYellowNoChange
level == LogLevel.InfoWhiteNoChange
level == LogLevel.DebugGrayNoChange
level == LogLevel.TraceGrayNoChange
+ +
    +
  • rowHighlightingRules - The row highlighting rules. Collection
    +Each collection item is represented by \ element with the following attributes:
  • +
  • backgroundColor - Background color. Color Enum Default: NoChange
  • +
  • foregroundColor - Foreground color. Color Enum Default: NoChange
  • +
  • +

    condition - Condition that must be met in order to set the specified foreground and background color. Condition Required.

    +
  • +
  • +

    wordHighlightingRules - The word highlighting rules. Collection
    +Each collection item is represented by \ element with the following attributes:

    +
  • +
  • backgroundColor - Background color. Color Enum Default: NoChange
  • +
  • foregroundColor - Foreground color. Color Enum Default: NoChange
  • +
  • text - Text to be matched. You must specify either text or regex.
  • +
  • words - Comma-separated list of words to be matched (Make sure to remove leading/trailing spaces) + > Introduced with NLog v6.0.3
  • +
  • ignoreCase - Indicates whether to ignore case when comparing texts. Boolean Default: false
  • +
  • wholeWords - Indicates whether to match whole words only. Boolean Default: false
    + > Enhanced with NLog v6.0.4 so text can include special characters for matching, but only highlight letter-/digit-part.
  • +
  • condition - Condition that must be met before scanning for words to highlight. Condition. + > Introduced with NLog 4.7.1.
  • +
+

RegEx not supported

+

NLog v6 no longer supports word-highlight using Regular Expressions (RegEx) and removed these options:

+
    +
  • regex - Regular expression to be matched. You must specify either text or regex.
  • +
  • compileRegex - Introduced in NLog 4.3. Compiles the Regex. If false, the regex cache is used. Setting this to true can improve performance, but costs memory. Default: false
  • +
+

Colors

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Color EnumDescriptionHEX CodeANSI ForegroundANSI Background
NoChangeDon't change the color
BlackBlack Color#000000\x1B[30m\x1B[40m
BlueBlue Color#0000FF\x1B[94m\x1B[104m
CyanCyan Color#00FFFF\x1B[96m\x1B[106m
DarkBlueDark Blue Color#000080\x1B[34m\x1B[44m
DarkCyanDark Cyan Color#008080\x1B[36m\x1B[46m
DarkGrayDark Gray Color#808080\x1B[90m\x1B[100m
DarkGreenDark Green Color#008000\x1B[32m\x1B[42m
DarkMagentaDark Magenta Color#800080\x1B[35m\x1B[45m
DarkRedDark Red Color#800000\x1B[31m\x1B[41m
DarkYellowDark Yellow Color#808000\x1B[33m\x1B[43m
GrayGray Color#C0C0C0\x1B[37m\x1B[47m
GreenGreen Color#00FF00\x1B[92m\x1B[102m
MagentaMagenta Color#FF00FF\x1B[95m\x1B[105m
RedRed Color#FF0000\x1B[91m\x1B[101m
WhiteWhite Color#FFFFFF\x1b[97m\x1B[107m
YellowYellow Color#FFFF00\x1B[93m\x1B[103m
+

Programmatic example

+
var consoleTarget = new ColoredConsoleTarget();
+
+var highlightRule = new ConsoleRowHighlightingRule();
+highlightRule.Condition = ConditionParser.ParseExpression("level == LogLevel.Info");
+highlightRule.ForegroundColor = ConsoleOutputColor.Green;
+consoleTarget.RowHighlightingRules.Add(highlightRule);
+
+

Microsoft Extension Logging AddConsole

+

The NLog Layout of the ColoredConsole-Target can be configured to match the output of the default MEL AddConsole().

+

See also NLog Console and AddConsole

+

Visual Studio Output window

+

The Visual Studio "Output Window" is bit tricky with colors. It is not a real console window - it just displays the console output from the application.

+

You could get colors by prefixing the message in your config (Ex. Layout="${level:format=FulleName}: ${message}")

+
    +
  • "Error: " - for errors - red
  • +
  • "Warning: " - for warnings - orange
  • +
+

See Stackoverflow

+

Or use The Visual Studio extension VSColorOutput (VS2015-2019). Then you could also use the regular Console target.

+

Missing colors for dotnet watch run

+

When running application using dotnet watch run then one might experience that console colors are missing.

+

This can be fixed by changing launchSettings.json and removing the entry launchBrowser and the colors should return.

+

See also: https://github.com/dotnet/aspnetcore/issues/25317

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Combine-XML-config-with-C#-config/index.html b/wiki/Combine-XML-config-with-C#-config/index.html new file mode 100644 index 000000000..f14df00f8 --- /dev/null +++ b/wiki/Combine-XML-config-with-C#-config/index.html @@ -0,0 +1,1364 @@ + + + + + + + + Combine XML config with C# config - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Combining XML config with C# config is tricky, as autoreload/load of the XML file could overwrite the C# config.

+

To combine both, the ConfigurationChanged event is needed

+

Example

+
    +
  • We use the nlog.config and
  • +
  • We add the console target and rules in C#
  • +
+
using System;
+using NLog;
+using NLog.Config;
+using NLog.Targets;
+
+class Program
+{
+    // Define a static logger variable so that it references the logger instanced named "Scribe"
+    private static readonly Logger log = LogManager.GetCurrentClassLogger();
+
+    static void Main(string[] args)
+    {
+        ExtendNLogConfig();
+
+        LogManager.ConfigurationChanged += LogManager_ConfigurationChanged;
+
+        log.Info("Entering Application.");
+
+        Console.WriteLine("Press any key to exit ...");
+        Console.Read();
+    }
+
+
+    private static void LogManager_ConfigurationChanged(object sender, LoggingConfigurationChangedEventArgs e)
+    {
+        if (e.ActivatedConfiguration != null)
+        {
+           ExtendNLogConfig();
+        }
+    }
+
+    /// <summary>
+    /// Extend the logging rules in the nlog.config with programmically rules.
+    /// </summary>
+    private static void ExtendNLogConfig()
+    {
+        // Do NOT set LogManager.Configuration because that will cause recursion and stackoverflow
+        var consoleTarget = new ColoredConsoleTarget();
+        consoleTarget.Name = "console";
+        LogManager.Configuration.AddTarget("console", consoleTarget);
+
+        consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message} ${exception} ${event-properties:item=MyValue}";
+        var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
+        LogManager.Configuration.LoggingRules.Add(rule1);
+        LogManager.ReconfigExistingLoggers();
+    }
+}
+
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/CompoundLayout/index.html b/wiki/CompoundLayout/index.html new file mode 100644 index 000000000..d9795ed33 --- /dev/null +++ b/wiki/CompoundLayout/index.html @@ -0,0 +1,1366 @@ + + + + + + + + CompoundLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Concatenate multiple layouts, so they become a single layout.

+
+

Platforms Supported: All

+

Introduced in NLog 4.3.6

+
+
<target name='file' type='File' fileName='log.txt'>
+  <layout type='CompoundLayout'>
+    <layout type='SimpleLayout' text="text1" />
+    <layout type='SimpleLayout' text=" - " />
+    <layout type='SimpleLayout' text="text2" />
+  </layout>
+</target>
+
+
text1 - text2
+
+

Advanced examples

+

From code

+
var compoundLayout = new CompoundLayout
+{
+    Layouts =
+    {
+        new SimpleLayout("myAmazingText: "),
+        new JsonLayout
+        {
+            Attributes =
+            {
+                new JsonAttribute("time", "${longdate}"),
+                new JsonAttribute("level", "${level:upperCase=true}"),
+            }
+        }
+    }
+};
+
+
myAmazingText: { "time": "2016-10-30 13:30:55.0000", "level": "INFO" }
+
+

From XML

+
<nlog>
+  <targets>
+    <target name='file' type='File' fileName='log.txt'>
+      <layout type='CompoundLayout'>
+        <layout type='SimpleLayout' text="myAmazingText: " />
+        <layout type='JsonLayout'>
+          <attribute name='time' layout='${longdate}' />
+          <attribute name='level' layout='${level:upperCase=true}'/>
+        </layout>
+      </layout>
+    </target>
+  </targets>
+  <rules>
+  </rules>
+</nlog>
+
+
myAmazingText: { "time": "2016-10-30 13:30:55.0000", "level": "INFO" }
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Conditions/index.html b/wiki/Conditions/index.html new file mode 100644 index 000000000..f03ea1234 --- /dev/null +++ b/wiki/Conditions/index.html @@ -0,0 +1,1307 @@ + + + + + + + + Conditions - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

See https://github.com/NLog/NLog/wiki/When-Filter#conditions

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ConfigSetting-Layout-Renderer/index.html b/wiki/ConfigSetting-Layout-Renderer/index.html new file mode 100644 index 000000000..6e1c5dec2 --- /dev/null +++ b/wiki/ConfigSetting-Layout-Renderer/index.html @@ -0,0 +1,1359 @@ + + + + + + + + ConfigSetting Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Lookup value from the appsettings.json or appsettings.Production.json and other configuration sources/overrides.

+
+

Introduced with NLog.Extensions.Logging 1.4.0 and NLog.Web.AspNetCore 4.8.0

+
+

Configuration Syntax

+
${configsetting:item=String:default=String}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Key in the config. Required. Use . for nested objects.
  • +
  • Default - Default value if not present. Optional.
  • +
+

Setup ConfigSetting

+

${configsetting} depends on Microsoft.Extensions.Configuration being loaded and available, so if using UseNLog() or AddNLog() on HostBuilder then everything will work out-of-the-box.

+

But if needing to load NLog configuration early before HostBuilder is ready, then ${configsetting} will not resolve the expected values, which might cause NLog Targets not using the expected configuration values. It is possible to setup ${configsetting} manually for these situations.

+

NLog Fluent Setup using LoadConfigurationFromAppSettings() from NLog.Web.AspNetCore nuget-package:

+
var logger = LogManager.Setup()
+                       .LoadConfigurationFromAppSettings()
+                       .GetCurrentClassLogger();
+
+

NLog Fluent Setup using LoadConfigurationFromSection(() from NLog.Extensions.Logging nuget-package:

+
IConfigurationRoot config = new ConfigurationBuilder()
+    .AddJsonFile(path: "AppSettings.json").Build();
+var logger = LogManager.Setup()
+                       .LoadConfigurationFromSection(config)
+                       .GetCurrentClassLogger();
+
+

NLog v4 can perform manual registration like this with NLog.Extensions.Logging nuget-package:

+
IConfigurationRoot config = new ConfigurationBuilder()
+    .AddJsonFile(path: "AppSettings.json").Build();
+NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration = config;
+
+

Examples

+

Example: appsettings.json:

+
{
+    "Mode":"Prod",
+    "Options":{
+        "StorageConnectionString":"UseDevelopmentStorage=true",
+    }
+}
+
+

Config Setting Lookup:

+
${configsetting:item=Mode} // renders "Prod"
+${configsetting:item=Options.StorageConnectionString} // renders "UseDevelopmentStorage=true"
+${configsetting:item=Options.TableName:default=MyTable} // renders "MyTable"
+
+

Config Setting Lookup Cached:

+
${configsetting:cached=True:item=Mode}
+
+

Notice appsettings.json gives the ability to make environment-specific overrides (Ex. appsettings.Production.json). See also Environment-specific-NLog-Logging-Configuration

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Configuration-API/index.html b/wiki/Configuration-API/index.html new file mode 100644 index 000000000..444f610ed --- /dev/null +++ b/wiki/Configuration-API/index.html @@ -0,0 +1,1307 @@ + + + + + + + + Configuration API - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

moved here: https://github.com/NLog/NLog/wiki/Configure-from-code

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Configuration-file/index.html b/wiki/Configuration-file/index.html new file mode 100644 index 000000000..c38b15edb --- /dev/null +++ b/wiki/Configuration-file/index.html @@ -0,0 +1,1772 @@ + + + + + + + + Configuration file - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog will only produce output if having configured one (or more) NLog targets. NLog can be configured using XML by adding a NLog.config, that will be described in the page.

+

Everything that can be configured from XML file, can be also be configured in code. See also How to configure from code.

+

Notice instead of using XML configuration file, then it is also possible to load NLog LoggingConfiguration from the appsettings.json file with help from NLog.Extensions.Logging.

+

Contents

+

NLog config XML
+File locations
+Top-level elements
+Targets
+Log levels
+Rules
+Variables
+Layouts and layout renderers
+Asynchronous processing and wrapper targets
+Default wrappers
+Default target parameters
+Extensions
+Automatic reconfiguration
+Include files
+Content escaping
+Troubleshooting logging

+

+

NLog config XML

+

Example XML for a stand-alone NLog.config that can be added to Visual Studio Project (Remember to configure File Properties: Copy If newer):

+
<?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="logfile" xsi:type="File" fileName="file.txt" />
+        <target name="logconsole" xsi:type="Console" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Info" writeTo="logconsole" />
+        <logger name="*" minlevel="Debug" writeTo="logfile" />
+    </rules>
+</nlog>
+
+

The NLog configuration can also be embedded into the .NET Framework application configuration file (app.config or web.config). This is done by adding an nlog section element under configSections and then use the nlog element. For example:

+
<configuration>
+  <configSections>
+    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
+  </configSections>
+  ...
+  <nlog>
+    <targets>
+       <target name="logconsole" xsi:type="Console" />
+    </targets>
+    <rules>
+       <logger name="*" minlevel="Info" writeTo="logconsole" />
+    </rules>
+  </nlog>
+</configuration>
+
+

The use of an XML namespace is optional, but enables Intellisense in Visual Studio.

+

NLog config XML is case-insensitive for Xml-Nodes and Xml-Attributes, when not using a namespace and is case-sensitive when using a namespace.

+

+

File locations

+

At startup, NLog searches for its configuration in various files as described below. It loads the first nlog configuration found. Search ends when the first nlog configuration is found. NLog will not perform any logging if configuration is not found.

+

For a stand-alone *.exe application, files are searched as follows: +* standard application configuration file app.config (Ex. applicationname.exe.config) +* applicationname.exe.nlog in application’s directory +* NLog.config in application’s directory +* NLog.dll.nlog in a directory where NLog.dll is located (only if NLog isn't installed in the GAC)

+

For an ASP.NET application, files are searched as follows: +* standard web application configuration file web.config +* web.nlog located in the same directory as web.config +* NLog.config in application’s directory +* NLog.dll.nlog in a directory where NLog.dll is located (only if NLog isn't installed in the GAC)

+

See also Explicit NLog configuration loading (Includes details about assets-folder for Xamarin Android).

+

+

Top-level elements

+

You can use the following elements as children to nlog. targets and rules are required in any configuration The others are optional and can be useful in advanced scenarios. + * targets – defines log targets/outputs + * rules – defines log routing rules + * extensions – loads NLog extensions from the *.dll file + * include– includes external configuration file + * variable – sets the value of a configuration variable

+

The simplest configuration consists of one target and one rule (logger) that routes messages to the target.

+

+

Targets

+

The targets section defines log Targets. Each target is represented by a target element. There are two attributes required for each target: + * name – target name + * type – target type – such as "File", "Database", "Mail". When using namespaces this attribute is named xsi:type.

+

In addition to these attributes, targets usually accept other parameters, which impact the way diagnostic traces are written. Each target has a different set of parameters, they are described in detail on project’s homepage and they are context-sensitive. Intellisense is also available in Visual Studio.

+

For example – the File target accepts the fileName parameter which defines output file name and the Console target has the error parameter which determines whether the diagnostic traces are written to standard error (stderr) instead of standard output (stdout) of the process.

+

This example demonstrates a targets section which defines multiple targets: two files, one network target and OutputDebugString target:

+
<targets>
+  <target name="f1" xsi:type="File" fileName="file1.txt"/>
+  <target name="f2" xsi:type="File" fileName="file2.txt"/>  
+  <target name="n1" xsi:type="Network" address="tcp://localhost:4001"/>
+  <target name="ds" xsi:type="OutputDebugString"/>
+</targets>
+
+

NLog provides many predefined Targets. It’s actually very easy to create your own target - see How to write a custom Target.

+

+

Log levels

+

Each log entry has a level. And each logger is configured to include or ignore certain levels. A common configuration is to specify the minimum level where that level and higher levels are included. For example, if the minimum level is Info, then Info, Warn, Error and Fatal are logged, but Debug and Trace are ignored.

+

The log levels ordered by severity:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
LogLevelOrdinalSeverityTypical Use
Trace0Most verbose level. Used for development and seldom enabled in production.Ex. Request-payload, Response-payload, Begin-method-X or End-method-X
Debug1Debugging the application behavior from internal events of interest.Ex. Executed query, User authenticated, Session expired
Info2Information about application lifetime events like starting/stopping and configuration changes.
Warn3Warnings about validation issues or temporary failures that can be recovered.
Error4Errors where functionality has failed or Exception have been caught.
Fatal5Most critical level. Application is about to abort.
Off6Artificial level for disabling logger output
+

The special loglevel Off has the highest ordinal value. It is not used for LogEvents, but can be used for filtering in logging rules.

+

+

Rules

+

The rules section controls how LogEvents from the Logger-objects are redirected to output targets. Where logger-name and log levels can be used for filtering.

+

When creating a NLog Logger-object then one must provide a logger-name like NLog.LogManager.GetLogger("my logger name"). The logger-name can also be extracted from class-context by using NLog.LogManager.GetCurrentClassLogger() where logger-name becomes "NameSpace.ClassName".

+

A single rule is defined with a logger element that filters what Logger-objects to match:

+
    +
  • name – Match logger-name of the Logger-object - may include wildcard characters (* and ?)
  • +
  • minlevel – minimum level to log (matches the specified level and levels above)
  • +
  • maxlevel – maximum level to log (matches the specified level and levels below)
  • +
  • level – single level to log.
  • +
  • levels - comma separated list of levels to log
  • +
  • writeTo – comma separated list of targets to write to
  • +
  • final – no rules are processed after a final rule matches
  • +
  • enabled - set to false to discard the logging rule completely, and reload is required to re-enable. Please note only literal true or false values can be used here; variables cannot be used to set this property.
  • +
  • ruleName - rule identifier to allow rule lookup with Configuration.FindRuleByName and Configuration.RemoveRuleByName. Introduced in NLog 4.6.4
  • +
  • finalMinLevel - Loggers matching will be restricted to specified minimum level for following rules. Introduced in NLog 5.0
  • +
+

The example below shows 2 rules that matches ALL Logger-objects independent of their logger-name because of name="*": +- First rule will match LogEvents with minimum LogLevel = Debug (or more severe), and matching LogEvents will be written to the file-target. +- Second rule will only match LogEvents with minimum LogLevel = Info (or more severe) and redirect to the console-target. This means a LogEvent with LogLevel = Info will match both rules and be written to both targets.

+
<targets>
+    <target name="logfile" xsi:type="File" fileName="file.txt" />
+    <target name="logconsole" xsi:type="Console" />
+</targets>
+
+<rules>
+    <logger name="*" minlevel="Debug" writeTo="logfile" />
+    <logger name="*" minlevel="Info" writeTo="logconsole" />
+</rules>
+
+

Rules are processed in sequential order. Multiple rules may apply to a logger. Use final to stop processing rules after a match is found.

+

If wanting to dynamically enable / disable a logger-rule at runtime with Layout-support. Then it is recommended not to use enabled, but instead use minLevel and use minLevel="Off" to disable output. See also Semi Dynamic Routing Rules

+

Note: Although a rule is named logger, it does not define a logger. It references one or more loggers based on the name-pattern.

+

Logger Name Filter

+

A rule is mapped to a logger by matching the rule name pattern to a logger name. A rule name attribute may include wildcard characters (* and ?) to match logger names by wildcard matching.
+ * * - matches 0 or more characters + * ? - matches exactly 1 character

+

+

+

When using NLog.LogManager.GetCurrentClassLogger() then the logger name will have the format "NameSpace.ClassName". This makes it very convenient to setup filtering for all classes within a namespace:

+
<logger name="Name.Space.*" writeTo="target1" />
+
+

By using logger-name filtering then one can also redirect output for a single ClassName-logger:

+
<logger name="Name.Space.Class1" writeTo="target2" /> <!-- Add final=true to stop output to target1 -->
+<logger name="Name.Space.*" writeTo="target1" />
+
+

One can also reduce the logging from a single ClassName-logger:

+
<logger name="Name.Space.Class2" maxlevel="Warn" final="true" /> <!-- Blackhole that stops all but Error + Fatal -->
+<logger name="Name.Space.*" writeTo="target1" />
+
+

One can also completely block a single ClassName-logger:

+
<logger name="Name.Space.Class3" maxlevel="Off" final="true" /> <!-- Blackhole that stops everything -->
+<logger name="Name.Space.*" writeTo="target1" />
+
+

Before NLog 4.6 then one could only use wildcards (*) at the beginning and/or at the end of the pattern:

+
<rules>
+  <logger name="*" minlevel="Info" writeTo="logconsole" />
+  <logger name="Name.Space.*" minlevel="Debug" writeTo="f1" />
+  <logger name="*.Class1" minlevel="Trace" writeTo="f2" />
+  <logger name="*.Library.*" minlevel="Warn" writeTo="f3" />
+</rules>
+
+

Since NLog 4.6, wildcards (* and ?) are allowed in any position.

+
<rules>
+  <logger name="*TcpTestServer[*].Connection[07].*" minlevel="Trace" writeTo="logconsole" final="true" />
+  <logger name="*TcpTestServer[*].Connection[??].*" minlevel="Debug" writeTo="logconsole" final="true" />
+  <logger name="*" minlevel="Info" writeTo="logconsole" />
+</rules>
+
+

Logger Level Filter

+

A rule defines which log entry level(s) are matched. Entries with other levels will not match this rule. A commonly used specifier is minlevel. The other specifiers allow for more advanced configuration.

+

If a rule contains more than one level-declaring attribute (level, levels, minlevel and maxlevel) only the first level-declaring attribute or set is used and the rest are ignored.

+

The level-declaring attributes are processed in the following order:

+
    +
  1. level
  2. +
  3. levels
  4. +
  5. minlevel and maxlevel (these have the same priority)
  6. +
  7. none (all levels are logged)
  8. +
+

For example: if minlevel="Warn" level="Info" is used, the rule will only use Info

+

In case a rule is marked as final and contains any level-declaring attributes, the final attribute applies only to the specified levels.

+

Dynamic Logger Level Filter

+

The logging rules provides high performance because of their static nature. The options for configuration has been very limited. But recent changes has now been made to improve this:

+
    +
  • NLog 4.6 added support for using NLog Config Variables to configure level attributes. (level, minlevel etc):
  • +
+
<variable name='globalLevel' value='debug'/>
+
+<rules>
+  <logger minlevel='${globalLevel}'/>
+</rules>
+
+
+

+

Variables

+

NLog Config Variables allows you to simplify configuration by reducing repeated text. Variable can be used to give a human name to a NLog Layout that is commonly used (or is long and complex). This makes it easier to organize and structure the NLog config.

+

Define a custom variable as follows:

+
<variable name="varname" value="xxx" />
+
+

The value of a variable can be inserted into an attribute value via the ${varname} syntax. A variable value can even be used to define the value of another variable. The following example shows using a pre-defined variable shortdate and defining and using a custom variable logDirectory.

+
<nlog>
+  <variable name="logDirectory" value="logs/${shortdate}"/>
+  <targets>
+    <target name="file1" xsi:type="File" fileName="${logDirectory}/file1.txt"/>
+    <target name="file2" xsi:type="File" fileName="${logDirectory}/file2.txt"/>
+  </targets>
+</nlog>
+
+

With this syntax, a variable must be defined before use. Otherwise configuration initialization will fail. Note ${gdc} can be used used as an alternative to configuration variables, as they work independent of loading / unloading / reloading different NLog configurations.

+

NLog Config variables can operate in two modes:

+
    +
  • Constant mode - ${varName}
  • +
  • Dynamic mode - ${var:varName} (Introduced with NLog 4.1)
  • +
+

Constant mode (or static mode) works for all types of properties independent of their type, but they will not react to runtime changes.

+

Dynamic mode only works for properties of the type NLog Layout, and provides the following abilities:

+
    +
  • Variables can be changed, deleted and created from the Configuration API
  • +
  • A default value can be configured for a variable, e.g. ${var:password:default=unknown}
  • +
  • By default all variables assigned at runtime are kept even after configuration reloads. Unless having configured keepVariablesOnReload="false".
    +

    NLog 4.4 introduced keepVariablesOnReload and before NLog 5.0 the default value was false

    +
    +
  • +
+

NLog 5.0 extends NLog config variables to also handle complex Layout types like JsonLayout + CsvLayout. Ex:

+
<nlog>
+  <variable name="myJsonLayout">
+    <layout type="JsonLayout">
+       <attribute name="message" value="${messsage}">
+    </layout>
+  </variable>
+  <targets>
+    <target name="debug" type="Debug" layout="${myJsonLayout}" />
+  </targets>
+  <rules>
+    <logger name="*" minlevel="Debug" writeTo="debug" />
+  </rules>
+</nlog>
+
+

+

Layouts and layout renderers

+

One of NLog’s strongest assets is the ability to use layouts. In the simplest form, layouts are texts with embedded tags delimited by ${ and }. The tags are called Layout Renderers and can be used to insert pieces of contextual information into the text.

+

Layouts can be used in many places, for example they can control the format of information written on the screen or sent to a file, but also to control the file names themselves. This is very powerful, which we’ll see in a moment.

+

Let’s assume, that we want to annotate each message written to the console with: +* current date and time +* name of the class and method that emitted the log message +* log level +* message text

+

This is very easy:

+
<target name="c" xsi:type="Console"  layout="${longdate} ${callsite} ${level} ${message}"/>
+
+

We can make each messages for each logger go to a separate file, as in the following example:

+
<target name="f" xsi:type="File" fileName="${logger}.txt"/>
+
+

As you can see, the ${logger} layout renderer was used in the fileName attribute, which causes each log message to be written to the file whose name includes the logger name. The above example will create the following files: +* Name.Space.Class1.txt +* Name.Space.Class2.txt +* Name.Space.Class3.txt +* Other.Name.Space.Class1.txt +* Other.Name.Space.Class2.txt +* Other.Name.Space.Class3.txt

+

+

Asynchronous processing and wrapper targets

+

NLog provides wrapper and compound targets which modify other targets’ behavior by adding features like: +* asynchronous processing (wrapped target runs in a separate thread) +* retry-on-error +* load balancing +* buffering +* filtering +* failover (failover)

+

To define a wrapper in the configuration file, simply nest a target node within another target node. You can even wrap a wrapper target - there are no limits on depth. For example, to add asynchronous logging with retry-on-error functionality add this to your configuration file:

+
<targets>
+  <target name="n" xsi:type="AsyncWrapper">
+    <target xsi:type="RetryingWrapper">
+      <target xsi:type="File" fileName="${file}.txt" />
+    </target>
+  </target>
+</targets>
+
+

Because asynchronous processing is a common scenario, NLog supports a shorthand notation to enable it for all targets without the need to specify explicit wrappers. You can simply set async="true" on targets element and all your targets within that element will be wrapped with the AsyncWrapper target.

+
<nlog>
+  <targets async="true">
+    <!-- all targets in this section will automatically be asynchronous -->
+  </targets>
+</nlog>
+
+

Remember to Flush is very important, when using asynchronous background writing. It ensures all logging is written before application exit.

+

+

Default wrappers

+

Sometimes we require ALL targets to be wrapped in the same way, for example to add buffering and/or retrying. NLog provides <default-wrapper /> syntax for that. You simply put this element in the <targets /> section and all your targets will be automatically wrapped with the specified wrapper. Note that <default-wrapper /> applies to the single <targets /> section only and you can have multiple sections so you can define groups of targets that are wrapped in a similar manner.

+
<nlog>  
+  <targets>  
+    <default-wrapper xsi:type="BufferingWrapper" bufferSize="100"/>  
+    <target name="f1" xsi:type="File" fileName="f1.txt"/>  
+    <target name="f2" xsi:type="File" fileName="f2.txt"/>  
+  </targets>  
+  <targets>  
+    <default-wrapper xsi:type="AsyncWrapper">  
+      <wrapper-target xsi:type="RetryingWrapper"/>  
+    </default-wrapper>  
+    <target name="n1" xsi:type="Network" address="tcp://localhost:4001"/>  
+    <target name="n2" xsi:type="Network" address="tcp://localhost:4002"/>  
+    <target name="n3" xsi:type="Network" address="tcp://localhost:4003"/>  
+  </targets>  
+</nlog>
+
+

In the above example we’ve defined two buffered File targets and three asynchronous and retrying Network targets.

+

+

Default target parameters

+

Similar to default wrappers, NLog provides <default-target-parameters /> which enables you to specify default values of target parameters. For example, if you don’t want files to be kept open, you can either add keepFileOpen="false" to each target, as in the following example:

+
<nlog>
+  <targets>
+    <target name="f1" xsi:type="File" fileName="f1.txt" keepFileOpen="false"/>
+    <target name="f2" xsi:type="File" fileName="f2.txt" keepFileOpen="false"/>
+    <target name="f3" xsi:type="File" fileName="f3.txt" keepFileOpen="false"/>
+   </targets>
+</nlog>
+
+

Alternatively you can specify a single <default-target-parameters /> that applies to all targets in the <targets /> section. Default parameters are defined on a per-type basis and are applied BEFORE the actual attributes defined in the XML file:

+
<nlog>
+  <targets>
+    <default-target-parameters xsi:type="File" keepFileOpen="false"/>
+    <target name="f1" xsi:type="File" fileName="f1.txt"/>
+    <target name="f2" xsi:type="File" fileName="f2.txt"/>
+    <target name="f3" xsi:type="File" fileName="f3.txt"/>
+  </targets>
+</nlog>
+
+

+

Extensions

+

Extensions can be configured to include additional NLog packages or custom ones:

+

Just reference the DLL in the config in the <extensions /> as shown below. +The name should not include the .dll

+

Configuration file example:

+
<nlog> 
+  <extensions> 
+    <add assembly="MyAssembly"/> 
+  </extensions> 
+  <targets> 
+    <target name="a1" type="MyTarget" host="localhost"/> 
+  </targets> 
+  <rules> 
+    <logger name="*" minlevel="Info" appendTo="a1"/> 
+  </rules> 
+</nlog>
+
+

With NLog 5.0 it is also possible to specify fully qualified type-name, instead of needing to update <extensions>-section. This makes the snippets more isolated:

+
<nlog> 
+  <targets> 
+    <target name="a1" type="MyTarget, MyAssembly" host="localhost"/> 
+  </targets> 
+  <rules> 
+    <logger name="*" minlevel="Info" appendTo="a1"/> 
+  </rules> 
+</nlog>
+
+

NLog 5.0 no longer automatically scans and loads extensions from assemblies with NLog-prefix. Because it introduced overhead during startup, and failed to work with <packagereference>. See also Register-your-custom-component

+

+

Automatic reconfiguration

+

The configuration file is read automatically at program startup. In a long running process (such as a Windows service or an ASP.NET application) it’s sometimes desirable to temporarily increase the log level without stopping the application. NLog can monitor logging configuration files and re-read them each time they are modified. To enable this mechanism, you simply add autoReload="true" parameter to the configuration file.

+
<nlog autoReload="true">
+   ...
+</nlog>
+
+

Note that automatic reconfiguration supports include files, so each time one of the included files is changed, the entire configuration gets reloaded.

+

Just to make it explicit, automatic reloading will NOT stop/recycle the IIS Application Pool.

+

+

Include files

+

NLog provides an include file feature so that configuration can be stored in multiple files.

+
<include file="nlog-common.config" />
+
+

Like most attributes in NLog config, the file attribute may reference variables. The following example includes a file named the same as the machine that nlog is running on.

+
<include file="${machinename}.config" ignoreErrors="true" />
+
+

Setting the attribute ignoreErrors to true prevents a startup failure if the include file cannot be loaded -- file not found, invalid XML, .... Use the Troubleshooting logging section to log errors. This attribute is optional and defaults to false.

+

Since NLog 4.4.2, wildcards (*) are allowed. E.g. <include file="nlog-*.config"/>

+

A larger example can be found here: XML config <include /> example

+

+

Content escaping

+

In the configuration file some characters needs to be escaped. +Because it XML file, the < and > brackets should be escaped with &lt; and &gt;. This also holds for the attribute values, like a condition.

+

Inside a layout we need to escape the } bracket and the colon : should be escaped because:

+
    +
  • : is the value separator.
  • +
  • } is the end of the layout
  • +
+

Nested layout renderers doesn't need escaping. Also the backslash doesn't need an escape.

+

Examples:

+
    +
  • ${appdomain:format={1\}{0\}} (escape of })
  • +
  • ${rot13:inner=${scopenested:topFrames=3:separator=x}} (no escaping needed)
  • +
  • ${when:when=1 == 1:Inner=Test\: Hello} (escape of :)
  • +
+

+

Troubleshooting logging

+

If log output is missing, the issue may be related to configuration loading, logging rules, target initialization, filesystem permissions, deployment configuration, or application execution.

+

NLog provides several settings that can help diagnose logging issues:

+
    +
  • <nlog internalLogLevel="Trace|Debug|Info|Warn|Error|Fatal" /> — Enables NLog InternalLogger output. Internal logging is often the most useful diagnostic tool when troubleshooting configuration loading, log routing, and target-writing issues.
  • +
  • <nlog throwConfigExceptions="true" /> — Causes configuration-loading errors to be surfaced as exceptions instead of being silently ignored. This setting is recommended during troubleshooting and is often appropriate in production environments where successful loading of the logging configuration is required.
  • +
  • <nlog throwExceptions="true" /> — Causes runtime logging exceptions to be propagated to the calling application instead of being handled internally. This setting is intended only for troubleshooting and unit testing. Do not enable it in production environments because logging failures may cause application errors or crashes.
  • +
+

For systematic troubleshooting steps, examples, and common causes of missing log output, see Logging-troubleshooting.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Configure-NLog/index.html b/wiki/Configure-NLog/index.html new file mode 100644 index 000000000..3df1eb086 --- /dev/null +++ b/wiki/Configure-NLog/index.html @@ -0,0 +1,1307 @@ + + + + + + + + Configure NLog - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Moved here https://github.com/NLog/NLog/wiki/Configuration-file

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Configure-component-logging/index.html b/wiki/Configure-component-logging/index.html new file mode 100644 index 000000000..a3a0202fc --- /dev/null +++ b/wiki/Configure-component-logging/index.html @@ -0,0 +1,1353 @@ + + + + + + + + Configure component logging - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The default approach for managing Loggers via the global singleton LogManager class in NLog. It works well for homogeneous applications where the main application and all the extension components are configured via a single configuration file.

+

By including the component class-namespace in the Logger-name (Happens automatically when using NLog.LogManager.GetCurrentClassLogger()), then it is easy to configure NLog Logging-Rules to route to the wanted destination-target for the plugin (Ex. filename="Plugin-${logger}.log").

+

Isolated Logger Property

+

If the component is complex and uses many Logger-instances, then one can consider to also imbue the component Logger-instance with a common LogEvent-PropertyName:

+
var pluginLogger = NLog.LogManager.GetLogger(componentName).WithProperty("ComponentName", componentName);
+
+

Then it is possible to include the component-identifier in the target output. Ex ${event-properties:ComponentName:whenEmpty=Core}

+

See also ${event-properties}

+

Isolated LogFactory

+

But sometimes you want to create a separate logging configuration, just for a particular component, plugin or extension. Instead of using LogManager (which is global to an application) then one can use isolated LogFactory object-instance that is local to your component/plugin. It allows you to have multiple LogFactory-instances, where each have their own isolated logging configuration.

+

When creating LogFactory you need to explicitly pass the configuration (either from a file or by programmatically constructing targets and rules) as in the following example:

+
internal class MyLogManager 
+{ 
+    // A Logger dispenser for the current assembly (Remember to call Flush on application exit)
+    public static LogFactory Instance { get { return _instance.Value; } }
+    private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);
+
+    // 
+    // Use a config file located next to our current assembly dll 
+    // eg, if the running assembly is c:\path\to\MyComponent.dll 
+    // the config filepath will be c:\path\to\MyComponent.nlog 
+    // 
+    // WARNING: This will not be appropriate for assemblies in the GAC 
+    // 
+    private static LogFactory BuildLogFactory()
+    {
+         // Use name of current assembly to construct NLog config filename 
+         Assembly thisAssembly = Assembly.GetExecutingAssembly(); 
+         string configFilePath = Path.ChangeExtension(thisAssembly.Location, ".nlog"); 
+
+         LogFactory logFactory = new LogFactory();
+         logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory); 
+         return logFactory;
+    }
+}
+
+

Then all you need to do is to create loggers with:

+
Logger logger = MyLogManager.Instance.GetLogger("name");
+
+

or

+
Logger logger = MyLogManager.Instance.GetCurrentClassLogger();
+
+

If you want multiple assemblies to share this MyLogManager – just make it a public class and get others to use it.

+

NLog LogFactory will attempt to automatically shutdown together with the AppDomain / ProcessExit. But it is recommended to shutdown the isolate LogFactory in the plugin-dispose-stage by calling LogFactory.Shutdown().

+

See Also: Explicit NLog configuration loading

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Configure-from-code/index.html b/wiki/Configure-from-code/index.html new file mode 100644 index 000000000..e17d9ef28 --- /dev/null +++ b/wiki/Configure-from-code/index.html @@ -0,0 +1,1407 @@ + + + + + + + + Configure from code - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog can be also configured programmatically.

+

All options match with the attribute names in the XML config, so for all config options you could check https://nlog-project.org/config/

+

There is also a SHFB docs, see https://nlog-project.org/documentation/

+

Fluent API Example

+

NLog 5.0 introduces a Fluent-Configuration-API so you can do this instead:

+
NLog.LogManager.Setup().LoadConfiguration(builder => {
+   builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole();
+   builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: "file.txt");
+});
+
+

Old Style Example

+
var config = new NLog.Config.LoggingConfiguration();
+
+// Targets where to log to: File and Console
+var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
+var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
+
+// Rules for mapping loggers to targets            
+config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
+config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
+
+// Apply config           
+NLog.LogManager.Configuration = config;
+
+

Extended Features

+

Passing Custom Values

+

There are many ways to capture current Context and output it to the final target. Simple example:

+
logger.Info("Message with {myProperty}", "myValue");
+
+

Render with ${event-properties:myProperty}

+

Add this to Layout, e.g.

+
var fileTarget = new FileTarget("target2")
+{
+    FileName = "${basedir}/file.txt",
+    Layout = "${longdate} ${level} ${message}  ${exception} ${event-properties:myProperty}"
+};
+
+

For many more examples, see ${event-properties} layout renderer.

+

Creating dynamic Layouts

+

NLog Layout will implicitly convert from string-objects. It will automatically parse the string and compile it into the recognized Layout-Renderers.

+

NLog will perform validation when parsing, but errors detected will be swallowed unless having enabled LogManager.ThrowConfigExceptions. But one can also force NLog to throw parsing error no matter what:

+
var layout = NLog.Layouts.Layout.FromString("${evil}", throwConfigExceptions: true); // will throw
+
+

NLog 4.7 also allows you to generate a Layout from a simple lambda-method:

+
var unixTime = NLog.Layouts.Layout.FromMethod(logEvent => ((DateTimeOffset)logEvent.TimeStamp).ToUnixTimeSeconds().ToString());
+var jsonLayout = NLog.Layouts.JsonLayout()
+{
+    Attributes = { new NLog.Layouts.JsonAttribute("unixtime", unixTime) { Encode = false } }
+};
+
+

!! NOTICE !! Ensure that custom method given to Layout.FromMethod is very simple. Deadlock or StackOverflow can occur if performing complex logic that triggers new logevents or acquiring locks.

+

Update config in code

+

It is possible to dive into the NLog LoggingConfiguration and assign properties directly. But NLog is much happier about using NLog Layout logic when possible. Example:

+
<target type="file" name="logfile" filename="${gdc:CompanyName:whenEmpty=Default}_${shortdate}.log" />
+
+

Then in code one can just update the GDC-item, and it will take effect right away:

+
NLog.GlobalDiagnosticsContext.Set("CompanyName", "SuperPower");
+
+

This removes the need to know the exact NLog-target names in the NLog.config, so it decouples the logic even further and makes it more resilient. This will also work excellent together with autoReload="true", as you don't have to re-apply the same settings again, as it will happen automatically. This can also be used for adjusting logging rules dynamically at runtime.

+

But if you really want to get your hands dirty, then here you go:

+
var configuration = LogManager.Configuration;
+
+// Update single target
+var myFileTarget = configuration.FindTargetByName<FileTarget>("myTargetName");
+if (myFileTarget != null)
+    myFileTarget.FileName = "SuperPower" + "_${shortdate}.log";
+LogManager.Configuration = configuration; // re-init
+
+// Update all targets
+foreach (var fileTarget = configuration.AllTargets.OfType<FileTarget>())
+{
+   fileTarget.FileName = "SuperPower" + "_${shortdate}.log";
+}
+LogManager.Configuration = configuration; // re-init
+
+

Combine nlog.config and config from code

+

Please note that combining the config file (nlog.config) and changing it in code, the reload of nlog.config could undo your changes. If you combine both, then reapply the changes on the reload event. E.g.

+
// On start of your program
+UpdateConfig();
+
+LogManager.ConfigurationChanged += (sender, e) =>
+{
+    if (e.ActivatedConfiguration != null)
+    {
+        //Re apply if config reloaded
+        UpdateConfig();
+    }
+};
+
+

Where UpdateConfig is

+
public void UpdateConfig()
+{
+     // Do NOT set LogManager.Configuration because that will cause recursion and stackoverflow
+    var fileTarget = LogManager.Configuration.FindTargetByName<FileTarget>("myTargetName");
+    fileTarget.FileName = "${basedir}/file.log";
+    LogManager.ReconfigExistingLoggers(); // Soft refresh
+}
+
+

Instead of trying to perform patching of NLog-configuration, then it is recommended to make use of NLog Layouts for Target- and LoggingRule-configuration forexample using ${gdc}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Console-target/index.html b/wiki/Console-target/index.html new file mode 100644 index 000000000..c57062b92 --- /dev/null +++ b/wiki/Console-target/index.html @@ -0,0 +1,1375 @@ + + + + + + + + Console target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to the console.

+
+

Platforms Supported: All

+
+

There is also the colorful ColoredConsole-Target that can highlight single words or color entire rows.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Console"
+          name="String"
+          layout="Layout"
+          footer="Layout"
+          header="Layout"
+          encoding="Encoding"
+          stderr="Boolean"
+          detectConsoleAvailable="Boolean"
+          writeBuffer="Boolean" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
  • +
  • footer - Footer. Layout
  • +
  • header - Header. Layout
  • +
+

Console Options

+
    +
  • +

    encoding - File encoding name like "utf-8", "ascii" or "utf-16". See Encoding class on MSDN. Defaults to Encoding.Default.

    +
    +

    Introduced in NLog 4.0.

    +
    +
  • +
  • +

    StdErr - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). Layout Default: false

    +
    +

    Before NLog v5.0 the property was named error. +Before NLog v6.0 the property was boolean instead of NLog Layout

    +
    +
  • +
  • +

    detectConsoleAvailable - Indicates whether the console target should disable itself when no console detected. Boolean Default: false

    +
    +

    Introduced in NLog 4.3.10 with default: true, then NLog 4.4 changed default to false.

    +
    +
  • +
  • +

    autoFlush - Performs explicit flush after every console write. Useful if having redirected to custom console-stream that doesn't has autoflush enabled. Boolean. Default = False.

    +
    +

    Introduced in NLog 4.6.3

    +
    +
  • +
  • +

    ForceWriteLine - Call Console.WriteLine instead of writing directly to buffer using Console.Write. Available if doing console-redirection that requires Console.WriteLine. Default: False.

    +
    +

    Before NLog v6.0 the property was named WriteBuffer which was introduced with v4.6.8.

    +
    +
  • +
+

Example

+
<target name="Console" xsi:type="Console"  layout="${longdate} ${logger} ${level} ${message}"/>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Context/index.html b/wiki/Context/index.html new file mode 100644 index 000000000..a0c677a53 --- /dev/null +++ b/wiki/Context/index.html @@ -0,0 +1,1380 @@ + + + + + + + + Context - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Besides the information included with the log message, then there are several options for capturing additional local context state with the LogEvent:

+
    +
  • ${logger} - Name of the Logger-object used for writing LogEvent.
  • +
  • ${level} - LogEvent Level of importance / severity.
  • +
  • ${exception} - Exception object included with the LogEvent.
  • +
  • ${event-properties} - LogEvent Properties - From Structured logging or explicity added to LogEventInfo.Properties.
  • +
  • ${gdc} - Global Diagnostic Context for application-wide static context assigned at startup.
  • +
  • ${scopeproperty} - Provide context properties for the current thread with async Task-support
    +

    Replaces the legacy ${mdlc} and ${mdc} from before NLog 5.0

    +
    +
  • +
  • ${scopenested} - Provide nested scope details for the current thread with async Task-support
    +

    Replaces the legacy ${ndlc} and ${ndc} from before NLog 5.0

    +
    +
  • +
  • ${activity:TraceId} - Using System.Diagnostics.Activity.Current for OpenTelemetry TraceId / SpanId.
  • +
  • ${aspnet-item} - ASP.NET Item variable from HttpContext.Items dictionary.
  • +
+

More LayoutRenderers

+

LogEvent Properties

+

See Structured logging for more details of using the log-message to inject additional properties:

+
logger.Info("Say hello to {myProperty}", "myValue");
+
+

One can also use the Fluent-Logger-API:

+
logger.ForInfoEvent().Message("Hello").Property("myProperty", "myValue").Log();
+
+

Or explicitly create the LogEvent:

+
var logEvent = LogEventInfo() { Level = LogLevel.Info };
+logEvent.Properties["myProperty"] = "myValue";
+logger.Log(logEvent);
+
+

It is also possible to inject properties into the Logger-object, so they are always added:

+
logger.WithProperty("myProperty", "myValue").Info("Hello"); // NLog 4.6.3+
+
+

LogEvent Properties can be rendered with ${event-properties:item=myProperty}, ${all-event-properties} or JsonLayout.

+

ScopeContext Properties

+

Handles thread context properties for a scope. Ex. assigning RequestId for the method-call-scope:

+
using (NLog.ScopeContext.PushProperty("myRequestId", Guid.NewGuid()))
+{
+   logger.Info("myLogEvent");
+}
+
+

Thread Context Properties can be rendered with ${scopeproperty:item=myRequestId} or JsonLayout with IncludeScopeProperties=true.

+
+

Note when using Microsoft Extension Logging ILogger.BeginScope with NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided properties.

+
+

ScopeContext Nested States

+

Handles thread context naming of a scope. Ex. assigning MethodName for the method-call-scope:

+
using (NLog.ScopeContext.PushNestedState("myMethodName"))
+{
+   logger.Info("myLogEvent");
+}
+
+

Thread Scope names can be rendered with ${scopenested}.

+
+

Note when using Microsoft Extension Logging ILogger.BeginScope with NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided scope-name.

+
+

.NET Core logging

+

When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options:

+
using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("userid", request.UserId) }))
+{
+   _logger.LogDebug("Hello {World}", "Earth"); // Render userId via ${scopeproperty:userid} in target output
+}
+
+

NLog.Extensions.Logging v5.3.7 adds support for using ValueTuple for single scope-property (better performance):

+
using (_logger.BeginScope(("userid", request.UserId)))
+{
+   _logger.LogDebug("Hello {World}", "Earth"); // Render userId via ${scopeproperty:userid} in target output
+}
+
+

Context for Code or HttpContext

+

Need other context from code or from the HttpContext (ASP.NET or ASP.NET Core). You could write a custom layout renderer with a single line, see How to write a custom layout renderer.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/CopyToOutputDirectory.png b/wiki/CopyToOutputDirectory.png new file mode 100644 index 000000000..e1a23ef3e Binary files /dev/null and b/wiki/CopyToOutputDirectory.png differ diff --git a/wiki/Counter-layout-renderer/index.html b/wiki/Counter-layout-renderer/index.html new file mode 100644 index 000000000..17611a114 --- /dev/null +++ b/wiki/Counter-layout-renderer/index.html @@ -0,0 +1,1326 @@ + + + + + + + + Counter layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A counter value (increases on each layout rendering).

+
+

Platforms Supported: All

+
+

Configuration Syntax

+

Starting in NLog v4.0 the sequence options have been changed from String to layout

+
${counter:increment=Integer:sequence=Layout:value=Integer}
+
+

The syntax for versions below NLog v4.0 is:

+
${counter:increment=Integer:sequence=String:value=Integer}
+
+

Parameters

+

Counter Options

+
    +
  • increment - Value to be added to the counter after each layout rendering. Integer Default: 1
  • +
  • sequence - Name of the sequence. Different named sequences can have individual values.
  • +
  • value - Initial value of the counter. Integer Default: 1
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/CsvLayout/index.html b/wiki/CsvLayout/index.html new file mode 100644 index 000000000..91bdb9db9 --- /dev/null +++ b/wiki/CsvLayout/index.html @@ -0,0 +1,1401 @@ + + + + + + + + CsvLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders CSV-formatted events.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target>
+    <layout xsi:type="CsvLayout">
+      <!-- CSV Columns -->
+      <column layout="Layout" name="String"/> <!-- repeated -->
+
+      <!-- CSV Options -->
+      <quoting>Enum</quoting>
+      <quoteChar>String</quoteChar>
+      <withHeader>Boolean</withHeader>
+      <customColumnDelimiter>String</customColumnDelimiter>
+      <delimiter>Enum</delimiter>
+    </layout>
+  </target>
+</targets>
+
+

Parameters

+

Columns

+

Array-collection where each item is represented by <column /> element with the following attributes:
+ * name - Name of the column (Becomes part of the Header for the CSV-output) + * layout - Layout for the column value. Layout Required. + * quoting - Column specific override of the default column quoting (Ex. for column with multiline exception-output) + > Introduced with NLog 4.6

+

CSV Options

+
    +
  • quoting - Default Quoting mode for columns to ensure valid CSV output. Default: Auto
    +Possible values:
  • +
  • Auto - Only add quotes when detecting value contains the quote symbol, the separator or newlines (Slow)
  • +
  • All - Add quotes for all values. Useful for data known to be multiline such as Exception-ToString (Fast)
  • +
  • +

    Nothing - Quote nothing, but make sure not to include newlines or quote-delimiter in output (Very Fast)

    +
  • +
  • +

    quoteChar - Quote Character. Default: "

    +
  • +
  • +

    withHeader - Indicates whether CSV should include header. Boolean. Default true

    +
  • +
  • +

    customColumnDelimiter - Custom column delimiter value (valid when delimiter is set to Custom).

    +
  • +
  • +

    delimiter - Column delimiter. Default: Auto
    +Possible values:

    +
  • +
  • Auto - Automatically detect from regional settings.
  • +
  • Comma - Comma , character (ASCII 44).
  • +
  • Custom - Custom string, specified by the CustomColumnDelimiter.
  • +
  • Pipe - Pipe | character (ASCII 124).
  • +
  • Semicolon - Semicolon ; character (ASCII 59).
  • +
  • Space - Space character (ASCII 32).
  • +
  • Tab - Tab character (ASCII 9).
  • +
+

Example

+
<target xsi:type="File" name="csvFileExample" fileName="./CsvLogExample.csv">
+    <layout xsi:type="CsvLayout" delimiter="Tab" withHeader="false">
+        <column name="time" layout="${longdate}" />
+        <column name="level" layout="${level:upperCase=true}"/>
+        <column name="message" layout="${message}" />
+        <column name="exception" layout="${exception:format=ToString}"/>
+        <column name="property1" layout="${event-properties:property1}"/>
+    </layout>
+</target>
+
+

Performance

+

NLog 4.6 introduces the ability to override quoting from automatic to the faster Nothing or All. This will skip the overhead of the automatic quoting logic for individual columns.

+

This example shows how to override quoting for individual columns for better performance:

+
    <layout xsi:type="CsvLayout" delimiter="Tab" withHeader="false">
+        <column name="time" layout="${longdate}" quoting="Nothing" />
+        <column name="level" layout="${level:upperCase=true}" quoting="Nothing"/>
+        <column name="message" layout="${message}" quoting="All" />
+        <column name="exception" layout="${exception:format=ToString}" quoting="All"/>
+        <column name="property1" layout="${event-properties:property1}"/>
+    </layout>
+
+

From code

+
Layout = new CsvLayout()
+{
+   Columns =
+   {
+      new CsvColumn("time", "${longdate}"),
+      new CsvColumn("level", "${level:upperCase=true}"),
+      new CsvColumn("message", "${message}"),
+      new CsvColumn("exception", "${exception:format=ToString}"),
+      new CsvColumn("property1", "${event-properties:property1}"),
+   }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/CurrentDir-Layout-Renderer/index.html b/wiki/CurrentDir-Layout-Renderer/index.html new file mode 100644 index 000000000..5dffbeade --- /dev/null +++ b/wiki/CurrentDir-Layout-Renderer/index.html @@ -0,0 +1,1329 @@ + + + + + + + + CurrentDir Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The current working directory of the application.

+
+

Platforms Supported: All

+

Introduced in NLog v4.5.

+

See also ${basedir}, ${specialfolder}, ${processdir}, ${tempdir}

+
+

Configuration Syntax

+

${currentdir:dir=String:file=String}

+

Parameters

+

Advanced Options

+
    +
  • +

    dir: Name of the directory to be Path.Combine()'d with the current directory.

    +
  • +
  • +

    file: Name of the file to be Path.Combine()'d with the current directory.

    +
  • +
+

Notes

+

Applications can change their current directory, so NLog resolves the current directory without caching. If not expecting current directory to be changed, then enabling caching will improve performance: ${currentdir:cached=true}

+

See also: FileTarget FileName Directory

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Custom-extension-of-Logger-interface/index.html b/wiki/Custom-extension-of-Logger-interface/index.html new file mode 100644 index 000000000..aae8c4c45 --- /dev/null +++ b/wiki/Custom-extension-of-Logger-interface/index.html @@ -0,0 +1,1369 @@ + + + + + + + + Custom extension of Logger interface - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Introduction

+

There can be different reasons for extending the NLog logging interface:

+
    +
  • Extend logging interface to automatically add relevant context when logging.
  • +
  • Create an abstract interface to avoid direct NLog dependency in source-code.
  • +
+

Abstract Interface Libraries

+

There already exists several libraries that provides an abstract interface:

+ +

Extended logging interface

+

There are two ways to extend the NLog Logger.

+
    +
  • Inherit from the NLog Logger and add your own custom extensions.
  • +
  • Create a custom wrapper around the NLog Logger and forward the logevents to the NLog Logger.
  • +
+

Custom Wrapper and callsite

+

NLog has a special Callsite feature, that allows it to automatically capture the location in source code that performed the logging. This feature has a huge overhead (logging becomes 20 times slower, together with lots of bonus allocations), because the capture of StackTrace and scanning for source location is expensive.

+

When creating a custom wrapper around the NLog Logger-interface (or extension methods), then the callsite logic will think the custom wrapper is the origin of the log-statement. This can be solved by using Logger.Log(Type wrapperType, LogEventInfo logEvent)-method when writing the LogEvent, and providing the typeof(MyCustomWrapper) as first parameter.

+
public class MyLogger
+{
+   private readonly NLog.Logger Logger;
+
+   public MyLogger(string name)
+   {
+      Logger = NLog.LogManager.GetLogger(name);
+   }
+
+   public void WriteMessage(string message)
+   {
+      NLog.LogEventInfo logEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Info, null, message);
+      Logger.Log(typeof(MyLogger), logEvent);
+   }
+}
+
+

When the custom wrapper provides its own Type as wrapperType, then the callsite logic will not see the custom wrapper as being the origin of the log-statement. If extending the NLog Logger-interface without providing the correct wrapperType, then Callsite will stop working.

+

Note NLog 5.0 adds full support for using Caller Information-attributes that was introduced with .NET 4.5. When having called LogEventInfo.SetCallerInfo(...) then StackTrace capture is not needed for the Callsite feature.

+
public class MyLogger
+{
+   private readonly NLog.Logger Logger;
+
+   public MyLogger(string name)
+   {
+      Logger = NLog.LogManager.GetLogger(name);
+   }
+
+   public void WriteMessage(string message,
+        [CallerMemberName] string callerMemberName = "",
+        [CallerFilePath] string callerFilePath = "",
+        [CallerLineNumber] int callerLineNumber = 0)
+   {
+      NLog.LogEventInfo logEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Info, null, message);
+      logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber);
+      Logger.Log(typeof(MyLogger), logEvent);
+   }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/DB-null-layout-renderer/index.html b/wiki/DB-null-layout-renderer/index.html new file mode 100644 index 000000000..6c30b53ef --- /dev/null +++ b/wiki/DB-null-layout-renderer/index.html @@ -0,0 +1,1317 @@ + + + + + + + + DB null layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

DB null for a database

+
+

Platforms Supported: All

+
+

Introduced in NLog 4.6. Most usefull for the Database target

+

Configuration Syntax

+
${db-null}
+
+

Render a DbNull value for the database parameter

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Data-types/index.html b/wiki/Data-types/index.html new file mode 100644 index 000000000..6ca8c7965 --- /dev/null +++ b/wiki/Data-types/index.html @@ -0,0 +1,1314 @@ + + + + + + + + Data types - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The data types used in NLog

+
    +
  • Layout: The layout created with Layout-Renderers
  • +
  • Boolean: true or false in the XML.
  • +
  • Integer: 4 bytes integral number.
  • +
  • Long: 8 bytes integral number.
  • +
  • Encoding: An encoding name. Possible values are listed in the Name column of the table that appears in the Encoding class topic.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Database-target/index.html b/wiki/Database-target/index.html new file mode 100644 index 000000000..d4d0e215f --- /dev/null +++ b/wiki/Database-target/index.html @@ -0,0 +1,1690 @@ + + + + + + + + Database target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to the database using an ADO.NET provider. The database operation is always executed outside of a transaction.

+
+

Platforms Supported: All - Requires nuget-package NLog.Database since NLog 5.0

+
+

You can use this target with various DB providers, e.g. System.Data, Microsoft.Data, PostgreSQL, Oracle, MySql, SqlLite etc. +see Providers examples

+

ℹ️ Don't forget to install the needed nuget-package for your DB provider!

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Database"
+          name="String"
+          dbProvider="String"
+          connectionString="Layout"
+          connectionStringName="String"
+          keepConnection="Boolean"
+          isolationLevel="System.Data.IsolationLevel"
+          dbDatabase="Layout"
+          dbUserName="Layout"
+          dbPassword="Layout"
+          dbHost="Layout"
+          commandType="Enum"
+          commandText="Layout"
+          installConnectionString="Layout">
+    <install-command commandType="Enum" 
+                     connectionString="Layout" 
+                     ignoreFailures="Boolean"
+                     text="Layout"/><!-- repeated -->
+    <uninstall-command commandType="Enum" 
+                       connectionString="Layout" 
+                       ignoreFailures="Boolean"
+                       text="Layout"/><!-- repeated -->
+    <parameter name="String" 
+              layout="Layout"
+              precision="Byte" 
+              scale="Byte" 
+              size="Integer"
+              dbType="DbType" 
+              allowDbNull="Boolean"
+              format="string" 
+              parameterType="Type" /> <!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Connection Options

+
    +
  • dbProvider - Name of the database provider. Required. Default: sqlserver + Following values are recognized by default:
  • +
  • sqlserver, mssql, microsoft or msde - Resolves to System.Data.SqlClient Data Provider
  • +
  • odbc - ODBC Data Provider (Not recognized on NetCore)
  • +
  • oledb - OLEDB Data Provider (Not recognized on NetCore)
  • +
+

Note for .NET Core one should install the Nuget-package for the DbProvider (Ex. System.Data.SqlClient), and instead use the fully qualified name of the provider connection type (class implementing IDbConnection). See also DbProvider Examples

+

If you get the following error in Internal-Logging then you might have to use the fully qualified name.

+

Error during initialization of DatabaseTarget(Name=db). Could not load type '<Name Of DbProvider>' from assembly

+
    +
  • +

    connectionString - Connection string. When provided, it overrides the values specified in DBHost, DBUserName, DBPassword, DBDatabase and DBProvider. Layout

    +
  • +
  • +

    connectionStringName - Name of the connection string to lookup in app.config. The ProviderName of the connectionstring will be used to determine the SQL type. Since NLog 4.3 this ProviderName attribute isn't required anymore and the dbProvider will be used as fallback.

    +
    +

    Not supported on NetCore as app.config has been replaced with appsettings.json. Use ${configsetting} in connectionString instead

    +
    +
  • +
  • +

    keepConnection - Indicates whether to keep the database connection open between the log events. Boolean Default: false

    +
  • +
  • +

    isolationLevel - Activates transactions where multiple rows are written in a single transaction. This can improve performance when using batching (Ex. <targets async="true">). Recommended to assign ReadCommitted for enabling transactional writing. Consider adding ;ENLIST=FALSE to ConnectionString to disable auto-enlist. Default: Not set

    +
    +

    Introduced with NLog 4.7

    +
    +
  • +
  • +

    dbDatabase - Database name. If the ConnectionString is not provided this value will be used to construct the "Database=" part of the connection string. Layout

    +
  • +
  • +

    dbUserName - Database user name. If the ConnectionString is not provided this value will be used to construct the "User ID=" part of the connection string. Layout

    +
  • +
  • +

    dbPassword - Database password. If the ConnectionString is not provided this value will be used to construct the "Password=" part of the connection string. Layout

    +
  • +
  • +

    dbHost - Database host name. If the ConnectionString is not provided this value will be used to construct the "Server=" part of the connection string. Layout

    +
  • +
  • +

    useTransactions - This option was removed in NLog 4.0 because the logging code always runs outside of transaction. This ensures that the log gets written to the database if you rollback the main transaction because of an error and want to log the error.

    +
  • +
+

SQL Statement

+
    +
  • commandType - Type of the command. Required. Default: text
    + Possible values:
      +
    • StoredProcedure - The commandText is the stored procedure name.
    • +
    • TableDirect -
    • +
    • Text - regular query
    • +
    +
  • +
  • +

    commandText - Text of the SQL command to be run on each log level. Layout Required.
    +Typically this is a SQL INSERT statement or a stored procedure call. It should use the database-specific parameters (marked as @parameter for SQL server or :parameter for Oracle, other data providers have their own notation) and not the layout renderers, because the latter is prone to SQL injection attacks. The layout renderers should be specified as \ elements instead.

    +
  • +
  • +

    parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection +Each collection item is represented by \ element with the following attributes:

    +
  • +
  • layout - Layout that should be use to calcuate the value for the parameter. Layout Required. Note: there is also ${db-null}
  • +
  • name - Database parameter name. Required.
  • +
  • precision - Database parameter precision. Byte Default: 0
  • +
  • scale - Database parameter scale. Byte Default: 0
  • +
  • size - Database parameter size. Integer Default: 0
  • +
  • dbType - One of the values of DbType (e.g. "Int32", "Decimal", "DateTime"), + or a value of DBType like prefixed with the property name, e.g. "SqlDbType.NChar" will set the property "SqlDbType" on "NChar". + Another example: "NpgsqlDbType.Json" with NpgsqlParameter. + Introduced in NLog 4.6. Since NLog 4.7 not case-sensitive any more
  • +
  • parameterType - Optional parametertype (System.Type), Will be automatically mapped for common DbType-values. When using special DbType like SqlDbType.SmallInt, then one can specify parameterType="System.Int16" to help - This will skip the overhead of first rendering to string, and parsing the string into the expected type. Introduced in NLog 4.6
  • +
  • format - format for parsing the value when not using the rawValue, of if the rawValue conversion to has been failed. Introduced in NLog 4.6
  • +
  • culture - culture for parsing the value, analogous as "format". Introduced in NLog 4.6
  • +
  • allowDbNull - empty value will be translate into DbNull. Requires database column to allow NULL values. Introduced in NLog 4.7.4. Empty values are null for nullable types and null and '' for strings.
  • +
+

Installation Options

+

See Installing targets.

+
    +
  • installConnectionString - Connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. Layout
  • +
  • InstallDdlCommands - The installation DDL commands. Collection . +Each collection item is represented by \ element with the following attributes:
  • +
  • commandType - Type of the command. Required. Default: text
    + Possible values:
      +
    • StoredProcedure - The command-text is the stored procedure name.
    • +
    • TableDirect -
    • +
    • Text - regular query
    • +
    +
  • +
  • Text - The command-text (Or stored procedure name)
  • +
  • parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection
    +Each collection item is represented by element with the following attributes:
      +
    • layout - Layout that should be use to calcuate the value for the parameter. Layout Required.
    • +
    • name - Database parameter name. Required.
    • +
    • precision - Database parameter precision. Byte Default: 0
    • +
    • scale - Database parameter scale. Byte Default: 0
    • +
    • size - Database parameter size. Integer Default: 0
    • +
    • text - Command text. Layout Required.
    • +
    +
  • +
  • connectionString - Connection string to run the command against. If not provided, connection string from the target is used. Layout
  • +
  • ignoreFailures - Indicates whether to ignore failures. Boolean
  • +
  • uninstallDdlCommands - The uninstallation DDL commands. Collection
    +Each collection item is represented by \ element with the following attributes:
  • +
  • commandType - Type of the command. Required. Default: text
    + Possible values:
      +
    • StoredProcedure - The command-text is the stored procedure name.
    • +
    • TableDirect -
    • +
    • Text - regular query
    • +
    +
  • +
  • Text - The command-text (Or stored procedure name)
  • +
  • parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection
    +Each collection item is represented by \ element with the following attributes:
      +
    • layout - Layout that should be use to calcuate the value for the parameter. Layout Required.
    • +
    • name - Database parameter name. Required.
    • +
    • precision - Database parameter precision. Byte Default: 0
    • +
    • scale - Database parameter scale. Byte Default: 0
    • +
    • size - Database parameter size. Integer Default: 0
    • +
    • text - Command text. Layout Required.
    • +
    +
  • +
  • connectionString - Connection string to run the command against. If not provided, connection string from the target is used. Layout
  • +
  • ignoreFailures - Indicates whether to ignore failures. Boolean
  • +
+

Command and connection properties

+

Introduced in NLog 4.7, you could add properties to the connection (e.g. SqlConnection, OracleConnection) and the Command (e.g. SqlCommand, OracleCommand). this could be useful for the Azure Access Token

+

Examples

+
<commandProperty name="CommandTimeout" layout="${gdc:DefaultCommandTimeout}" propertyType="System.Int32" />
+<connectionProperty name="AccessToken" layout="${gdc:AccessToken}" propertyType="System.String" />
+
+

Full example:

+
<target name="db"
+        xsi:type="Database"
+        commandType="StoredProcedure"
+        commandText="[dbo].[NLog_AddEntry_p]"
+        >
+  <commandProperty name="CommandTimeout" layout="${gdc:DefaultCommandTimeout}" propertyType="System.Int32" />
+  <connectionProperty name="AccessToken" layout="${gdc:AccessToken}" propertyType="System.String" /> 
+  <parameter name="@logged"         layout="${date}" />
+  <parameter name="@level"          layout="${level}" />
+  <parameter name="@message"        layout="${message}" />
+  <parameter name="@logger"         layout="${logger}" />
+</target>
+
+

About DbType and IRawValue

+

The DbType works as follows +- NLog tries first if the Layout Renderer support IRawValue to get the non-string type. Then it will use the IPropertyTypeConverter for converting to the desired dbType. +- If that fails, NLog will render the layout render to string and then parse it (with usage of the optional format option). Then it will also use the IPropertyTypeConverter for converting to the desired dbType. +- NoRawValue layout renderer could be use for forcing to use the string value.

+

About allowDbNull example

+

Where null and empty string-value is converted to DbNull-value:

+
<parameter name="@activityid" layout="${activityid}" dbType="DbType.Guid" allowDbNull="true" />
+
+

Example Configurations

+

NLog and SQL Server Example Configuration

+
<target name="database" xsi:type="Database">
+  <connectionString>server=localhost;Database=*****;user id=****;password=*****</connectionString>
+
+  <!--
+  Script for creating the dbo.Log table.
+
+  SET ANSI_NULLS ON
+  SET QUOTED_IDENTIFIER ON
+  CREATE TABLE [dbo].[Log] (
+      [Id] [int] IDENTITY(1,1) NOT NULL,
+      [MachineName] [nvarchar](50) NOT NULL,
+      [Logged] [datetime] NOT NULL,
+      [Level] [nvarchar](50) NOT NULL,
+      [Message] [nvarchar](max) NOT NULL,
+      [Logger] [nvarchar](250) NULL,
+      [Exception] [nvarchar](max) NULL,
+    CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)
+      WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
+  ) ON [PRIMARY]
+  -->
+
+  <commandText>
+    insert into dbo.Log (
+      MachineName, Logged, Level, Message,
+      Logger, Exception
+    ) values (
+      @MachineName, @Logged, @Level, @Message,
+      @Logger, @Exception
+    );
+  </commandText>
+
+  <parameter name="@MachineName" layout="${machinename}" />
+  <parameter name="@Logged" layout="${date}" />
+  <parameter name="@Level" layout="${level}" />
+  <parameter name="@Message" layout="${message}" />
+  <parameter name="@Logger" layout="${logger}" />
+  <parameter name="@Exception" layout="${exception:tostring}" />
+</target>
+
+

NLog and SQL Server using a stored procedure

+

This approach keeps the NLog.config file simpler, and helps confine +database logic to the database.

+

NLog target configuration

+
<target name="db"
+        xsi:type="Database"
+        connectionString="server=localhost;Database=*****;user id=****;password=*****"
+        commandType="StoredProcedure"
+        commandText="[dbo].[NLog_AddEntry_p]"
+        >
+  <parameter name="@machineName"    layout="${machinename}" />
+  <parameter name="@logged"         layout="${date}" />
+  <parameter name="@level"          layout="${level}" />
+  <parameter name="@message"        layout="${message}" />
+  <parameter name="@logger"         layout="${logger}" />
+  <parameter name="@properties"     layout="${all-event-properties:separator=|}" />
+  <parameter name="@exception"      layout="${exception:tostring}" />
+</target>
+
+

SQL scripts to set up the database objects

+

Remember to grant permissions on the database objects so that the website can execute the stored procedure.

+
CREATE TABLE [dbo].[NLog] (
+   [ID] [int] IDENTITY(1,1) NOT NULL,
+   [MachineName] [nvarchar](200) NULL,
+   [Logged] [datetime] NOT NULL,
+   [Level] [varchar](5) NOT NULL,
+   [Message] [nvarchar](max) NOT NULL,
+   [Logger] [nvarchar](300) NULL,
+   [Properties] [nvarchar](max) NULL,
+   [Exception] [nvarchar](max) NULL,
+ CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([ID] ASC) 
+   WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];
+
+GO
+
+CREATE PROCEDURE [dbo].[NLog_AddEntry_p] (
+  @machineName nvarchar(200),
+  @logged datetime,
+  @level varchar(5),
+  @message nvarchar(max),
+  @logger nvarchar(300),
+  @properties nvarchar(max),
+  @exception nvarchar(max)
+) AS
+BEGIN
+  INSERT INTO [dbo].[NLog] (
+    [MachineName],
+    [Logged],
+    [Level],
+    [Message],
+    [Logger],
+    [Properties],
+    [Exception]
+  ) VALUES (
+    @machineName,
+    @logged,
+    @level,
+    @message,
+    @logger,
+    @properties,
+    @exception
+  );
+END
+
+

Example: log with custom properties, not all in the message

+

This combines structured logging and WithProperty. You need at least NLog 4.6.3 for this.

+

Logger call:

+
logger.WithProperty("Property2", "value2")
+      .Info("my info message {Property1}", "value1");
+
+
+

config:

+
<target name="apiUsageLog" xsi:type="Database" connectionStringName="connStringName">
+    <commandText>
+        INSERT INTO Table
+        (message, machinename, property1, property2)
+        VALUES
+        (@message, @machinenameParam, @propertyParam2)
+    </commandText>
+    <parameter name="@messageParam" layout="${message}" /> <!-- this will be: my info message with "value1"-->
+    <parameter name="@machinenameParam" layout="${machinename}" /> <!-- defined in NLog, see https://nlog-project.org/config/?tab=layout-renderers-->
+    <parameter name="@propertyParam1" layout="${event-properties:Property1}" /> <!-- this will be "value1" -->
+    <parameter name="@propertyParam2" layout="${event-properties:Property2}" /> <!-- this will be "value2" -->
+    </target>
+</targets>
+
+

This will create a log record in the database with my info message with "Value1" , the machine name and the custom properties "value1" and "value2"

+

Note, now "value1" is in the message and "value2" isn't.

+

AOT Example

+

AOT-builds does not support usage of DbProvider-option for doing type-reflection, instead one can create instance of DatabaseTarget with DbConnectionFactory-delegate:

+
var databaseTarget = new NLog.Targets.DatabaseTarget(() => new Npgsql.NpgsqlConnection());
+NLog.LogManager.Setup().LoadConfiguration(cfg => cfg.ForLogger().WriteTo(databaseTarget));
+
+

For Database-Parameters then one can use DbTypeEnum-property, and if needing custom DbType, then one can create instance of DatabaseParameterInfo with delegate:

+
var databaseParameter = new DatabaseParameterInfo("@context",
+    "${all-event-properties}",
+    (p) => ((NpgsqlParameter)p).NpgsqlDbType = NpgsqlDbType.VarChar);
+databaseTarget.Parameters.Add(databaseParameter);
+
+

DbProvider Examples

+

Microsoft.Data.SqlClient

+

Install package: https://www.nuget.org/packages/Microsoft.Data.SqlClient/

+
dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"
+
+

MySql

+

Install package: https://www.nuget.org/packages/MySql.Data/

+
dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data"
+
+

or if using packages: https://www.nuget.org/packages/MySqlConnector/ and https://www.nuget.org/packages/MySqlConnector.Logging.NLog/

+
dbProvider="MySqlConnector.MySqlConnection, MySqlConnector"
+
+

System.Data.SQLite

+

Install package: https://www.nuget.org/packages/System.Data.SQLite

+
dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
+
+

Microsoft.Data.Sqlite

+

Install package: https://www.nuget.org/packages/Microsoft.Data.SQLite/

+
dbProvider="Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"
+
+

PostgreSQL Npgsql

+

Install package: https://www.nuget.org/packages/Npgsql/

+
dbProvider="Npgsql.NpgsqlConnection, Npgsql"
+
+

Oracle.ManagedDataAccess

+
dbProvider="Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess"
+
+

Mono.Data.Sqlite and .NET

+
dbProvider="Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite"
+
+

Microsoft Access

+
    <target xsi:type="Database"
+            name="MdbLog"
+            dbProvider="oledb"
+            connectionString="Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\path\to\my.mdb">
+    ...
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Date-layout-renderer/index.html b/wiki/Date-layout-renderer/index.html new file mode 100644 index 000000000..bf7149e37 --- /dev/null +++ b/wiki/Date-layout-renderer/index.html @@ -0,0 +1,1333 @@ + + + + + + + + Date layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Current date and time.

+
+

Platforms Supported: All

+

Alternative ${longdate} or ${shortdate} can be used for high performance timestamp-logging.

+
+

Configuration Syntax

+
${date:universalTime=Boolean:format=String:culture=Culture}
+
+

Parameters

+

Rendering Options

+
    +
  • universalTime - Indicates whether to output UTC time instead of local time.Boolean Default: False
  • +
  • format - Date format. Can be any argument accepted by DateTime.ToString(format).
    +

    Note that colons need to escaped with a backslash: \ + Example: ${date:format=yyyy-MM-dd HH\:mm\:ss.fff} -> DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") -> "2000-01-01 00:00:00.000"

    +
    +
  • +
+
+

Note that backslashes, that shall be passed through, also need to be escaped: \ + Example: ${date:format=\\Yyyyy\\MMM\\Ddd} -> DateTime.Now.ToString(@"\Yyyyy\MMM\Ddd") -> Y2000M01D01" +* culture - Culture used for rendering. Default: InvariantCulture

+
+

Time Source Precision

+

NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount. For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Debug-target/index.html b/wiki/Debug-target/index.html new file mode 100644 index 000000000..b4f1891b7 --- /dev/null +++ b/wiki/Debug-target/index.html @@ -0,0 +1,1345 @@ + + + + + + + + Debug target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Mock target for unit-testing. If looking for output to System.Diagnostics.Debug then use DebugSystem-target.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="Debug" name="String" layout="Layout" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
  • +
+

Examples

+

Logging to Debug Target

+

(snippet from Debug Simple Example.cs )

+
        NLog.Targets.DebugTarget target = new NLog.Targets.DebugTarget() { Name = "Debug" };
+        target.Layout = "${message}";
+
+        NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
+        config.AddRuleForAllLevels(target)
+        NLog.LogManager.Configuration = config;
+
+        NLog.Logger logger = NLog.LogManager.GetLogger("Example");
+        logger.Debug("log message");
+        logger.Debug("another log message");
+
+        Console.WriteLine("The debug target has been hit {0} times.", target.Counter);
+        Console.WriteLine("The last message was '{0}'.", target.LastMessage);
+
+

Some examples of DebugTarget use can be found in unit tests

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/DebugSystem-target/index.html b/wiki/DebugSystem-target/index.html new file mode 100644 index 000000000..176d1f0bf --- /dev/null +++ b/wiki/DebugSystem-target/index.html @@ -0,0 +1,1333 @@ + + + + + + + + DebugSystem target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages through System.Diagnostics.Debug.WriteLine

+
+

Platforms Supported: All (Introduced with NLog 5.0)

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="DebugSystem" name="String" layout="Layout" />
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Output Options

+
    +
  • layout - Layout used to format log messages. Layout Required
  • +
  • header - Layout used to format header-output when initializing. Layout
  • +
  • footer - Layout used to format footer-output when closing. Layout
  • +
+

Notes

+

Alternative targets for diagnostic output: +- Trace-target for output to System.Diagnostics.Trace +- Debugger-target for output to System.Diagnostics.Debugger.Log +- OutputDebugString-target for output to OutputDebugString Win32 API

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Debugger-target/index.html b/wiki/Debugger-target/index.html new file mode 100644 index 000000000..f95e16501 --- /dev/null +++ b/wiki/Debugger-target/index.html @@ -0,0 +1,1355 @@ + + + + + + + + Debugger target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to the attached managed debugger (Ex. Visual Studio Output Window). See also System.Diagnostics.Debugger.Log

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="Debugger" name="String" layout="Layout" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+
    +
  • name - Name of the target.
  • +
  • layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
  • +
  • header - Layout used to format header-output when initializing.
  • +
  • footer - Layout used to format footer-output when closing.
  • +
  • Category - Layout used to format the category. Default: ${logger}
    +

    Introduced with NLog v6.1

    +
    +
  • +
  • MaxMessageSize - Max message length in characters before applying OnOverflow-action (0 means unlimited) . Default: 0.
    +

    Introduced with NLog v6.1

    +
    +
  • +
  • OnOverflow - Action to perform when max message size is exceeded. Default: Split
    +

    Introduced with NLog v6.1

    +
    +
  • +
  • Truncate - Truncate the message to fit.
  • +
  • Split - Split the big message into multiple log messages.
  • +
  • Discard - Discard the entire message.
  • +
+

Examples

+

From stackoverflow

+
<targets>
+  <target name="debugger" xsi:type="Debugger" layout="${level}|${message:withException=true}"/>
+</targets>
+
+<rules>
+  <logger name="*" minlevel="Trace" writeTo="debugger" />
+</rules>
+
+

Notes

+

Alternative targets for diagnostic output: +- Trace-target for output to System.Diagnostics.Trace +- DebugSystem-target for output to System.Diagnostics.Debug +- OutputDebugString-target for output to OutputDebugString Win32 API

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Dependency-injection-with-NLog/index.html b/wiki/Dependency-injection-with-NLog/index.html new file mode 100644 index 000000000..fdfb27a93 --- /dev/null +++ b/wiki/Dependency-injection-with-NLog/index.html @@ -0,0 +1,1357 @@ + + + + + + + + Dependency injection with NLog - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Resolve Dependency Injection Interface during initialization

+

NLog 5.0 makes it possible to resolve interfaces using dependency injection during initialization. This allows you to load targets using NLog config file, before dependency injection provider is available.

+

The custom NLog target can then override InitializeTarget to resolve the necessary dependencies:

+
protected override void InitializeTarget()
+{
+   var wantedDependency = base.ResolveService<IWantedDependency>();
+   base.InitializeTarget();
+}
+
+

If the custom NLog target requests a dependency, that is unavailable, then NLog will perform re-initialization of the NLog when the dependency becomes available. Service interfaces can registered like this:

+
NLog.LogManager.Setup().SetupExtensions(ext => RegisterSingletonService<IWantedDependency>(wantedInstance));
+
+

It is also possible to connect with an external IServiceProvider for resolving dependencies:

+
NLog.LogManager.Setup().SetupExtensions(ext => RegisterServiceProvider(serviceProvider));
+
+

It is recommended to setup dependency-injection early before loading the NLog LoggingConfiguration, or else they might not take effect.

+

Resolve Dependency Injection Interface during object creation

+

NLog v5.2 introduces the ability to register extensions together with custom factory-method:

+
NLog.LogManager.Setup().SetupExtensions(ext => RegisterTarget<MyTarget>(() => new MyTarget(wantedDependency));
+
+
+

⚠️ NLog v5.2 has marked ConfigurationItemFactory.CreateInstance as obsolete, as it doesn't work well with Ahead-of-Time (AOT) application trimming in .NET

+
+

NLog will by default use the default constructor for creating new objects. It is possible to override the creation by using ConfigurationItemFactory.CreateInstance. Example:

+
using NLog.Config;
+
+var defaultConstructor = ConfigurationItemFactory.Default.CreateInstance;
+
+ConfigurationItemFactory.Default.CreateInstance.CreateInstance = type =>
+{
+   if (type == typeof(MyCustomTarget))
+       return new MyCustomTarget(myCustomParameter);
+
+   return defaultConstructor(type);
+};
+
+

NLog will only be able to create objects of known types. To support custom objects one must also register the config-item-type before it will be recognized. See also Register your custom component

+

Initialize NLog configuration with Dependency Injection Provider

+

The combination of dynamic logging configuration and dependency injection can give a catch22. You want to have logging up and running early, but this will fail if dependent on custom objects that requires a dependency injection provider is fully loaded.

+

The "ugly" work-around to this catch22 is to have two constructors for your custom-objects: +- Default Constructor that initializes an object in disabled state (Ignored by dependency injection provider). +- Specialized Constructor that initializes an object in working state.

+

Alternative override the CreateInstance-method as first thing (Before creating first Logger-object or loading NLog config). Where it calls the specialized constructor with parameters that signals that it should be in disabled state.

+

Then one can "just" perform a reload of the NLog config, after the dependency injection provider has been fully loaded and performed final override of CreateInstance. This will make NLog recreate all configuration items once again, and now with a working dependency injection provider that calls the specialized constructor with correct parameters.

+
using NLog;
+
+LogManager.Configuration = LogManager.Configuration.Reload();
+
+

See also Reinitialize NLog configuration

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Directory-separator/index.html b/wiki/Directory-separator/index.html new file mode 100644 index 000000000..da3e87247 --- /dev/null +++ b/wiki/Directory-separator/index.html @@ -0,0 +1,1318 @@ + + + + + + + + Directory separator - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Renders the OS dependent directory separator

+

Introduced in NLog 4.7

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${dir-separator}
+
+

Remarks

+

Same result as Path.DirectorySeparatorChar

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/DocumentUri-layout-renderer/index.html b/wiki/DocumentUri-layout-renderer/index.html new file mode 100644 index 000000000..0d7c0d72c --- /dev/null +++ b/wiki/DocumentUri-layout-renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + DocumentUri layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

URI of the HTML page which hosts the current Silverlight application.

+
+

Supported in Silverlight (NLog 5.0 does not support Silverlight)

+
+

Configuration Syntax

+
${document-uri}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Elmah-target/index.html b/wiki/Elmah-target/index.html new file mode 100644 index 000000000..0a9c86cbf --- /dev/null +++ b/wiki/Elmah-target/index.html @@ -0,0 +1,1307 @@ + + + + + + + + Elmah target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ + + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Environment-User-Layout-Renderer/index.html b/wiki/Environment-User-Layout-Renderer/index.html new file mode 100644 index 000000000..28dde96ba --- /dev/null +++ b/wiki/Environment-User-Layout-Renderer/index.html @@ -0,0 +1,1339 @@ + + + + + + + + Environment User Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Thread User identity information (username).

+
+

Platforms Supported: All

+

Introduced with NLog ver. 4.6.4

+
+

Configuration Syntax

+
${environment-user:userName=Boolean:domain=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • userName - Indicates whether username should be included. Boolean Default: True
  • +
  • domain - Indicates whether domain name should be included. Boolean Default: False
  • +
  • DefaultUser - Fallback value if unable to lookup username
  • +
  • DefaultDomain - Fallback value if unable to lookup domain
  • +
+

Notes

+
    +
  • +

    On Windows the Environment.UserName property wraps a call to the Windows GetUserName function.

    +
  • +
  • +

    On Unix platforms the UserName property wraps a call to the getpwuid_r function.

    +
  • +
  • +

    If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user. In a published ASP.NET application, this property returns the name of the application pool account (such as Default AppPool).

    +
  • +
+

Alternative one can use ${windows-identity} that depends on WindowsIdentity.Getcurrent()

+

Another alternative is ${identity} that depends on Thread.CurrentPrincipal.

+

Yet another alternative is ${aspnet-user-identity} but it only works on ASP.NET Applications with identity enabled.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Environment-layout-renderer/index.html b/wiki/Environment-layout-renderer/index.html new file mode 100644 index 000000000..8b5974f83 --- /dev/null +++ b/wiki/Environment-layout-renderer/index.html @@ -0,0 +1,1342 @@ + + + + + + + + Environment layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The environment variable like USERNAME, TMP, USERPROFILE, COMPUTERNAME, PROCESSOR_ARCHITECTURE etc.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${environment:variable=String}
+
+

Parameters

+

Rendering Options

+
    +
  • variable - Name of the environment variable. Required. Examples: USERNAME, TMP, USERPROFILE, COMPUTERNAME, PROCESSOR_ARCHITECTURE etc.
  • +
+

Remarks

+
    +
  • +

    For better performance then consider to combine with cached=true. Thus only resolving environment-variable value only once, but then not react to any changes of the environment variable.

    +
  • +
  • +

    This Layout Renderer outputs environment variables, and NOT properties from System.Environment

    +
  • +
  • +

    To list all environment variables in your system:

    +
  • +
  • Open Command Prompt (cmd) and execute the command set
  • +
  • Open PowerShell and execute the command dir env:
  • +
  • System.Environment.GetEnvironmentVariables()
  • +
+

Example

+

log file for 32 bits systems in folder 32 and otherwise in folder 64

+
<target 
+   xsi:type="File"
+   name="file1" 
+   fileName="c:\temp\${when:when='${environment:PROCESSOR_ARCHITECTURE:cached=true}'='X86':inner=32:else=64}\file.log" />
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Environment-specific-NLog-Logging-Configuration/index.html b/wiki/Environment-specific-NLog-Logging-Configuration/index.html new file mode 100644 index 000000000..551232142 --- /dev/null +++ b/wiki/Environment-specific-NLog-Logging-Configuration/index.html @@ -0,0 +1,1378 @@ + + + + + + + + Environment specific NLog Logging Configuration - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

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 (As part of application installation).

+

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

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Event-Context-Layout-Renderer/index.html b/wiki/Event-Context-Layout-Renderer/index.html new file mode 100644 index 000000000..41d52b9cb --- /dev/null +++ b/wiki/Event-Context-Layout-Renderer/index.html @@ -0,0 +1,1336 @@ + + + + + + + + Event Context Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Log event property data.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${event-properties:item=MyValue}
+
+

Note that ${event-properties} syntax replaces the now deprecated ${event-context} syntax.

+

Parameters

+

Rendering Options

+
    +
  • item - Name of the item (required)
  • +
+

Example

+

In your C# code, create an event and add an element to the Properties dictionary (or the deprecated Context dictionary):

+
...
+Logger log = LogManager.GetCurrentClassLogger();
+LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", "Pass my custom value");
+theEvent.Properties["MyValue"] = "My custom string";
+// deprecated
+theEvent.Context["TheAnswer"] = 42;
+log.Log(theEvent);
+...
+
+

And in your NLog.config file:

+
${event-properties:item=MyValue}   -- renders "My custom string"
+${event-properties:item=TheAnswer} -- renders "42"
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/EventProperties-Layout-Renderer/index.html b/wiki/EventProperties-Layout-Renderer/index.html new file mode 100644 index 000000000..8038420e9 --- /dev/null +++ b/wiki/EventProperties-Layout-Renderer/index.html @@ -0,0 +1,1401 @@ + + + + + + + + EventProperties Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Log event properties data.

+

This has the same implementation as ${event-context}, but the latter is deprecated.

+
+

Platforms Supported: All

+
+

To log all properties, use ${all-event-properties}. See also NLog Context.

+

Configuration Syntax

+
${event-properties:item=String:culture=String:format=String:objectpath=String}
+
+

Parameters

+
    +
  • item - Name of the item. Required.
  • +
  • ignoreCase - Name lookup should be case-insensitive. Default true. Introduced in NLog 5.0
  • +
  • objectpath - property path if the value is an object. Nested properties are supported. Examples: Id, Details.Title. Introduced in NLog 4.6.3
  • +
+

Rendering Options

+
    +
  • culture - The culture used for rendering. Introduced in NLog 4.1. Default value is CultureInfo.InvariantCulture
  • +
  • format - Format for conversion from object to string. Introduced in NLog 4.1.
  • +
  • format=@ means serialize object properties into Json-format. Introduced in NLog 4.5.
  • +
+

Example

+

Structured logging Properties

+

NLog 4.5+

+
logger.Info("Order {orderid} created for {user}", 42, "Kenny");
+
+

and in your NLog.config file:

+
${event-properties:item=orderId} -- renders "42"
+${event-properties:item=user} -- renders "Kenny"
+
+

LogEvent Properties Dictionary

+

In C# class, create an event and add an element to the Properties dictionary (or the deprecated Context dictionary):

+
...
+Logger logger = LogManager.GetCurrentClassLogger();
+LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, null, "My log message");
+theEvent.Properties["MyValue"] = "My custom string";
+theEvent.Properties["MyDateTimeValue"] = new DateTime(2015, 08, 30, 11, 26, 50);
+theEvent.Properties["MyInteger"] = 42;
+logger.Log(theEvent);
+...
+
+

and in your NLog.config file:

+
${event-properties:item=MyValue} -- renders "My custom string"
+${event-properties:MyDateTimeValue:format=yyyy-M-dd}"; -- renders "2015-8-30"
+${event-properties:MyDateTimeValue:culture=en-US} -- renders "8/30/2015 11:26:50 AM"
+${event-properties:MyDateTimeValue:format=yyyy-M-dd HH:mm:ss:culture=en-US} -- renders "2015-8-30 11:26:50"
+
+

Logger WithProperty

+
+

Introduced in NLog 4.6.3, where Logger have the method WithProperty.

+
+

The Logger can be enriched, so it automatically injects one (or more) log-event properties for all log-events being written by the Logger. This can work as an alternative to ScopeContext properties.

+

Examples:

+
// WithProperty will return a new unique Logger with the newly added property
+var newLogger = logger.WithProperty("myProperty", myValue);
+newLogger.Info("hello");
+newLogger.Info("again"); // will also have "myProperty"
+logger.Info("hi");       // is not affected
+
+

Logger FLuent API

+

NLog 5.0 provides Fluent-Logger-API for building LogEvents:

+
_logger.ForInfoEvent()
+       .Message("This is a fluent message {0}.", "test")
+       .Property("PropertyName", "PropertyValue")
+       .Log();
+
+

Fallback to default value

+

When LogEvent Property cannot be found (or has blank value), then one can use whenEmpty to specify fallback value:

+
${event-properties:EventId:whenEmpty=42}
+
+

Objectpath

+

Examples with usage of Objectpath. NLog 4.6.3+

+

Set the property:

+
var property1 = new { Id = 1, Name = "test", Nested = new { Id = 3 } };
+
+var logger = LogManager.GetLogger("logger1");
+
+// e.g. with WithProperty
+logger.WithProperty("prop1", property1 ).Info("test message");
+
+// or with structured logging
+logger.Info("test Message with {prop1}", property1);
+
+

config examples:

+
${event-properties:prop1} -- renders: { Id = 1, Name = test, Nested = { Id = 3 } }
+${event-properties:prop1:objectpath=Id} -- renders: 1
+${event-properties:prop1:objectpath=Nested.Id} -- renders: 3
+
+

See also Transform captured properties

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Eventlog-target/index.html b/wiki/Eventlog-target/index.html new file mode 100644 index 000000000..221798c40 --- /dev/null +++ b/wiki/Eventlog-target/index.html @@ -0,0 +1,1403 @@ + + + + + + + + Eventlog target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log message to the Windows Event Log.

+
+

Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsEventLog since NLog 5.0

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="EventLog"
+          name="String"
+          layout="Layout"
+          machineName="String"
+          source="Layout" 
+          category="Layout"
+          eventId="Layout"
+          log="String"
+          maxKilobytes="long"
+          maxMessageLength="Integer" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}. Note: max size of 31839 characters (limitation of the EventLog API)
  • +
+

Event Log Options

+
    +
  • machineName - Name of the machine on which Event Log service is running. Default: .
    +

    NLog 6.0 changed property-type from string to NLog Layout.

    +
    +
  • +
  • source - Value to be used as the event Source. By default this is the friendly name of the current AppDomain.
    +

    NLog 4.0 changed property-type from string to NLog Layout.

    +
    +
  • +
  • category - Layout that renders event Category. The categories must be predefined for the specified source and needs to be numeric.
    +

    NLog 5.0 changed property-type from string to NLog Layout.

    +
    +
  • +
  • eventId - Layout that renders event ID.
    +

    NLog 5.0 changed property-type from standard NLog Layout to typed-layout.

    +
    +
  • +
  • eventLogEntryType - Layout that renders EventLogEntryType. Default: Use LogLevel
    +

    NLog 5.0 changed property-type from standard NLog Layout to typed-layout.

    +
    +
  • +
  • log - Name of the Event Log to write to. This can be System, Application or any user-defined name. Default: Application
    +

    NLog 6.0 changed property-type from string to NLog Layout.

    +
    +
  • +
  • MaxMessageLength - The message length limit to write to the Event Log. There are various message length limit that depends on the OS.
    +

    Introduced in NLog 4.3 with default-value: 16,384, and bumped to 30,000 with NLog v5.0.2 . +NLog 6.0 changed property-type from integer to NLog Layout.

    +
    +
  • +
  • onOverflow - Action to take when a log message is larger than the MaxMessageLength option. Available actions are:
  • +
  • Truncate - Truncates the message before writing to the Event Log. This is the default.
  • +
  • Split - Splits the message and writes multiple entries to the Event Log. Warning: the message layout will be spread across multiple Event Log entries; if there is an application reading and parsing the Event Log, split messages will not have the expected layout of a log entry.
  • +
  • Discard - Discards of the message. It will not be written to the Event Log.
  • +
  • MaxKilobytes - maximum Event log size in kilobytes. null is default (512KB). Value should be multiples of 64 and between 64 and 4194240. Note, this requires admin rights.
    +

    Introduced in NLog 4.4.10 . +NLog 6.0 changed property-type from integer to NLog Layout.

    +
    +
  • +
+

Notes

+

When writing to the Windows EventLog, the EventLog-Source must be registered. NLog will automatically attempt to register the EventLog-Source if the application is running with necessary permissions. Alternatively, one must explicitly perform the EventLog-Source registration during application install. +- Installing Targets will only register EventLog-Source if source is static (Not using layout renderers). +- A simple PowerShell command can be used to register an EventLog-Source (run PowerShell as Administrator): + PowerShell + New-EventLog -LogName Application -Source "MySourceName" + NOTE: It may be necessary to restart the Windows Event Log Service (or, alternatively, reboot the computer) after making a change to the EventLog-Source registration in order for the change to take effect.

+

Notice a specific EventLog-source can only be registered for writing to a single named EventLog. Windows gives the illusion of multiple EventLogs, but all LogEvents are stored in the same blob where the EventLog-name is more like a category. The Windows Registry Database controls where the LogEvents from registered EventLog-source should be shown. If changing an EventLog-source to write to a different EventLog, then the change will not be applied until having restarted Windows (or restarted the EventLog-Windows-Service).

+

The Event Log has a limit in the number of bytes in a message. From MSDN:

+
+

The message string is longer than 31,839 bytes (32,766 bytes on Windows operating systems before Windows Vista).

+
+

Example

+
<targets>
+    <target xsi:type="EventLog"
+            name="EventLogTarget"
+            source="MyApplicationName"
+            eventId="${event-properties:EventId:whenEmpty=0}"
+            layout="${message}${newline}${exception:format=ToString}" />
+</targets>
+<rules>
+    <logger name="ApplicationEventLog" writeTo="EventLogTarget" />
+</rules>
+
+
NLog.LogManager.GetLogger("ApplicationEventLog").WithProperty("EventId", 42).Error("Kilroy was here");
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Examples/index.html b/wiki/Examples/index.html new file mode 100644 index 000000000..896bd1c01 --- /dev/null +++ b/wiki/Examples/index.html @@ -0,0 +1,1358 @@ + + + + + + + + Examples - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Using NLog as .NET Core and ASP.NET Core logging provider

+ +

Changing log file name at runtime

+
using NLog.Targets;
+...
+FileTarget target = LogManager.Configuration.FindTargetByName<FileTarget>(targetName);
+target.FileName = filename;
+
+

Note that it is often easier to create the file name with a combination of layout-renderers.

+

See also Configure from code

+

Using NLog with Autofac - ASP.NET Web API 2

+

This example is using a nuget package Autofac.Extras.Nlog that takes care of creating the Autofac module needed to wire up the dependency in the Web API.

+

First, add an nlog section to the configSections in the Web.config:

+
  <configSections>
+    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
+  </configSections>
+
+

Then, in the Global.asax.cs (or Startup.cs, depending where Autofac is configured) register the module provided by the Autofac.Extras.Nlog nuget package:

+
  var builder = new ContainerBuilder();
+   ...
+
+  builder.RegisterModule<NLogModule>();
+
+

Nothing extra is needed to configure the NLog targets.

+

This example uses constructor injection but Autofac.Extras.Nlog supports property and service locator injection as well.

+
using System;
+using System.Net;
+using System.Net.Http;
+using System.Threading.Tasks;
+using Autofac.Extras.NLog;
+using Microsoft.AspNet.Identity;
+
+    public class UserService: IUserService
+    {
+        private readonly IUserStore _userStore;
+        private readonly ILogger _logger;
+
+        public UserService(IUserStore userStore, ILogger logger)
+        {
+            _userStore = userStore;
+            _logger = logger;
+        }
+
+        .....
+    }
+
+

Happy logging!

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Exception-layout-renderer/index.html b/wiki/Exception-layout-renderer/index.html new file mode 100644 index 000000000..3f764d0e9 --- /dev/null +++ b/wiki/Exception-layout-renderer/index.html @@ -0,0 +1,1408 @@ + + + + + + + + Exception layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Exception information provided together with the LogEvent. See also How to properly log exceptions.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${exception:format=String:innerFormat=String:maxInnerExceptionLevel=Integer:innerExceptionSeparator=String
+           :separator=String:exceptionDataSeparator=string}
+
+

Parameters

+

Rendering Options

+
    +
  • format - Format of the output. Default: ToString,Data. Must be a comma-separated list of exception properties:
    +

    Notice before NLog 5.0, then default was just message.

    +
    +
  • +
  • Message - Serialize Exception.Message
  • +
  • Type - Serialize Exception.GetType().FullName
  • +
  • ShortType - Serialize Exception.GetType().Name
  • +
  • ToString - Serialize Exception.ToString()
  • +
  • Method - Serialize Exception.TargetSite
  • +
  • StackTrace - Serialize Exception.StackTrace
  • +
  • Data - Serialize the dictionary Exception.Data
  • +
  • Source - Serialize Exception.Source. Introduced in NLog 4.6.7
  • +
  • TargetSite - Serialize Exception.TargetSite. Introduced in NLog 4.6.7
  • +
  • HResult - Serialize Exception.HResult. Introduced in NLog 4.6.8
  • +
  • Properties - Appends any additional properties that specific type of Exception might have. Introduced in NLog 4.6.8
  • +
  • +

    @ - Serialize all Exception-properties into Json-format. Introduced in NLog 4.5

    +
  • +
  • +

    innerFormat - Format of the output of inner exceptions. Must be a comma-separated list of exception properties (As shown above). This parameter value is case-insensitive.

    +
  • +
  • +

    maxInnerExceptionLevel - Maximum number of inner exceptions to include in the output. By default inner exceptions are not enabled for compatibility with NLog 1.0. Note that the format @ serializes InnerException like any other property. Integer. Default: 0

    +
  • +
  • +

    separator - Separator used to concatenate parts specified in the Format. Default: single space

    +
  • +
  • innerExceptionSeparator - Separator between inner exceptions. Default: new line
  • +
  • +

    exceptionDataSeparator - Separator used to concatenate the exception data parts. Default: ;

    +
    +

    Introduced in NLog 4.3.9

    +
    +
  • +
  • +

    baseException - Render innermost Exception from Exception.GetBaseException(). Boolean. Default: false

    +
    +

    Introduced in NLog 4.7.1

    +
    +
  • +
  • +

    flattenException - Automatically flatten AggregateException from async operations to extract its inner exceptions. Boolean. Default: true

    +
    +

    Introduced in NLog 4.7.6

    +
    +
  • +
+

Notes

+

If debug symbol information is not available, then Exception.ToString() will not output source-code filenames or line-numbers. Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause "unexpected" line-numbers.

+

Examples

+

Log only message

+
${exception:format=message}
+
+

Log full (without Data)

+

ToString will also print the innerException:

+
${exception:format=toString}
+
+

Log full (including Data)

+

Also print exception data, e.g.

+
var ex = new Exception();
+ex.Data.Add("data1", "val2");
+throw ex;
+
+
${exception:format=toString,Data}
+
+

Log exception as JSON

+

the @ format recursively serializes the entire exception hierarchy; combining it with maxInnerExceptionLevel and innerExceptionSeparator won't do what you want. To get the entire exception hierarchy including innerexceptions as nested objects, just specify :format=@.

+
${exception:format=@}
+
+

Custom Exception Serialization

+

NLog 4.7 allows you to override the object reflection for certain object-types. This can be useful for objects with dangerous properties or complex properties.

+
LogManager.Setup().SetupSerialization(s =>
+   s.RegisterObjectTransformation<System.Net.WebException>(ex => new {
+      Type = ex.GetType().ToString(),
+      Message = ex.Message,
+      StackTrace = ex.StackTrace,
+      Source = ex.Source,
+      InnerException = ex.InnerException,
+      Status = ex.Status,
+      Response = ex.Response.ToString(),  // Call your custom method to render stream as string
+   })
+);
+
+

This can then be used together with:

+
${exception:format=ToString,Properties,Data}
+
+

Or like this for generating JSON:

+
${exception:format=@}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ExceptionData-Layout-Renderer/index.html b/wiki/ExceptionData-Layout-Renderer/index.html new file mode 100644 index 000000000..787a8e11d --- /dev/null +++ b/wiki/ExceptionData-Layout-Renderer/index.html @@ -0,0 +1,1321 @@ + + + + + + + + ExceptionData Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Lookup item in Exception.Data-Dictionary from Exception provided together with the LogEvent. See also How to properly log exceptions.

+
+

Platforms Supported: All (Introduced with NLog 5.0)

+
+

Configuration Syntax

+
${exceptiondata:item=String:format=String:BaseException=Boolean}
+
+

Parameters

+
    +
  • Item - Item to lookup in Exception.Data
  • +
  • Format - Format for conversion from object to string (@ means serialize object properties into Json-format)
  • +
  • BaseException - Render innermost Exception from Exception.GetBaseException(). Boolean. Default: false
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Explicit-NLog-configuration-loading/index.html b/wiki/Explicit-NLog-configuration-loading/index.html new file mode 100644 index 000000000..cb90e6a98 --- /dev/null +++ b/wiki/Explicit-NLog-configuration-loading/index.html @@ -0,0 +1,1360 @@ + + + + + + + + Explicit NLog configuration loading - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ℹ️ See also Environment specific NLog Logging Configuration

+

Loading NLog configuration from file

+

NLog will automatically scan for configuration files, but sometimes the platform requires explicit configuration loading like this:

+
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("nlog.config");
+
+

Loading NLog configuration from string

+

The configuration can also come from standard string like this with NLog v4.6:

+
NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString);
+
+

NLog v5 introduces this fluent extension-method:

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

Loading NLog config from Assembly Resource

+

You need to put the NLog.config file into the application-project, then edit file's properties - change the build action to embedded resource.

+
public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
+{
+  var resourcePaths = assembly.GetManifestResourceNames()
+    .Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
+    .ToList();
+  if (resourcePaths.Count == 1)
+  {
+    return assembly.GetManifestResourceStream(resourcePaths.Single());
+  }
+  return null;
+}
+
+var nlogConfigStream = GetEmbeddedResourceStream(myAssembly, "NLog.config");
+if (nlogConfigStream != null)
+{
+    var xmlString = new System.IO.StreamReader(nlogConfigStream).ReadToEnd();
+    NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString);
+}
+
+

NLog v5 introduces this fluent configuration extension-method:

+
NLog.LogManager.Setup().LoadConfigurationFromAssemblyResource(typeof(App).GetTypeInfo().Assembly);
+
+

Xamarin Android

+

⚠️ NLog v5 will no longer scan the assets folder for NLog.config. Instead consider using Embedded Assembly Resource

+

With NLog v4 then the NLog.dll built for Xamarin Android would automatically scan the assets folder for NLog.config.

+

If the file name is different, then NLog v4 also supported this:

+
LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
+````
+
+If using the NLog.dll built for NetStandard in Xamarin, then the Android `assets`-folder is not recognized or scanned. Instead consider using Assembly Resource.
+
+To explicly read file from [Android Assets](https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/resources-in-android/android-assets), then one can do this:
+```c#
+AssetManager assets = this.Assets;
+var assetStream = assets.Open("NLog.config");
+var xmlString = new System.IO.StreamReader(assetStream).ReadToEnd();
+NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString);
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Extending-NLog/index.html b/wiki/Extending-NLog/index.html new file mode 100644 index 000000000..6c209627a --- /dev/null +++ b/wiki/Extending-NLog/index.html @@ -0,0 +1,1323 @@ + + + + + + + + Extending NLog - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The following article has related news post: Extending NLog is... easy!

+

If one needs to capture additional context for target output, then one can create own custom NLog LayoutRenderer. But usually most people will just make use of NLog LogEvent Properties for providing custom context. Ensure also to check the available layoutrenderers.

+

If one needs to redirect output to a different output target destination, then one can create own custom NLog Target. But usually most people will just make use of NLog Network-Target or NLog WebService-Target and override the NLog Layout to match the payload format. Ensure also to check the available targets.

+

Write Extensions

+ +

Register Extensions

+ + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/FAQ/index.html b/wiki/FAQ/index.html new file mode 100644 index 000000000..45ca2d768 --- /dev/null +++ b/wiki/FAQ/index.html @@ -0,0 +1,1401 @@ + + + + + + + + FAQ - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ + + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/FallbackGroup-target/index.html b/wiki/FallbackGroup-target/index.html new file mode 100644 index 000000000..d8818d5ac --- /dev/null +++ b/wiki/FallbackGroup-target/index.html @@ -0,0 +1,1357 @@ + + + + + + + + FallbackGroup target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Provides fallback-on-error.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="FallbackGroup" name="String" returnToFirstOnSuccess="Boolean">
+    <target xsi:type="wrappedTargetType" ... />
+    <target xsi:type="wrappedTargetType" ... />
+    ...
+    <target xsi:type="wrappedTargetType" ... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Fallback Options

+
    +
  • returnToFirstOnSuccess - Indicates whether to return to the first target after any successful write. Boolean. Default false
  • +
+

Example

+

Fallback to another mail if the mailserver is down

+
<target xsi:type="FallbackGroup" 
+        name="mail"
+        returnToFirstOnSuccess="true">
+    <target xsi:type="Mail"
+            name="mailserver1"
+            subject="Layout"
+            to="Layout"
+            from="Layout"
+            smtpServer="mx1.example.com" 
+            smtpPort="Integer"
+            layout="Layout" />
+    <target xsi:type="Mail"
+            name="mailserver2" 
+            subject="Layout"
+            to="Layout"
+            from="Layout"
+            smtpServer="mx2.example.com" 
+            smtpPort="Integer"
+            layout="Layout" />
+</target>
+<rules>
+  <logger name="*" minlevel="Trace" writeTo="mail" />
+</rules>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/File-AddNewItem.png b/wiki/File-AddNewItem.png new file mode 100644 index 000000000..f66842279 Binary files /dev/null and b/wiki/File-AddNewItem.png differ diff --git a/wiki/File-AddReference.png b/wiki/File-AddReference.png new file mode 100644 index 000000000..fe8517d08 --- /dev/null +++ b/wiki/File-AddReference.png @@ -0,0 +1,287 @@ + + + + + + + + + + + + + + + File:AddReference.png - NLog - Advanced .NET Logging + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+ + + + +
+
+
+ + +Ads by Lake Quincy Media +
+
+

Wiki Navigation

+
+ + +   +
+
+
+Gibraltar - Learn about the best analysis tool for NLog +
+
+ + + +
+ +

File:AddReference.png

+
+
+ +
+ NLog documentation is a Wiki, which allows registered users to edit its content.
If you want to contribute, please create a user account and contact Jarek to get edit access. +
+
+ + +
+ + + + + +

File history

Click on a date/time to view the file as it appeared at that time. +

(Latest | Earliest) View (newer 50) (older 50) (20 | 50 | 100 | 250 | 500) + + +
Date/TimeThumbnailDimensionsUserComment
current20:12, 5 June 2010Thumbnail for version as of 20:12, 5 June 2010728×450 (59 KB)Admin (Talk | contribs)
+(Latest | Earliest) View (newer 50) (older 50) (20 | 50 | 100 | 250 | 500) +
+
+

The following page links to this file: +

+ + + +
+
+ + +Ads by Lake Quincy Media +
+ +
+
+ + + + + +
+
+ diff --git a/wiki/File-Intellisense.png b/wiki/File-Intellisense.png new file mode 100644 index 000000000..7a1d27abe --- /dev/null +++ b/wiki/File-Intellisense.png @@ -0,0 +1,287 @@ + + + + + + + + + + + + + + + File:Intellisense.png - NLog - Advanced .NET Logging + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+ + + + +
+
+
+ + +Ads by Lake Quincy Media +
+
+

Wiki Navigation

+
+ + +   +
+
+
+Gibraltar - Learn about the best analysis tool for NLog +
+
+ + + +
+ +

File:Intellisense.png

+
+
+ +
+ NLog documentation is a Wiki, which allows registered users to edit its content.
If you want to contribute, please create a user account and contact Jarek to get edit access. +
+
+ + +
+ + + + + +

File history

Click on a date/time to view the file as it appeared at that time. +

(Latest | Earliest) View (newer 50) (older 50) (20 | 50 | 100 | 250 | 500) + + +
Date/TimeThumbnailDimensionsUserComment
current20:17, 5 June 2010Thumbnail for version as of 20:17, 5 June 2010864×581 (105 KB)Admin (Talk | contribs)
+(Latest | Earliest) View (newer 50) (older 50) (20 | 50 | 100 | 250 | 500) +
+
+

The following page links to this file: +

+ + + +
+
+ + +Ads by Lake Quincy Media +
+ +
+
+ + + + + +
+
+ diff --git a/wiki/File-target/index.html b/wiki/File-target/index.html new file mode 100644 index 000000000..d549ba206 --- /dev/null +++ b/wiki/File-target/index.html @@ -0,0 +1,1777 @@ + + + + + + + + File target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to one or more files.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="File"
+          name="String"
+          layout="Layout"
+          header="Layout"
+          footer="Layout"
+          fileName="Layout"
+          encoding="Encoding"
+          lineEnding="Enum"
+          archiveAboveSize="Long"
+          maxArchiveFiles="Integer"
+          maxArchiveDays="Integer"
+          archiveFileName="Layout"
+          archiveEvery="Enum"
+          archiveOldFileOnStartup="Boolean"
+          replaceFileContentsOnEachWrite="Boolean"
+          deleteOldFileOnStartup="Boolean"
+          enableFileDelete="Boolean"
+          createDirs="Boolean"
+          openFileFlushTimeout="Integer"
+          openFileCacheTimeout="Integer"
+          openFileCacheSize="Integer"
+          bufferSize="Integer"
+          autoFlush="Boolean"
+          keepFileOpen="Boolean"
+          writeFooterOnArchivingOnly="Boolean"
+          writeHeaderWhenInitialFileNotEmpty="Boolean"
+          writeBom="Boolean" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • +

    layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}

    +
  • +
  • +

    header - Header. Layout

    +
  • +
  • +

    footer - Footer. Layout

    +
  • +
  • +

    encoding - File encoding name like "utf-8", "ascii" or "utf-16". See Encoding class on MSDN. Default: Utf-8 (Before NLog 5.0 the default was Encoding.Default)

    +
  • +
  • +

    writeBom - Indicates whether to write BOM (byte order mark) in created files. Boolean Default: false.

    +
    +

    Introduced with NLog 4.5. And after NLog 5.0 is is automatically enabled when encoding UTF16 or UTF32.

    +
    +
  • +
  • +

    lineEnding - Line ending mode.
    +Possible values:

    +
  • +
  • CR - Insert CR character (ASCII 13) after each line.
  • +
  • CRLF - Insert CR LF sequence (ASCII 13, ASCII 10) after each line.
  • +
  • Default - Insert platform-dependent end-of-line sequence after each line.
  • +
  • LF - Insert LF character (ASCII 10) after each line.
  • +
  • NULL - Null terminator (ASCII 0) after each line.
  • +
  • None - Don't insert any line ending.
  • +
+

Output Options

+
    +
  • +

    fileName - Name of the file to write to. Layout Required.
    +This FileName string is a layout which may include instances of layout renderers. This lets you use a single target to write to multiple files.
    +The following value makes NLog write logging events to files based on the log level in the directory where the application runs. ${basedir}/${level}.log All Debug messages will go to Debug.log, all Info messages will go to Info.log and so on. You can combine as many of the layout renderers as you want to produce an arbitrary log file name. See also Filename Directory

    +
  • +
  • +

    enableFileDelete - Indicates whether to enable log file(s) to be deleted. The FileTarget will periodically verify if the file has been deleted and must be recreated. Boolean Default: True

    +
  • +
  • +

    createDirs - Indicates whether to create directories if they don't exist. Boolean Default: True
    +Setting this to false may improve performance a bit, but you'll receive an error when attempting to write to a directory that's not present.

    +
  • +
  • +

    replaceFileContentsOnEachWrite - Indicates whether to replace file contents on each write instead of appending log message at the end. Boolean Default: False

    +
  • +
  • +

    writeHeaderWhenInitialFileNotEmpty - Indicates whether to write the Header on initial creation of file appender, independent of file is empty or not. Boolean Default: False (Alternative one can use archiveOldFileOnStartup to ensure each application-session has its own individual log-file)

    +
    +

    Introduced with NLog v5.2.6

    +
    +
  • +
  • +

    forceManaged - Indicates that the file target should only use managed methods. This disables some of the options.

    +
    +

    NLog v6 removed support for native methods, and always use managed FileStream

    +
    +
  • +
  • +

    fileAttributes - File attributes (Windows only).

    +
    +

    NLog v6 removed support for native methods and assigning file-attributes. +Possible values:

    +
    +
  • +
  • Archive - File should be archived.
  • +
  • ~~Compressed~~ - Compress won't work due to .Net restrictions. You can use enableArchiveFileCompression.
  • +
  • DeleteOnClose - Delete file after it is closed.
  • +
  • Device - Device file.
  • +
  • Encrypted - Encrypted file.
  • +
  • Hidden - Hidden file.
  • +
  • NoBuffering - The system opens a file with no system caching.
  • +
  • Normal - Normal file.
  • +
  • NotContentIndexed - File should not be indexed by the content indexing service.
  • +
  • PosixSemantics - A file is accessed according to POSIX rules.
  • +
  • Readonly - Read-only
  • +
  • ReadOnly - Read-only file.
  • +
  • ReparsePoint - Reparse point.
  • +
  • SparseFile - Sparse file.
  • +
  • System - System file.
  • +
  • Temporary - File is temporary (should be kept in cache and not written to disk if possible).
  • +
  • WriteThrough - The system writes through any intermediate cache and goes directly to disk.
  • +
+

Archival Options

+
    +
  • +

    archiveAboveSize - Size in bytes above which log files will be automatically archived. Long

    +
    +

    Before NLog ver. 4.5.7 then this would not work together with archiveNumbering=Date. Newer version will correctly merge into the existing file on archive.

    +
    +
  • +
  • +

    maxArchiveFiles - Maximum number of archive files that should be kept. If maxArchiveFiles is less or equal to 0, old files aren't deleted Integer Default: 0

    +
  • +
  • +

    maxArchiveDays - Maximum age of archive files that should be kept. Has no effect when archiveNumbering is Rolling. If maxArchiveDays is less or equal to 0, old files aren't deleted Integer Default: 0

    +
    +

    Introduced with NLog 4.7 but not supporting archiveNumbering="Rolling", or archiveNumbering="Sequence" with custom archiveFileName-path

    +
    +
  • +
+
+

NLog 5.0 added support for archiveNumbering="Sequence" with custom archiveFileName-path

+
+
    +
  • +

    archiveSuffixFormat - Filename-suffix to append, when the archive-logic is rolling to the next file. Works like string.Format where {0} outputs archive-sequence-number and {1} outputs the archiveFileName-timestamp. Default: _{0:00}.

    +
    +

    Introduced with NLog v6 to replace archiveNumbering and archiveDateFormat.

    +
    +
  • +
  • +

    archiveOldFileOnStartup - Archive old log file on startup. Default: False

    +
  • +
  • +

    deleteOldFileOnStartup - Indicates whether to delete old log file on startup. Boolean Default: False. This option works only when the "FileName" parameter denotes a single file.

    +
  • +
  • +

    archiveFileName - Name of the file to be used for an archive. Layout
    +It may contain a special placeholder {###} that will be replaced with a sequence of numbers depending on the archiving strategy. The number of hash characters used determines the number of numerical digits to be used for numbering files.

    +
    +

    NLog v6 replaces the special placeholder {###} with new ArchiveSuffixFormat

    +
    +
  • +
  • +

    Warning: Before NLog 4.5 then it would lead to very aggressive cleanup if having configured maxArchiveFiles without having specified the special placeholder {###}, as cleanup-wildcard would become any files in the archive folder (not just log files).

    +
  • +
  • +

    archiveNumbering - Way file archives are numbered. See also Archive Numbering Examples
    +Possible values:

    +
    +

    NLog v6 replaces ArchiveNumbering-option with new ArchiveSuffixFormat

    +
    +
  • +
  • Rolling - Rolling style numbering (the most recent is always #0 then #1, ..., #N).
  • +
  • Sequence - Sequence style numbering. The most recent archive has the highest number.
  • +
  • Date - Date style numbering. The date is formatted according to the value of archiveDateFormat.
      +
    • Warning: Before NLog ver. 4.5.7 then this would not work together with archiveAboveSize. Newer version will correctly merge into the existing file on archive.
    • +
    +
  • +
  • +

    DateAndSequence - Combination of Date and Sequence .Archives will be stamped with the prior period (Year, Month, Day) datetime. + The most recent archive has the highest number (in combination with the date). The date is formatted according to the value of archiveDateFormat.

    +
  • +
  • +

    archiveEvery - Indicates whether to automatically archive log files every time the specified time passes.
    +Possible values:

    +
  • +
  • Day - Archive daily.
  • +
  • Hour - Archive every hour.
  • +
  • Minute - Archive every minute.
  • +
  • Month - Archive every month.
  • +
  • None - Don't archive based on time.
  • +
  • Year - Archive every year.
  • +
  • Sunday - Archive every Sunday. Introduced in NLog 4.4.4.
  • +
  • Monday - Archive every Monday. Introduced in NLog 4.4.4.
  • +
  • Tuesday - Archive every Tuesday. Introduced in NLog 4.4.4.
  • +
  • Wednesday - Archive every Wednesday. Introduced in NLog 4.4.4.
  • +
  • Thursday - Archive every Thursday. Introduced in NLog 4.4.4.
  • +
  • Friday - Archive every Friday. Introduced in NLog 4.4.4.
  • +
  • +

    Saturday - Archive every Saturday. Introduced in NLog 4.4.4.

    +
    +

    Files are moved to the archive as part of the write operation if the current period of time changes. For example if the current hour changes from 10 to 11, the first write that will occur on or after 11:00 will trigger the archiving.

    +
    +
  • +
  • +

    archiveDateFormat - Specifies the date format used for archive numbering. Default format depends on the archive period. This option works only when the "ArchiveNumbering" parameter is set to Date or DateAndSequence

    +
    +

    NLog v6 replaces ArchiveDateFormat-option with new ArchiveSuffixFormat

    +
    +
  • +
  • Default: yyyyMMdd
  • +
  • Default when ArchiveEvery = Minute: yyyyMMddHHmm
  • +
  • Default when ArchiveEvery = Hour: yyyyMMddHH
  • +
  • Default when ArchiveEvery = Month: yyyyMM
  • +
  • +

    Default when ArchiveEvery = Year: yyyy

    +
  • +
  • +

    archiveOldFileOnStartupAboveSize - File size threshold to archive old log file on startup. Default value is 0 which means that the file is archived as soon as archiveOldFileOnStartup is enabled. Introduced in NLog 4.7

    +
    +

    NLog v6 replaces archiveOldFileOnStartupAboveSize-option with archiveOldFileOnStartup and archiveAboveSize.

    +
    +
  • +
  • +

    enableArchiveFileCompression - Indicates whether to compress the archive files into the zip files. Boolean Default: False

    +
    +

    Introduced in NLog ver. 4.0. Not supported for .Net35 + .Net40 and only works with static filename +Before NLog ver. 5.0 then the filename inside the zip-file would be original filename, instead of archive-filename. +NLog v6 removed enableArchiveFileCompression-option. Instead use NTFS-compression or setup cron-job / scheduled-task for nightly compression or GZip-File-Target or legacy NLog.Targets.ConcurrentFile

    +
    +
  • +
  • +

    writeFooterOnArchivingOnly - Indicates whether the footer should be written only when the file is archived. If False, the footer will also be written when starting to write to a different file and when the target is closed Boolean Default: False

    +
  • +
+

Performance Tuning Options

+
    +
  • +

    keepFileOpen - Indicates whether to keep log file open instead of opening and closing it on each logging event. When set to false it will allow other applications to "take over" the filehandle, and NLog will fail logging to file. When set to false then it will give a major performance hit because it is expensive to open/close file-handle. If the FileName points to a network-path, then it is recommended to use keepFileOpen="false" in combination with <targets async="true">. Boolean Default: True (Before NLog 5.0 the default was false)

    +
  • +
  • +

    concurrentWrites - Enables support for optimized concurrent writes to same log file from multiple processes on the same machine-host, when using keepFileOpen = true. By using a special synchronization techniques that lets it keep the files open from multiple processes. The special synchronization cost performance and not compatible with platforms like UWP / Xamarin. Default: False (Before NLog 5.0 the default was true)

    +
    +

    NLog v6 removed concurrentWrites-option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile

    +
    +
  • +
  • +

    openFileCacheTimeout - Maximum number of seconds that files are kept open. Configures Timer that automatically closes file-handles, that have been open for more than specified number of seconds. Integer Default: -1

    +
  • +
  • +

    openFileCacheSize - Maximum number of files to be kept open. Closes files in LRU (least-recently-used) ordering, so closes files unused for the longest period of time should the cache become full. Increasing the value can improve performance, when single file target is writing to many files (such as splitting by loglevel or by logger-name). But having too many file-handles open can also hurt performance. Integer Default: 5

    +
  • +
  • +

    networkWrites - Indicates whether concurrent writes to the log file by multiple processes on different network hosts. This effectively prevents files from being kept open, so behaves just like KeepFileOpen="false". Boolean Default: False

    +
    +

    NLog v6 removed networkWrites-option. Instead use KeepFileOpen=false.

    +
    +
  • +
  • +

    concurrentWriteAttemptDelay - Delay in milliseconds to wait before attempting to write to the file again. Integer Default: 1
    +The actual delay is a random value between 0 and the value specified in this parameter. On each failed attempt the delay base is doubled up to ConcurrentWriteAttempts times.
    +Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be: a random value between 0 and 10 milliseconds - 1st attempt a random value between 0 and 20 milliseconds - 2nd attempt a random value between 0 and 40 milliseconds - 3rd attempt a random value between 0 and 80 milliseconds - 4th attempt ... and so on.

    +
    +

    NLog v6 removed concurrentWrites-option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile

    +
    +
  • +
  • +

    concurrentWriteAttempts - Number of times the write is attempted on the file before NLog discards the log message. Integer Default: 10

    +
    +

    NLog v6 removed concurrentWrites-option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile

    +
    +
  • +
  • +

    cleanupFileName - before writing to a file, the name of the file get checked for illegal characters (OS dependent). This can be costly if a lot of messages are written. The cleanup is cached for fixed names (no layout renderers). Set this to false for optimal performance (but beware of the file name, if it's wrong, nothing gets written). Default: true. Introduced in NLog 4.2.3.

    +
    +

    NLog v6 removed cleanupFileName-option, since it happens implicitly.

    +
    +
  • +
  • +

    bufferSize - Log file buffer size in bytes. Notice Large-Object-Heap will be used when size 85000 or above. Integer Default: 32768

    +
  • +
  • +

    autoFlush - Ensures file buffers are flushed after each log message, thus avoiding loss of critical log-messages during unexpected application-crash or -exit. The operating system will ensure that flushed data will be written to disk, even if application has left the planet. But if the operating system also crashes or computer-power-failure, then flushed data might still be lost, as it is not flush with write-through. If log-messages are not super critical for troubleshooting, or not having issues with unexptected application crashes, then one can improve performance with AutoFlush = false (See also openFileFlushTimeout). Boolean Default: True

    +
  • +
  • +

    openFileFlushTimeout - Number of seconds between explicit flush of file buffers. Helps to ensure file buffers are eventually flushed when autoFlush = false. Integer Default: 0 (Disabled) + > Introduced with NLog v4.5.7

    +
  • +
+

Examples

+

Simple logging

+

The simplest use of File target is to produce single log file. In order to do this, put the following code in the configuration file such as NLog.config. Logs wil be written to logfile.txt in logs directory.

+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
+            fileName="${basedir}/logs/logfile.txt" 
+            keepFileOpen="true"
+            encoding="utf-8" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

Filename Directory

+

File Target supports relative paths since NLog 4.3, where it will implicitly use ${BaseDir} (AppDomain.BaseDirectory). It is also possible to specify an absolute path or make use of these helpers:

+ +

Example using CommonApplicationData which is good when running as Windows Service:

+
    +
  • fileName="${specialfolder:folder=CommonApplicationData:cached=true}/AppName/logfile.txt"
  • +
  • Windows-Path - C:/ProgramData/AppName/logfile.txt
  • +
+

To remove all doubt, then one can also use absolute-paths. And by using NLog config variables then one can reuse the absolute path for multiple file targets:

+
<variable name="logDirectory" value="C:/AppDir/" />
+<targets>
+<target type="file" name="logfile" filename="${logDirectory}App.log" />
+</targets>
+
+

It is also possible to override the directory at runtime using GDC:

+
<targets>
+<target type="file" name="logfile" filename="${gdc:logDirectory:whenEmpty=${baseDir}}/App.log" />
+</targets>
+
+
NLog.GlobalDiagnosticsContext.Set("logDirectory", "C:/Temp/");
+
+

Batch write and asynchronous logging

+

The file target has support for batch writing, where multiple log messages are written in one file-operation. Batch write will improve performance, especially when using KeepFileOpen=false. Batch writing is enabled automatically when using the AsyncWrapper. This can be done by adding the attribute async="true" to the <targets>-element.

+

Asynchronous logging is recommended for multi-threaded server applications, but might not be worth it for quick-finishing command line application. Make sure to remember to flush at application shutdown, or else output can be dropped.

+
<?xml version="1.0" ?>
+<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 async="true">
+        <target type="File" name="logfile" fileName="${basedir}/logs/${level}.txt" keepFileOpen="true" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="logfile" />
+    </rules>
+</nlog>
+
+

Multi processes writing same file

+

The IIS-application can run multiple AppDomains, and each AppDomain operates like a child process. When multiple processes are concurrently writing to the same file, then some locking for coordination is needed:

+
    +
  • +

    Operating System File Locks - Enabled with KeepFileOpen=false. File locking from operating system are not fair and doesn't scale when having more than 2 processes writing to the same file. Exceptions will be thrown when one process tries to open a file, that is currently in use by another process. NLog tries to handle these exception by retrying on error, but will backoff so LogEvents are lost. Performance can be improved a lot by applying <targets async="true>.

    +
  • +
  • +

    Atomic File Append - The lock synchronization is fair, and happens at the operating system level. It is the fastest concurrent mode available with minimum overhead. Each application performs non-buffered file-append with help from operating system O_APPEND. NLog v6 introduces Atomic-File-Target that supports both .NET Framework and new NET platforms on both Windows and Linux. Before this option was only available for .NET Framework.

    +
  • +
  • +

    Global Mutex Locks - Each application acquires a handle to a global mutex controlled by the operating system. But will not work when application doesn't have user-capabilities that allows access to global mutexes (Ex. Mobile platforms like Android / iOS). NLog v6 have moved the logic into NLog.Targets.ConcurrentFile-nuget-package.

    +
  • +
+

NLog v6 has removed support for ConcurrentWrites-option in the standard NLog File-Target. Instead one must use additional nuget-package like Atomic-File-Target or NLog.Targets.ConcurrentFile.

+

It is recommended to enable asynchronous logging as it will reduce the overhead from file locking coordination (Especially when using KeepFileOpen=false and ConcurrentWrites=true).

+

Archive old log files

+

NLog 4.5 makes it easy to setup archive logic to cleanup old files when using dynamic fileName-Layout. You just need to configure maxArchiveFiles and it will automatically perform cleanup.

+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
+            fileName="${basedir}/logs/AppLog.${shortdate}.txt" 
+            maxArchiveFiles="4"
+            archiveAboveSize="10240" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

NLog 4.7 (and newer) adds support for the option MaxArchiveDays. It works like MaxArchiveFiles but instead inspect the timestamp of the files in the archive. They can be combined. Ex. maxArchiveDays="30" maxArchiveFiles="90" (Deletes files older than 30 days or if more than 90 files in archive).

+

Dynamic vs. Static Archive Logic

+

Do not mix "Dynamic FileName Archive Logic" together with "Static FileName Archive Logic" as one will get unexpected archive behavior.

+
    +
  • +

    Dynamic FileName Archive Logic - Enabled by using fileName="${basedir}/AppLog.${shortdate}.log". This means it will roll / archive dynamically because of the layout-renderer-logic in ${date} (Changes on day-change). Never use it together with archiveFileName="..." or archiveEvery="Day".

    +
  • +
  • +

    Static FileName Archive Logic - Enabled by using archiveEvery="Day" and archiveFileName="...". This means it will expect the FileName to be static (Ex. fileName="${basedir}/AppLog.txt"). Never use dynamic layout (Ex. ${date}) in archiveFileName="..." or fileName="...".

    +
  • +
+

Static-filename-archive-logic are well suited for being used with tail-applications, that monitors a single static-filename. But there might be issues when NLog tries to rename/move the old file to create new file (Ex. when locked by external file-viewer). It is possible to move files into a different folder when using static-filename-archive-logic: +- archiveFileName - Can move old files into other folder and also rename with datetime/seq-no

+

There are several FileTarget-Archive-Examples of how to use Static FileName with ArchiveEvery.

+

Per-level log files

+

Single File target can be used to write to multiple files at once. The following configuration will cause log entries for each log level to be written to a separate file, so you will get: + * Trace.log + * Debug.log + * Info.log + * Warn.log + * Error.log + * Fatal.log

+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
+            fileName="${basedir}/${level}.log" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

JSON Log-file

+

The NLog FileTarget can be combined with the JsonLayout to create Json-LogFile:

+
<?xml version="1.0" ?>
+<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="jsonfile" xsi:type="File" fileName="${basedir}/file.json">
+            <layout xsi:type="JsonLayout">
+                <attribute name="time" layout="${date:format=O}" />
+                <attribute name="message" layout="${message}" />
+                <attribute name="logger" layout="${logger}"/>
+                <attribute name="level" layout="${level}"/>
+            </layout>
+        </target>
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="jsonfile" />
+    </rules>
+</nlog>
+
+

CSV Log-file

+

The NLog FileTarget can be combined with the CsvLayout to create comma-separated CSV-LogFile. Here is an example of a file with 4 columns:

+
<?xml version="1.0" ?>
+<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="csvfile" xsi:type="File" fileName="${basedir}/file.csv">
+            <layout xsi:type="CSVLayout">
+                <column name="time" layout="${longdate}" />
+                <column name="message" layout="${message}" />
+                <column name="logger" layout="${logger}"/>
+                <column name="level" layout="${level}"/>
+            </layout>
+        </target>
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="csvfile" />
+    </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/FileContents-layout-renderer/index.html b/wiki/FileContents-layout-renderer/index.html new file mode 100644 index 000000000..5a07b7f7c --- /dev/null +++ b/wiki/FileContents-layout-renderer/index.html @@ -0,0 +1,1323 @@ + + + + + + + + FileContents layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Renders contents of the specified file. Example if having a flat file containing a special setting value.

+
+

Platforms Supported: All (Removed with NLog v6 - Instead setup custom layout-renderer with method-delegate)

+
+

Configuration Syntax

+
${file-contents:encoding=Encoding:fileName=Layout}
+
+

Parameters

+

File Options

+
    +
  • encoding - Encoding used in the file.Encoding
  • +
  • fileName - Name of the file.Layout
  • +
+

Notes

+

If the file content doesn't change, then adding the option :cached=true will give a performance boost.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/FileTarget-Archive-Examples/index.html b/wiki/FileTarget-Archive-Examples/index.html new file mode 100644 index 000000000..9716ba2d3 --- /dev/null +++ b/wiki/FileTarget-Archive-Examples/index.html @@ -0,0 +1,1520 @@ + + + + + + + + FileTarget Archive Examples - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog v4.5 improves dynamic archive mode, so it is easy to archive old files.

+

NLog v6.0 have introduced ArchiveSuffixFormat and obsoleted the following options: +- ArchiveDateFormat +- ArchiveNumbering +- ArchiveFileKind +- ArchiveOldFileOnStartupAboveSize +- EnableArchiveFileCompression

+

These examples shows the archive options for the static-archive-mode. One should Not mix dynamic with static-archive-mode.

+

Size-based file archival

+

Log files can be automatically archived by moving them to another location after reaching certain size. The following configuration will produce +the following files (and generate new file when file reaches 10KB): ++ logs/logfile.txt // the current log being written to ++ archives/log.000000.txt // The oldest log file ++ archives/log.000001.txt ++ archives/log.000002.txt ++ etc.

+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}" 
+            fileName="${basedir}/logs/logfile.txt" 
+            archiveFileName="${basedir}/archives/log.{#####}.txt"
+            archiveAboveSize="10240"
+            archiveNumbering="Sequence" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

Time-based file archival

+

Log files can also be automatically archived based on time. This configuration will archive a file at the beginning of each day and will use rolling file naming, so log file from the previous day can always be found in archives//log.0.txt, log from two days ago is in archives//log.1.txt and so on. This configuration will keep at most 7 archive files, so logs older than one week will be automatically deleted:

+
    +
  • logs/logfile.txt // todays log being written to
  • +
  • archives/log.0.txt // previous log file from yesterday
  • +
  • archives/log.1.txt
  • +
  • archives/log.2.txt
  • +
  • archives/log.3.txt
  • +
  • archives/log.4.txt
  • +
  • archives/log.5.txt
  • +
  • archives/log.6.txt // Oldest file defined by maxArchiveFiles=7
  • +
+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}" 
+            fileName="${basedir}/logs/logfile.txt" 
+            archiveFileName="${basedir}/archives/log.{#}.txt"
+            archiveEvery="Day"
+            archiveNumbering="Rolling"
+            maxArchiveFiles="7" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

Archive every Week

+

You can specify different archival time periods. For example, if you wanted to archive once a week on Tuesdays, +you would set archiveEvery="Tuesday". Possible values for archiveEvery can be found above. This will result in +the following files being created: ++ logfile.txt // the current log being written to ++ logfile.20170307.txt ++ logfile.20170314.txt ++ logfile.20170321.txt ++ etc.

+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}" 
+            fileName="${basedir}/logs/logfile.txt" 
+            archiveFileName="${basedir}/archives/logfile.{#}.txt"
+            archiveEvery="Tuesday"
+            maxArchiveFiles="7" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

Archive Numbering Examples

+

Rolling

+
        <target name="file" xsi:type="File"
+            ...
+            fileName="logfile.txt"
+            archiveFileName="log.{####}.txt"
+            archiveNumbering="Rolling"  />
+
+
+

Example of file names (newest files first):

+
    +
  • logfile.txt
  • +
  • log.0000.txt
  • +
  • log.0001.txt
  • +
  • log.0002.txt
  • +
+

Sequence

+
        <target name="file" xsi:type="File"
+            ...
+            fileName="logfile.txt"
+            archiveFileName="log.{####}.txt"
+            archiveNumbering="Sequence"  />
+
+
+

Example of file names (newest files first):

+
    +
  • logfile.txt
  • +
  • log.0002.txt
  • +
  • log.0001.txt
  • +
  • log.0000.txt
  • +
+

Date

+
        <target name="file" xsi:type="File"
+            ...
+            fileName="logfile.txt"
+            archiveFileName="log.{#}.txt"
+            archiveNumbering="Date"
+            archiveEvery="Day"
+            archiveDateFormat="yyyyMMdd"
+  />
+
+
+

Example of file names (newest files first):

+
    +
  • logfile.txt
  • +
  • log.20150731.txt
  • +
  • log.20150730.txt
  • +
+

DateAndSequence

+
        <target name="file" xsi:type="File"
+            ...
+            fileName="logfile.txt"
+            archiveFileName="log.{#}.txt"
+            archiveNumbering="DateAndSequence"
+            archiveAboveSize="1000"
+            archiveDateFormat="yyyyMMdd"
+  />
+
+
+

Example of file names (newest files first):

+
    +
  • logfile.txt
  • +
  • log.20150730.3.txt
  • +
  • log.20150730.2.txt
  • +
  • log.20150730.1.txt
  • +
+

Archive file in new folder

+

NLog also has support for writing to a static fileName-Layout, and then move the file to archive-location and re-create new fresh file. But it only works when not including dynamic layout (Ex. ${date}) in the fileName-Layout or archiveFileName-Layout. See also Do not mix dynamic-filename with static archive logic

+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
+            fileName="${basedir}/logs/AppLog.txt" 
+            archiveFileName="${basedir}/archives/AppLog.{#}.txt"
+            archiveEvery="Day"
+            maxArchiveFiles="4"
+            archiveAboveSize="10240" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+

It will generate the following filenames (newest first):

+
* AppLog.txt // the current log being written to
+* AppLog.20170321.txt
+* AppLog.20170314.txt
+* AppLog.20170307.txt
+
+

One log file per application instance, remove old logs

+

The following configuration will create a dedicated log file for each start of your application. Multiple instances can run in parallel and write to their respective log file. By adding a timestamp to the filename, each filename is unique (up to the second). Up to ten log files (active + nine archive) are kept. The removal of old logs works, when the archiveFileName contains a placeholder, archiveDateFormat has the same datetime format as in the name property, and archiveNumbering and archiveEvery are enabled. The $(cached:...) directive prevents that a new log file name is generated for every log entry. Log files will be named: + * 2017-11-05 08_00_00.log + * 2017-11-05 08_00_01.log + * 2017-11-05 12_35_04.log + * 2017-11-06 09_54_32.log + * ...

+
<?xml version="1.0" ?>
+<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="file" xsi:type="File"
+            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
+            fileName="${basedir}/logs/${cached:${date:format=yyyy-MM-dd HH_mm_ss}}.log"
+            archiveFileName="${basedir}/{#}.log"
+            archiveDateFormat="yyyy-MM-dd HH_mm_ss"
+            archiveNumbering="Date"
+            archiveEvery="Year"
+            maxArchiveFiles="9" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="file" />
+    </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Filesystem-Normalize-Layout-Renderer/index.html b/wiki/Filesystem-Normalize-Layout-Renderer/index.html new file mode 100644 index 000000000..443cf9edb --- /dev/null +++ b/wiki/Filesystem-Normalize-Layout-Renderer/index.html @@ -0,0 +1,1327 @@ + + + + + + + + Filesystem Normalize Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Filters characters not allowed in the file names by replacing them with safe character.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${filesystem-normalize:fSNormalize=Boolean:inner=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:fSNormalize=Boolean}
+
+

Parameters

+

Advanced Options

+
    +
  • fSNormalize - Indicates whether to modify the output of this renderer so it can be used as a part of file path (illegal characters are replaced with '_'). Boolean Default: True
  • +
+

Transformation Options

+
    +
  • inner - Wrapped layout. Layout
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Filtering-log-messages/index.html b/wiki/Filtering-log-messages/index.html new file mode 100644 index 000000000..a2e584c6f --- /dev/null +++ b/wiki/Filtering-log-messages/index.html @@ -0,0 +1,1422 @@ + + + + + + + + Filtering log messages - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Log messages may be filtered via either routing or filtering.

+

Routing

+

Logging Rules is the most efficient way to perform filtering using the name of the Logger. By skipping the allocation of LogEventInfo-objects, when no output is needed.

+

One can silence a noisy loggger by redirecting it to a "blackhole" by not specifying writeTo= for the logging-rule. But if also needing custom filter logic, then one needs to use a Null target.

+
+

NLog 4.5 made it possible to specify empty writeTo="", but when using older versions then Null target must be used.

+
+
<rules>
+   <!-- ignore events written that are written to a logger which starts with "Namespace." -->
+   <logger name="Namespace.*" minlevel="Trace" final="true" /> <!-- BlackHole that swallows everything -->
+   <logger name="Namespace.*" maxLevel="Info" final="true" />  <!-- BlackHole that swallows non-critical -->
+</rules>
+
+

NLog v5 introduced the FinalMinLevel-option, because MaxLevel was causing a lot of headache and confusion.

+
<rules>
+   <!-- ignore events written that are written to a logger which starts with "Namespace." -->
+   <logger name="Namespace.*" finalMinLevel="Off" /> <!-- BlackHole that swallows everything -->
+   <logger name="Namespace.*" finalMinLevel="Warn" />  <!-- BlackHole that swallows non-critical -->
+</rules>
+
+

Filters

+

With the use of <filters> then you can inspect the actual log-events and decide to ignore (blacklist) and/or allow (whitelist) the events. See also <when> filter.

+

e.g.

+
<logger name="*" writeTo="file">
+  <filters defaultAction="Log">
+    <when condition="length('${message}') > 100" action="Ignore" />
+  </filters>
+</logger>
+
+

The defaultAction-option was introduced with NLog 4.6. Before NLog 5.0 then the default value was Neutral.

+

Note filters gives a performance penalty, because NLog LogEventInfo objects will be allocated upfront even if discarded by filter-result.

+

Example in C

+

The above configuration can be implemented directly in C# like this:

+
var config = LogManager.Configuration;
+
+// some target
+var fileTarget = new FileTarget();
+
+// set-up rule with filter
+var loggingRule = new LoggingRule("*", fileTarget);
+loggingRule.FilterDefaultAction = FilterResult.Log;
+loggingRule.Filters.Add(new ConditionBasedFilter()
+{
+    Condition = "length('${message}') > 100",
+    Action = FilterResult.Ignore
+});
+config.LoggingRules.Add(loggingRule);
+
+// apply config
+LogManager.Configuration = config;
+
+

With NLog 5.0 then one can also do this:

+
NLog.LogManager.Setup().LoadConfiguration(builder => {
+   builder.ForLogger().FilterDynamicIgnore(evt => evt.FormattedMessage?.Length > 100).WriteToFile("log.txt");
+});
+
+

Global Threshold

+

LogManager.GlobalThreshold can be assigned a LogLevel, and then only LogEvents with same severity (or higher) will be logged.

+

LogManager.GlobalThreshold will overrule the configuration of logging rules. If logging rules says minLevel="Debug" then LogManager.GlobalThreshold = LogLevel.Error will still win.

+
if (IsProduction)
+   NLog.LogManager.GlobalThreshold = NLog.LogLevel.Info;
+else
+   NLog.LogManager.GlobalThreshold = NLog.LogLevel.Trace;  // No global filter
+
+

Null Logger

+

LogManager.CreateNullLogger() will return a Logger-instance that will not generate any output.

+

This can be used to silence certain components without depending on the NLog-configuration.

+
var logger = IsProduction ? LogManager.CreateNullLogger() : LogManager.GetCurrentClassLogger();
+logger.Info("No output when in production");
+
+

DEBUG build only

+

The .NET compiler has the ability to remove DEBUG-code when making Release-build. This means only Debug-build will give output, when using these conditional logging methods: +- Logger.ConditionalTrace - Performs logging using NLog LogLevel.Trace +- Logger.ConditionalDebug - Performs logging using NLog LogLevel.Debug

+
_logger.ConditionalDebug("DEBUG build only output");
+
+

It is shorthand of doing this:

+
#if DEBUG
+_logger.Debug("DEBUG build only output");
+#endif
+
+

Semi Dynamic Routing Rules

+

Routing rules are more efficient than using dynamic filters, and the performance comes from static nature of the rules. NLog 4.6.7 introduced the ability to use Layout-logic for controlling LogLevel in the logging-rules, that can be explicitly refreshed.

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

Then NLog 4.6.7 allows you to do this:

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

It is possible to disable logging output completely by using minLevel="Off" for the logging-rule.

+

Possible use-case could be to activate special debug-mode, that changes the loglevel-variable as shown above, and then schedules a timer to restore default-level to "Warn" after 5 mins.

+

Environment Specific Filtering

+

There is a dedicated wiki-page for how to setup Environment specific NLog Logging Configuration so Production- and Development-environment can have different output-levels and destination targets.

+

Fully Dynamic Filtering

+

The Semi Dynamic Routing Rules improves the combination of NLog configuration loaded from config-file, and adjusting NLog configuration at runtime.

+

When NLog configuration is created at runtime alone, then one have access to even more dynamic filtering logic capabilities. Ex. by using NLog.Filters.WhenMethodFilter:

+
config.LoggingRules.Last().Filters.Add(new WhenMethodFilter(logEvent => ShouldIgnoreLogEvent(logEvent) ? FilterResult.Ignore : FilterResult.Log));
+
+

It is also possible to use the NLog.Config.LoggingRule constructor that specifies RuleName. Where it is possible to lookup the LoggingRule using LoggingConfiguration.FindRuleByName when needing to adjust it.

+

Deprecated filters

+

These filters are deprecated. They have been replace by the <when> filter, which exposes uses modifiable conditions for filtering log events.

+ + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/FilteringWrapper-target/index.html b/wiki/FilteringWrapper-target/index.html new file mode 100644 index 000000000..6bb3edcd1 --- /dev/null +++ b/wiki/FilteringWrapper-target/index.html @@ -0,0 +1,1358 @@ + + + + + + + + FilteringWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Filters log entries based on a condition.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+

Filtering using condition:

+
<targets>
+  <target xsi:type="FilteringWrapper" name="String" condition="Condition">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Filtering using filter (Introduced with NLog 4.6.4):

+
<targets>
+  <target xsi:type="FilteringWrapper" name="default">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+    <filter xsi:type="whenRepeated" layout="${message}" timeoutSeconds="30" action="Ignore" />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Filtering Options

+
    +
  • condition - Condition Expression. Log events who meet this condition will be forwarded to the wrapped target. Condition Required, unless having specified a filter.
  • +
  • filter - Filter expression. For complex filtering logic like WhenRepeated-Filter.
    +

    Introduced with NLog 4.6.4

    +
    +
  • +
+

Examples

+

Repeat filter

+

Filter repeated LogEvents, so it will only send mail every 5 minutes (Introduced with NLog 4.6.4):

+
 <nlog>
+    <targets>
+      <target xsi:type="FilteringWrapper" name="filter-mail">
+        <target xsi:type="Mail" name="instant-mail">
+          <subject>${exception:format=Type}</subject>
+        </target>
+        <filter type="whenRepeated" layout="${exception:format=Type}" timeoutSeconds="300" action="Ignore" />
+      </target>
+    </targets>
+    <rules>
+        <logger name='*' minlevel='Debug' writeTo='filter-mail'/>
+    </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Fluent-API/index.html b/wiki/Fluent-API/index.html new file mode 100644 index 000000000..a56115336 --- /dev/null +++ b/wiki/Fluent-API/index.html @@ -0,0 +1,1361 @@ + + + + + + + + Fluent API - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog v5 supports fluent API: +- Fluent-Logger-API - Build LogEvents using a fluent C# API. +- Fluent-Configuration-API - Build Configuration using a fluent C# API.

+

Legacy Fluent API

+
+

⚠️ The original NLog.Fluent-namespace introduced with NLog v3.2 became obsolete with NLog v5

+
+

Writing info message via fluent API.

+
using NLog.Fluent;
+
+_logger.Info()
+       .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
+       .Property("Test", "InfoWrite")
+       .Write();
+
+

Writing error message.

+
try
+{
+    string text = File.ReadAllText(path);
+}
+catch (Exception ex)
+{
+    _logger.Error()
+           .Message("Error reading file '{0}'.", path)
+           .Exception(ex)
+           .Property("Test", "ErrorWrite")
+           .Write();
+}
+
+

Caller Info

+

Use the static Log class so you don't have to include loggers in all of classes. The static Log class using .net 4.5 caller info to get the logger from the file name.

+

Writing info message via static Log class with fluent API.

+
Log.Info()
+   .Message("This is a test fluent message.")
+   .Property("Test", "InfoWrite")
+   .Write();
+
+

Writing error message.

+
try
+{
+    string text = File.ReadAllText(path);
+}
+catch (Exception ex)
+{
+    Log.Error()
+        .Message("Error reading file '{0}'.", path)
+        .Exception(ex)
+        .Property("Test", "ErrorWrite")
+        .Write();
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Fluent-Configuration-API/index.html b/wiki/Fluent-Configuration-API/index.html new file mode 100644 index 000000000..ee23011a3 --- /dev/null +++ b/wiki/Fluent-Configuration-API/index.html @@ -0,0 +1,1432 @@ + + + + + + + + Fluent Configuration API - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The NLog Fluent Configuration API allows you to configure NLog directly in C# instead of XML.

+
    +
  • No XML required. No separate configuration file required.
  • +
  • Explicit setup logging as part of application startup
  • +
  • Compile-time checking
  • +
  • Full access to NLog features
  • +
  • Allow building reusable components or libraries with addtional NLog extensions.
  • +
+

The NLog LogFactory has support for fluent setup of the initial NLog configuration: +- LoadConfiguration - Explicit build/adjust NLog config. Introduced with NLog 4.7 but heavily improved with NLog 5.0 +- SetupExtensions - Registration of NLog extensions before loading configuration. Introduced with NLog 4.7 +- SetupSerialization - Override default log output for specific object types. Introduced with NLog 4.7 +- SetupLogFactory - LogFactory specific options. Introduced with NLog 5.0 +- SetupInternalLogger - InternalLogger specific options. Introduced with NLog 4.7 +- LoadConfigurationFromFile - For loading NLog config from specific xml file. Introduced with NLog 4.7 +- LoadConfigurationFromXml - For loading NLog config from xml content. Introduced with NLog 4.7

+

Example with LoadConfiguration

+

Build NLog config that writes everything to console:

+
NLog.LogManager.Setup().LoadConfiguration(builder => {
+   builder.ForLogger().WriteToConsole()
+});
+
+

Build NLog config that writes to file and console:

+
NLog.LogManager.Setup().LoadConfiguration(builder => {
+   builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole();
+   builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: "App_${shortdate}.txt");
+});
+
+

Build NLog config that writes to custom target::

+
NLog.LogManager.Setup().LoadConfiguration(builder => {
+   builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteTo(new MyCustomTarget() { Layout = "${message}" });
+});
+
+

Build NLog config that restricts output from noisy logger:

+
NLog.LogManager.Setup().LoadConfiguration(builder => {
+   builder.ForLogger("Microsoft.*").WriteToNil(finalMinLevel: LogLevel.Warn);
+   builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole();
+});
+
+

Example with SetupExtensions

+

To register a custom LayoutRenderer:

+
NLog.LogManager.Setup().SetupExtensions(ext =>
+   ext.RegisterLayoutRenderer("trace_id", (logevent) => CorrelationIdentifier.TraceId.ToString())
+);
+
+

To register a custom Target:

+
NLog.LogManager.Setup().SetupExtensions(ext =>
+   ext.RegisterTarget<MyNamespace.MyFirstTarget>("MyFirst")
+);
+
+

Example with SetupSerialization

+

Override the default object reflection for System.Net.WebException:

+
NLog.LogManager.Setup().SetupSerialization(s =>
+   s.RegisterObjectTransformation<System.Net.WebException>(ex => new {
+      Type = ex.GetType().ToString(),
+      Message = ex.Message,
+      StackTrace = ex.StackTrace,
+      Source = ex.Source,
+      InnerException = ex.InnerException,
+      Status = ex.Status,
+      Response = ex.Response.ToString(),  // Call your custom method to render stream as string
+   })
+);
+
+

Skip default object reflection for ReadOnlyMemory<byte>:

+
NLog.LogManager.Setup().SetupSerialization(s =>
+   s.RegisterObjectTransformation<ReadOnlyMemory<byte>>(obj => obj.Length)
+);
+
+

Examples with SetupLogFactory

+

Explicit configure the global NLog TimeSource:

+
NLog.LogManager.Setup().SetupLogFactory(fac =>
+   fac.SetTimeSourcAccurateUtc()
+);
+
+

Explicit activate exceptions on configuration errors:

+
NLog.LogManager.Setup().SetupLogFactory(fac =>
+   fac.SetThrowConfigExceptions(true)
+);
+
+

Explicit configure the global LogLevel threshold:

+
NLog.LogManager.Setup().SetupLogFactory(fac =>
+   fac.SetGlobalThreshold(LogLevel.Info)
+);
+
+

Example with SetupInternalLogger

+

Write internal warnings and errors to console output:

+
NLog.LogManager.Setup().SetupExtensions(intern =>
+   intern.SetMinimumLogLevel(LogLevel.Warn).LogToConsole(true)
+);
+
+

Register event handler to be called on warnings and errors:

+
NLog.LogManager.Setup().SetupExtensions(intern =>
+   intern.SetMinimumLogLevel(LogLevel.Warn).AddLogSubscription((sender, evt) => ReportEvent(evt.Message))
+);
+
+

Example with LoadConfigurationFromAppSettings

+

Loads NLog config from appsettings.json (with fallback to NLog.confg) and requires NLog.Web.AspNetCore:

+
var logger = LogManager.Setup()
+                       .LoadConfigurationFromAppSettings()
+                       .GetCurrentClassLogger();
+
+

See also NLog configuration with appsettings.json

+

Example with LoadConfigurationFromSection

+

Loads NLog config from Microsoft Configuration Section, and requires NLog.Extensions.Logging:

+
var config = new ConfigurationBuilder()
+                .SetBasePath(basePath ?? Directory.GetCurrentDirectory())
+                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
+                .AddJsonFile($"appsettings.{environment}.json", optional: true)
+                .AddEnvironmentVariables().Build();
+var logger = LogManager.Setup()
+                       .LoadConfigurationFromSection(config)
+                       .GetCurrentClassLogger();
+
+

See also NLog configuration with appsettings.json

+

Example with LoadConfigurationFromFile

+

Ensure NLog config has been loaded, and fail with exception when not:

+
NLog.LogManager.Setup().LoadConfigurationFromFile(optional: false);
+
+

Example with LoadConfigurationFromXml

+

Load NLog config from custom location (like assembly resource):

+
var fileXmlContent = File.ReadAllText(xmlFilePath);
+NLog.LogManager.Setup().LoadConfigurationFromXml(fileXmlContent);
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Fluent-Logger-API/index.html b/wiki/Fluent-Logger-API/index.html new file mode 100644 index 000000000..7a287c56a --- /dev/null +++ b/wiki/Fluent-Logger-API/index.html @@ -0,0 +1,1344 @@ + + + + + + + + Fluent Logger API - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Fluent Logger API

+

NLog 5.0 introduces new fluent LogEventBuilder that can be activated with one of these extensions methods for ILogger:

+
    +
  • ForLogEvent - Builds base LogEvent
  • +
  • ForTraceEvent - Builds LogEvent with Trace-LogLevel
  • +
  • ForDebugEvent - Builds LogEvent with Debug-LogLevel
  • +
  • ForInfoEvent - Builds LogEvent with Info-LogLevel
  • +
  • ForWarnEvent - Builds LogEvent with Warn-LogLevel
  • +
  • ForErrorEvent - Builds LogEvent with Error-LogLevel
  • +
  • ForFatalEvent - Builds LogEvent with Fatal-LogLevel
  • +
  • ForExceptionEvent - Builds LogEvent with Exception and Error-LogLevel
  • +
+

To complete the fluent builder then call Log() to capture available callsite information with help from Caller Member Attributes, and then writes the actual LogEvent to any configured NLog targets.

+
+

Replaces the old Fluent-namespace and also reduces memory-allocation when LogLevel not enabled.

+
+

Examples

+

Writing Info Message

+
_logger.ForInfoEvent()
+       .Message("This is a fluent message {0}.", "test")
+       .Property("PropertyName", "PropertyValue")
+       .Log();
+
+

Writing Exception Message.

+
try
+{
+    string text = File.ReadAllText(path);
+}
+catch (Exception ex)
+{
+    _logger.ForExceptionEvent(ex)
+           .Message("Error reading file '{0}'.", path)
+           .Property("Test", "InfoWrite")
+           .Log();
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/FormControl-target/index.html b/wiki/FormControl-target/index.html new file mode 100644 index 000000000..4c5852f92 --- /dev/null +++ b/wiki/FormControl-target/index.html @@ -0,0 +1,1307 @@ + + + + + + + + FormControl target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+ +
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/GELF-Target/index.html b/wiki/GELF-Target/index.html new file mode 100644 index 000000000..2c4d0437c --- /dev/null +++ b/wiki/GELF-Target/index.html @@ -0,0 +1,1490 @@ + + + + + + + + GELF Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to the remote instance of Graylog Server using Graylog Extended Log Format (GELF).

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network

+
+

This target inherits from the Network Target, and so it has also all the properties of the Network Target available. Using the GelfLayout to produce GELF JSON output.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Gelf"
+          name="String"
+          address="Layout">
+    <gelffield name="String" layout="Layout" /><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Payload Options

+
    +
  • +

    layout - Instance of GelfLayout that is used to format log messages. Layout Default: GelfLayout

    +
  • +
  • +

    GelfHostName - Graylog Message Host-field. Default = ${hostname}

    +
  • +
  • +

    GelfShortMessage - Graylog Message Short-Message-field (Truncates when longer than 250 chars). Default = ${message}

    +
  • +
  • +

    GelfFullMessage - Graylog Message Full-Message-field. Default = ${message}

    +
  • +
  • +

    GelfFacility - Legacy Graylog Message Facility-field. Default = null

    +
  • +
  • +

    IncludeEventProperties - Include all properties from the log events. Default = true.

    +
  • +
  • +

    IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false.

    +
  • +
  • +

    ExcludeEmptyProperties - Exclude null/empty properties. Default = false.

    +
  • +
  • +

    ExcludeProperties - Comma separated string with names which properties to exclude.

    +
  • +
  • +

    IncludeProperties - Comma separated string with names which properties to explicitly include.

    +
  • +
  • +

    GelfField

    +
  • +
  • name - Required. The name of the JSON-key
  • +
  • +

    layout - The layout for the JSON-value (Can be a nested JsonLayout)

    +
  • +
  • +

    encoding - Encoding to be used. Encoding Default: utf-8

    +
  • +
  • +

    newLine - Indicates whether to append newline at the end of log message. Boolean Default: False

    +
  • +
  • +

    lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF. Not used if newLine is false. +Possible values:

    +
  • +
  • CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default)
  • +
  • CR - Carriage Return (ASCII 13).
  • +
  • LF - Line Feed (ASCII 10).
  • +
  • NULL - Null terminator (ASCII 0)
  • +
  • +

    None - No end of line characters.

    +
  • +
  • +

    maxMessageSize - Maximum message size in bytes. Integer Default: 65000

    +
  • +
  • +

    onOverflow - Action that should be taken if the message-size is larger than maxMessageSize. +Possible values:

    +
  • +
  • Discard - Discard the entire message.
  • +
  • Error - Report an error.
  • +
  • Split - Split the message into smaller pieces (Default)
  • +
+

Connection Options

+
    +
  • address - Network address. Layout +The network address can be:
  • +
  • tcp://host:port - TCP (auto select IPv4/IPv6)
  • +
  • tcp4://host:port - force TCP/IPv4
  • +
  • tcp6://host:port - force TCP/IPv6
  • +
  • udp://host:port - UDP (auto select IPv4/IPv6)
  • +
  • udp4://host:port - force UDP/IPv4
  • +
  • udp6://host:port - force UDP/IPv6
  • +
  • http://host:port/pageName - HTTP using POST verb
  • +
  • +

    https://host:port/pageName - HTTPS using POST verb

    +
  • +
  • +

    keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True

    +
  • +
  • +

    connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5

    +
  • +
  • +

    maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16. Not used if keepConnection is true.

    +
  • +
  • +

    onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections.

    +
  • +
+

Possible enum values: + * Discard - Discard new messages when reaching limit (Default) + * Grow - Send message and ignore limit + * Block - Block until pending connections has been freed.

+
    +
  • +

    maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer. Default: 10000

    +
  • +
  • +

    onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize.

    +
  • +
  • Discard - Discard the entire message (Default)
  • +
  • Grow - Ignore limit and grow the queue.
  • +
  • +

    Block - Block until queue is below limit.

    +
  • +
  • +

    KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true.

    +
  • +
  • +

    sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. + Possible values (combination allowed, comma separated):

    +
  • +
  • None - No SSL/TLS is used
  • +
  • Default - Accepts Tls or Ssl3
  • +
  • Ssl2 - really not recommended
  • +
  • Ssl3 - not recommended
  • +
  • Tls - TLS 1.0
  • +
  • Tls11 - TLS 1.1
  • +
  • +

    Tls12 - TLS 1.2

    +
  • +
  • +

    SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation)

    +
  • +
  • +

    SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile

    +
  • +
  • +

    SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine)

    +
    +

    Introduced in NLog.Targets.Network v6.1.6

    +
    +
  • +
+

Example

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <extensions>
+    <add assembly="NLog.Targets.Network"/>
+  </extensions>
+
+  <targets>
+    <target name="graylog" xsi:type="gelf" address="http://localhost:12201/gelf" />
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="graylog" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/GZip-File-Target/index.html b/wiki/GZip-File-Target/index.html new file mode 100644 index 000000000..a4187b1df --- /dev/null +++ b/wiki/GZip-File-Target/index.html @@ -0,0 +1,1349 @@ + + + + + + + + GZip File Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes LogEvents to file using GZip compression, by extending the standard NLog File Target.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.GZipFile

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="GZipFile"
+          name="string"
+          fileName="Layout"
+          layout="Layout"
+          compressionLevel="CompressionLevel"
+          keepFileOpen="boolean"
+          enableArchiveFileCompression="boolean"
+          archiveOldFileOnStartup="boolean"
+  />
+</targets>
+
+

Parameters

+
    +
  • fileName - Name of the file to write to. Layout Required.
  • +
  • layout - Text to be rendered. Layout Required.
    +

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

    +
    +
  • +
  • compressionLevel - File compression level
  • +
  • Optimal - Optimize for small file size
  • +
  • Fastest - Optimize for speed
  • +
  • NoCompression - Disables GZip compression
  • +
  • keepFileOpen - Disables GZip compression when configured to false. Default: true
  • +
  • archiveOldFileOnStartup - Disables GZip compression when configured to false. Default: true
  • +
+

Also inherits all parameters from the standard File-Target.

+

Tools

+

Linux has the zutils to make it easier to view / tail GZip compressed log-files: +| Tool | Description | Example | +|-------|--------------|----------| +| zcat | Decompresses and copies files to standard output. | zcat <path_to_gzipped_log_file> | +| zgrep | Decompresses and searches files for a regular expression. | zgrep -i <path_to_gzipped_log_file> | +| zless | Decompresses and view in pages. | zless <path_to_gzipped_log_file> | +| zmore | Decompresses and view in pages. | zmore <path_to_gzipped_log_file> | +| ztest | Tests integrity of compressed files. | zcat <path_to_gzipped_log_file> |

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Gc-layout-renderer/index.html b/wiki/Gc-layout-renderer/index.html new file mode 100644 index 000000000..71cdcbcbb --- /dev/null +++ b/wiki/Gc-layout-renderer/index.html @@ -0,0 +1,1336 @@ + + + + + + + + Gc layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The information about the garbage collector.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${gc:property=Enum}
+
+

Parameters

+

Rendering Options

+
    +
  • property - Property to retrieve. Default: TotalMemory
    + Possible values:
  • +
  • CollectionCount0 - The number of Gen0 collections.
  • +
  • CollectionCount1 - The number of Gen1 collections.
  • +
  • CollectionCount2 - The number of Gen2 collections.
  • +
  • MaxGeneration - Maximum generation number supported by GC.
  • +
  • TotalMemory - Managed heap size in bytes (ignoring memory fragmentation).
  • +
  • TotalMemoryForceCollection - Managed heap size in bytes (after having forced full garbage collection) + > Marked obsolete with NLog v6.2 since method is not recommended, because of the application wide side-effects.
  • +
  • +

    WorkingSet - Physical memory used by the process both managed and unmanaged/native memory. + > Introduced with NLog v6.2

    +
  • +
  • +

    Format - The ToString(...) format-specifier. Ex. "N0" to output 1000-delimiter to be easier on the eye. + > Introduced with NLog v6.2

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Gdc-layout-renderer/index.html b/wiki/Gdc-layout-renderer/index.html new file mode 100644 index 000000000..b425be82b --- /dev/null +++ b/wiki/Gdc-layout-renderer/index.html @@ -0,0 +1,1367 @@ + + + + + + + + Gdc layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Global Diagnostic Context (GDC) - Dictionary structure for global settings for the entire application-instance.

+
+

Platforms Supported: All (NLog 4.1 allows storing any Object type, not just String)

+
+

GDC properties should be assigned at application-startup and remain static and immutable during the lifetime of the application/process. Do NOT modify the GDC as part of the logging operations, as it will have unwanted side-effects. If needing to include additional context information for a specific logevent, then consider using Logger.WithProperty() or Logger.PushScopeProperty(). See also NLog Context.

+

NLog also supports alternative locations for global state like Environment Variables, AppSettings.json, etc. See also Environment-specific-NLog-Logging-Configuration

+

Configuration Syntax

+
${gdc:item=String}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Name of the item. Required. Note Before NLog 5.0 it was case-sensitive.
  • +
  • culture - The culture used for rendering. Introduced in NLog 5.0. Default value is CultureInfo.InvariantCulture
  • +
  • format - Format for conversion from object to string. Introduced in NLog 4.5.
  • +
  • format=@ means serialize object properties into Json-format.
  • +
+

Example

+

Simple Properties

+

The following example demonstrates the basic usage of the Global Diagnostics Context.

+
GlobalDiagnosticsContext.Set("myDataBase","someValue");
+GlobalDiagnosticsContext.Set("informationGroup", new { One = 1, Two = 2 });
+GlobalDiagnosticsContext.Set("anyObject", anyObjectReferenceOrString);
+
+

Add the following to your logger configuration to reference the above properties:

+
${gdc:item=myDatabase}
+${gdc:item=informationGroup}
+${gdc:item=anyObject}
+
+

Dynamic Properties

+

The Global Diagnostics Context (GDC) can also store complex objects, and can be used as an alternative to registering own custom layout renderer. NLog sees the GDC like global variables that doesn't depend on thread execution context, so make sure any complex object logic doesn't depend on application logging thread-state.

+
public class ApplicationStateProperty : IFormattable
+{
+   public static readonly ApplicationStateProperty Default = new ApplicationStateProperty();
+
+   private ApplicationStateProperty() 
+   {
+   }
+
+   public override string ToString()
+   {
+      // Physical memory used by application process (in megabytes)
+      return ((long)(System.Environment.WorkingSet / (1024 * 1024))).ToString();
+   }
+
+   string IFormattable.ToString(string format, IFormatProvider formatProvider)
+   {
+      return ToString();
+   }
+}
+
+

During initialization, add the following code:

+
GlobalDiagnosticsContext.Set("AppMemorySize", ApplicationStateProperty.Default);
+
+

To reference the AppMemorySize Global Diagnostics Context property.

+
${gdc:item=AppMemorySize}
+
+

Notes

+

When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/GelfLayout/index.html b/wiki/GelfLayout/index.html new file mode 100644 index 000000000..b5a08f9ae --- /dev/null +++ b/wiki/GelfLayout/index.html @@ -0,0 +1,1353 @@ + + + + + + + + GelfLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders to Graylog Extended Log Format (GELF) which produces JSON output.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network

+
+
<target name="jsonFile" xsi:type="File" fileName="gelf-file.json" >
+      <layout xsi:type="GelfLayout" includeEventProperties="Boolean" excludeProperties="Comma-separated list (string)">
+              <GelfField name="threadid" layout="${threadid}" />
+       </layout>
+</target>
+
+

Layout Options

+
    +
  • +

    GelfHostName - Graylog Message Host-field. Default = ${hostname}

    +
  • +
  • +

    GelfShortMessage - Graylog Message Short-Message-field (Truncates when longer than 250 chars). Default = ${message}

    +
  • +
  • +

    GelfFullMessage - Graylog Message Full-Message-field. Default = ${message}

    +
  • +
  • +

    GelfFacility - Legacy Graylog Message Facility-field. Default = null

    +
  • +
  • +

    IncludeEventProperties - Include all properties from the log events. Default = true.

    +
  • +
  • +

    IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false.

    +
  • +
  • +

    ExcludeEmptyProperties - Exclude null/empty properties. Default = false.

    +
  • +
  • +

    ExcludeProperties - Comma separated string with names which properties to exclude.

    +
  • +
  • +

    IncludeProperties - Comma separated string with names which properties to explicitly include.

    +
  • +
  • +

    GelfField

    +
  • +
  • name - Required. The name of the JSON-key
  • +
  • layout - The layout for the JSON-value (Can be a nested JsonLayout)
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Getting-started-with-.NET-Core-2---Console-application/index.html b/wiki/Getting-started-with-.NET-Core-2---Console-application/index.html new file mode 100644 index 000000000..1ec753cff --- /dev/null +++ b/wiki/Getting-started-with-.NET-Core-2---Console-application/index.html @@ -0,0 +1,1428 @@ + + + + + + + + Getting started with .NET Core 2 Console application - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ + +
+

Description

+

Explains how to setup NLog as logging provider for .NET Core and Microsoft Extension Logging (MEL).

+

Notice that NLog can be used on .NET Core without help from Microsoft Extension Logging and NLog.Extension.Hosting. See standard NLog Tutorial.

+

0. Create a new .NET Core console project

+

In Visual Studio 2017, using .NET 4.6.1+ or .NET Core 2

+

image

+

1. Add dependency in csproj manually or using NuGet

+

Install:

+ +

e.g.

+
  <ItemGroup>
+    <PackageReference Include="NLog" Version="5.4.0" />
+    <PackageReference Include="NLog.Extensions.Logging" Version="5.4.0" />
+  </ItemGroup>
+
+

2. Create a nlog.config file.

+

Create nlog.config (lowercase all) file in the root of your application project (File Properties: Copy Always)

+

We use this example:

+
<?xml version="1.0" encoding="utf-8" ?>
+<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
+<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"
+      autoReload="true"
+      internalLogFile="c:\temp\console-example-internal.log"
+      internalLogLevel="Info" >
+
+  <!-- the targets to write to -->
+  <targets>
+    <!-- write logs to file -->
+    <target xsi:type="File" name="logfile" fileName="c:\temp\console-example.log"
+            layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
+    <target xsi:type="Console" name="logconsole"
+            layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
+  </targets>
+
+  <!-- rules to map from logger name to target -->
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="logfile,logconsole" />
+  </rules>
+</nlog>
+
+

For an introduction to the NLog.config-file then see the NLog Tutorial, and for more detailed information then see here.

+

Ensure to configure your project-file to copy NLog.config to the output directory:

+
 <ItemGroup>
+     <None Update="nlog.config" CopyToOutputDirectory="Always" />
+ </ItemGroup>
+
+

3. Update your program

+

3.1 Create your runner class

+
 public class Runner
+ {
+     private readonly ILogger<Runner> _logger;
+
+     public Runner(ILogger<Runner> logger)
+     {
+         _logger = logger;
+     }
+
+     public void DoAction(string name)
+     {
+         _logger.LogDebug(20, "Doing hard work! {Action}", name);
+     }
+ }
+
+

3.2 Setup Microsoft Logging with Dependency Injection

+
using Microsoft.Extensions.Logging;
+using NLog;
+using NLog.Extensions.Logging;
+
+static void Main(string[] args)
+{
+   // Disposing the ServiceProvider will also flush / dispose / shutdown the NLog Logging Provider
+   using var servicesProvider = new ServiceCollection()
+      .AddTransient<Runner>() // Runner is the custom class
+      .AddLogging(loggingBuilder =>
+      {
+         // Setup NLog for logging
+         loggingBuilder.ClearProviders();
+         loggingBuilder.AddNLog();
+      }).BuildServiceProvider();
+
+   var runner = servicesProvider.GetRequiredService<Runner>();
+   runner.DoAction("Action1");
+
+   Console.WriteLine("Press ANY key to exit");
+   Console.ReadKey();
+}
+
+

4 Example output

+

On screen:

+

image

+

In file:

+
2017/10/16 23:08:46.479|DEBUG|Doing hard work! Action1 |ConsoleExample.Runner|Action=Action1, EventId_Id=20, EventId_Name=, EventId=20
+
+
+

ℹ️ See also example in GitHub

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Getting-started-with-.NET-Core-Console-application/index.html b/wiki/Getting-started-with-.NET-Core-Console-application/index.html new file mode 100644 index 000000000..7331cd430 --- /dev/null +++ b/wiki/Getting-started-with-.NET-Core-Console-application/index.html @@ -0,0 +1,1377 @@ + + + + + + + + Getting started with .NET Core Console application - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +

NLog integrates with the built-in Microsoft.Extensions.Logging (MEL) infrastructure. Application code continues to use ILogger<T>, while NLog handles log routing, formatting, and writing to configured targets.

+

This guide shows how to configure NLog as a logging provider for a .NET console application.

+

1. Install NLog

+

Install the NLog.Extensions.Logging NuGet package:

+
+

dotnet add package NLog.Extensions.Logging

+
+

2. Register NLog Logging Provider

+

Create a LoggerFactory and include AddNLog():

+
using Microsoft.Extensions.Logging;
+using NLog.Extensions.Logging;
+
+using var loggerFactory = LoggerFactory.Create(builder =>
+{
+    // Remove default Microsoft logging providers
+    builder.ClearProviders();
+    // Register NLog
+    builder.AddNLog();
+});
+
+var logger = loggerFactory.CreateLogger<Program>();
+logger.LogInformation("Application started.");
+
+

AddNLog() registers NLog as the logging provider for the Microsoft.Extensions.Logging LoggerFactory. From this point log messages will be processed by NLog.

+

3. Configure NLog

+

NLog supports several configuration approaches:

+ +

This guide uses an NLog.config XML file as the configuration example, but the alternatives above also work. Create a file named NLog.config in the application project root directory and add the following content:

+
<?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"
+      throwConfigExceptions="true"
+      autoReload="true">
+  <targets async="true">
+    <target xsi:type="Console" name="console" layout="${MicrosoftConsoleLayout}" />
+
+    <target xsi:type="File" name="file" fileName="logs/app-${shortdate}.log" maxArchiveFiles="7">
+      <layout>${longdate}|${level}|${message}|${all-event-properties} ${exception:format=tostring}</layout>
+    </target>
+  </targets>
+  <rules>
+    <!-- Reduce noise from .NET Core Host, and route relevant logging to output targets -->
+    <logger name="System.*" finalMinLevel="Warning" />
+    <logger name="Microsoft.*" finalMinLevel="Warning" />
+    <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" />
+    <logger name="*" minLevel="Info" writeTo="console,file" />
+  </rules>
+</nlog>
+
+

This configuration includes:

+
    +
  • Targets — Define output destinations for writing log messages. See NLog Targets
  • +
  • Rules — Define how log messages are routed from loggers to output targets.
  • +
  • Layout — Define how log messages are formatted. See NLog Layouts
  • +
  • Layout Renderers - Provide additional details to include in log output. See NLog Layout Renderers
  • +
+

The Console-target ensures that .NET Core hosting lifetime startup messages are available on the console. The file-target uses a simple layout, but the layout can be changed to JSON to capture structured logging properties and trace context (TraceId and SpanId) to correlate logs with traces in distributed systems.

+

Ensure that the NLog.config file is copied to the output directory when building or publishing the application. In Visual Studio, set the Copy to Output Directory property to Copy if newer.

+

4. Start logging

+

NLog is now configured in the application. Start the application, and existing ILogger<T> calls will be processed by NLog and written to the configured targets.

+

You are not required to use the ILogger<T>, if you prefer using NLog.LogManager.GetCurrentClassLogger() in the console application.

+

If NLog is not working as expected, see the NLog Logging troubleshooting guide to identify configuration issues.

+

Using the .NET Generic Host

+

If the console application uses the .NET Generic Host, NLog can be registered directly with the host using UseNLog().

+

See the NLog.Extensions.Hosting NuGet package for information about integrating NLog with the .NET Generic Host.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Getting-started-with-ASP.NET-Core-2/index.html b/wiki/Getting-started-with-ASP.NET-Core-2/index.html new file mode 100644 index 000000000..614ee7e8e --- /dev/null +++ b/wiki/Getting-started-with-ASP.NET-Core-2/index.html @@ -0,0 +1,1573 @@ + + + + + + + + Getting started with ASP.NET Core 2 - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

⚠️ Missing the trace/debug logs in .NET Core 2? Check your appsettings.json

+
+

ℹ️ See also example in GitHub

+
+

This tutorial is for ASP.NET Core 2.

+ +

Note: .NET 4.6+ or .NET standard 2 are required

+

0. Create a new ASP.NET Core project

+

In Visual Studio 2017.

+

1. Add dependency in csproj manually or using NuGet

+

Install the latest: +- NLog.Web.AspNetCore 4.8+ +- Update the NLog package if possible

+

in csproj:

+
<PackageReference Include="NLog.Web.AspNetCore" Version="4.*" />
+<PackageReference Include="NLog" Version="4.*" />
+
+

2. Create a nlog.config file.

+

Create nlog.config (lowercase all) file in the root of your project.

+

We use this example:

+
<?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">
+      autoReload="true"
+      internalLogLevel="Info"
+      internalLogFile="c:\temp\internal-nlog.txt">
+
+  <!-- enable asp.net core layout renderers -->
+  <extensions>
+    <add assembly="NLog.Web.AspNetCore"/>
+  </extensions>
+
+  <!-- the targets to write to -->
+  <targets>
+    <!-- write logs to file  -->
+    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
+            layout="${longdate}|${event-properties:item=EventId_Id}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
+
+    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
+    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
+            layout="${longdate}|${event-properties:item=EventId_Id}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
+  </targets>
+
+  <!-- rules to map from logger name to target -->
+  <rules>
+    <!--All logs, including from Microsoft-->
+    <logger name="*" minlevel="Trace" writeTo="allfile" />
+
+    <!--Skip non-critical Microsoft logs and so log only own logs-->
+    <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
+    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
+  </rules>
+</nlog>
+
+

More details of the config file are here.

+

If you like to include other targets or layout renderers, check the Platform support table, as there is a limited set implemented. Check the column NetStandard. To read more about NetStandard, see the docs from Microsoft

+

3. Enable copy to bin folder

+

Enable copy to bin folder for nlog.config

+

NLogConfig

+

or edit .csproj file manually and add:

+
  <ItemGroup>
+    <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
+  </ItemGroup>
+
+

4. Update program.cs

+

Update the program.cs

+
using NLog.Web;
+using Microsoft.Extensions.Logging;
+
+public static void Main(string[] args)
+{
+    // NLog: setup the logger first to catch all errors
+    var logger = NLog.LogManager.Setup().RegisterNLogWeb().GetCurrentClassLogger();
+
+    try
+    {
+        logger.Debug("init main");
+        CreateWebHostBuilder(args).Build().Run(); 
+    }
+    catch (Exception ex)
+    {
+        //NLog: catch setup errors
+        logger.Error(ex, "Stopped program because of exception");
+        throw;
+    }
+    finally
+    {
+        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
+        NLog.LogManager.Shutdown();
+    }
+}
+
+public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
+    WebHost.CreateDefaultBuilder(args)
+        .UseStartup<Startup>()
+        .ConfigureLogging(logging =>
+        {
+            logging.ClearProviders();
+            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
+        })
+        .UseNLog();  // NLog: Register as Logging Provider
+
+

5. Configure appsettings.json

+

The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel. So either remove "Default": or adjust it correctly to your needs.

+
{
+    "Logging": {
+        "LogLevel": {
+            "Default": "Trace",
+            "Microsoft": "Information"
+        }
+    }
+}
+
+

Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json

+

6. Write logs

+

Inject the ILogger in your controller:

+
using Microsoft.Extensions.Logging;
+
+public class HomeController : Controller
+{
+    private readonly ILogger<HomeController> _logger;
+
+    public HomeController(ILogger<HomeController> logger)
+    {
+        _logger = logger;
+    }
+
+    public IActionResult Index()
+    {
+        _logger.LogInformation("Index page says hello");
+        return View();
+    }
+
+
+

7. Example Output

+

When starting the ASP.NET Core website, we get two files:

+

nlog-own-2017-10-10.log

+
2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main |url: |action: 
+2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index! |url: http://localhost/|action: Index
+
+

nlog-all-2017-10-10.log

+
2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main 
+2017-10-10 23:40:30.9739|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\Users\j.verdurmen\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 
+2017-10-10 23:40:30.9897|37|DEBUG|Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository|Reading data from file 'C:\Users\j.verdurmen\AppData\Local\ASP.NET\DataProtection-Keys\key-bfd1ce07-8dc6-4eef-a51a-d21ddb547109.xml'. 
+2017-10-10 23:40:31.0004|18|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Found key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109}. 
+2017-10-10 23:40:31.0124|13|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver|Considering key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} with expiration date 2017-12-28 19:01:07Z as default key. 
+2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60 
+2017-10-10 23:40:31.0422|51|DEBUG|Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor|Decrypting secret element using Windows DPAPI. 
+2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60 
+2017-10-10 23:40:31.0422|4|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'AES' from provider '(null)' with chaining mode CBC. 
+2017-10-10 23:40:31.0543|3|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'SHA256' from provider '(null)' with HMAC. 
+2017-10-10 23:40:31.0543|2|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider|Using key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} as the default key. 
+2017-10-10 23:40:31.0543|0|DEBUG|Microsoft.AspNetCore.DataProtection.Internal.DataProtectionStartupFilter|Key ring with default key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} was loaded during application startup. 
+2017-10-10 23:40:31.4080|3|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting starting 
+2017-10-10 23:40:31.5508|4|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting started 
+2017-10-10 23:40:31.5508|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly ASP.NET Core 2 - VS2017 
+2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.ApplicationInsights.HostingStartup 
+2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.Server.IISIntegration 
+2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK64" started. 
+2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK65" started. 
+2017-10-10 23:40:31.7418|19|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK65" reset. 
+2017-10-10 23:40:31.7418|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK65" disconnecting. 
+2017-10-10 23:40:31.7418|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK65" sending FIN. 
+2017-10-10 23:40:31.7591|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK65" stopped. 
+2017-10-10 23:40:31.8153|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/   
+2017-10-10 23:40:31.8607|4|DEBUG|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|The request path / does not match a supported file type 
+2017-10-10 23:40:32.0160|1|DEBUG|Microsoft.AspNetCore.Routing.RouteBase|Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'. 
+2017-10-10 23:40:32.1120|1|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) 
+2017-10-10 23:40:32.1326|1|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) with arguments ((null)) - ModelState is Valid 
+2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index! 
+2017-10-10 23:40:32.1620|2|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017), returned result Microsoft.AspNetCore.Mvc.ViewResult. 
+2017-10-10 23:40:32.1620|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine|View lookup cache miss for view 'Index' in controller 'Home'. 
+2017-10-10 23:40:33.6906|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\Home\Index.cshtml' started. 
+2017-10-10 23:40:35.7180|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\Home\Index.cshtml' completed in 2024.1338ms. 
+2017-10-10 23:40:35.7988|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\_ViewStart.cshtml' started. 
+2017-10-10 23:40:35.8637|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\_ViewStart.cshtml' completed in 63.9912ms. 
+2017-10-10 23:40:35.8710|2|DEBUG|Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor|The view 'Index' was found. 
+2017-10-10 23:40:35.8710|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor|Executing ViewResult, running view at path /Views/Home/Index.cshtml. 
+2017-10-10 23:40:35.9577|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine|View lookup cache miss for view '_Layout' in controller 'Home'. 
+2017-10-10 23:40:36.0454|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\Shared\_Layout.cshtml' started. 
+2017-10-10 23:40:36.2080|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\Shared\_Layout.cshtml' completed in 161.8031ms. 
+2017-10-10 23:40:36.2209|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' initialized. 
+2017-10-10 23:40:36.2209|3|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' processed. 
+2017-10-10 23:40:36.2367|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' initialized. 
+2017-10-10 23:40:36.2367|3|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' processed. 
+2017-10-10 23:40:36.2942|2|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) in 4181.1451ms 
+2017-10-10 23:40:36.3036|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK64" completed keep alive response. 
+2017-10-10 23:40:36.3273|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 4515.4954ms 200 text/html; charset=utf-8 
+2017-10-10 23:40:36.3273|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK67" started. 
+2017-10-10 23:40:36.3273|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK66" started. 
+2017-10-10 23:40:36.3386|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/css/bootstrap.css   
+2017-10-10 23:40:36.3386|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/css/site.css   
+2017-10-10 23:40:36.3610|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\css\site.css' 
+2017-10-10 23:40:36.3610|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.css'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\lib\bootstrap\dist\css\bootstrap.css' 
+2017-10-10 23:40:36.4312|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK66" completed keep alive response. 
+2017-10-10 23:40:36.4312|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 90.8043ms 200 text/css 
+2017-10-10 23:40:36.4312|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK67" completed keep alive response. 
+2017-10-10 23:40:36.4312|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 98.4683ms 200 text/css 
+2017-10-10 23:40:36.4710|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK68" started. 
+2017-10-10 23:40:36.4710|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK69" started. 
+2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/jquery/dist/jquery.js   
+2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/js/bootstrap.js   
+2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner2.svg   
+2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/js/site.js?v=ji3-IxbEzYWjzzLCGkF1KDjrT2jLbbrSYXw-AhMPNIA   
+2017-10-10 23:40:36.4819|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK6A" started. 
+2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\js\site.js' 
+2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.js'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\lib\jquery\dist\jquery.js' 
+2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner2.svg'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\images\banner2.svg' 
+2017-10-10 23:40:36.4933|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK67" completed keep alive response. 
+2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.js'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\lib\bootstrap\dist\js\bootstrap.js' 
+2017-10-10 23:40:36.4933|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 20.2541ms 200 application/javascript 
+2017-10-10 23:40:36.5143|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK66" completed keep alive response. 
+2017-10-10 23:40:36.5143|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 32.361ms 200 image/svg+xml 
+2017-10-10 23:40:36.5143|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2   
+2017-10-10 23:40:36.5401|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\lib\bootstrap\dist\fonts\glyphicons-halflings-regular.woff2' 
+2017-10-10 23:40:36.5401|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner1.svg   
+2017-10-10 23:40:36.5401|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner1.svg'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\images\banner1.svg' 
+2017-10-10 23:40:36.5539|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK67" completed keep alive response. 
+2017-10-10 23:40:36.5539|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 39.9074ms 200 font/woff2 
+2017-10-10 23:40:36.5745|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner3.svg   
+2017-10-10 23:40:36.5745|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner4.svg   
+2017-10-10 23:40:36.5951|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK68" completed keep alive response. 
+2017-10-10 23:40:36.6015|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 119.5389ms 200 application/javascript 
+2017-10-10 23:40:36.6015|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner4.svg'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\images\banner4.svg' 
+2017-10-10 23:40:36.5745|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner3.svg'. Physical path: 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\wwwroot\images\banner3.svg' 
+2017-10-10 23:40:36.6946|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK64" completed keep alive response. 
+2017-10-10 23:40:36.6703|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK66" completed keep alive response. 
+2017-10-10 23:40:36.6946|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 119.7561ms 200 image/svg+xml 
+2017-10-10 23:40:36.6015|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK69" completed keep alive response. 
+2017-10-10 23:40:36.7137|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 170.2078ms 200 image/svg+xml 
+2017-10-10 23:40:36.7137|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK6A" completed keep alive response. 
+2017-10-10 23:40:36.7560|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 181.4017ms 200 image/svg+xml 
+2017-10-10 23:40:36.6946|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 216.2838ms 200 application/javascript 
+2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK68" received FIN. 
+2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK67" received FIN. 
+2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK67" disconnecting. 
+2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK69" received FIN. 
+2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK69" disconnecting. 
+2017-10-10 23:42:21.6657|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK67" sending FIN. 
+2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK68" disconnecting. 
+2017-10-10 23:42:21.6657|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK69" stopped. 
+2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK66" received FIN. 
+2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK66" disconnecting. 
+2017-10-10 23:42:21.6657|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK69" sending FIN. 
+2017-10-10 23:42:21.6657|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK67" stopped. 
+2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK6A" received FIN. 
+2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK6A" disconnecting. 
+2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK64" received FIN. 
+2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK64" disconnecting. 
+2017-10-10 23:42:21.6800|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK68" sending FIN. 
+2017-10-10 23:42:21.6800|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK68" stopped. 
+2017-10-10 23:42:21.6800|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK66" sending FIN. 
+2017-10-10 23:42:21.6800|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK66" stopped. 
+2017-10-10 23:42:21.6943|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK6A" stopped. 
+2017-10-10 23:42:21.6943|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK6A" sending FIN. 
+2017-10-10 23:42:21.6943|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK64" sending FIN. 
+2017-10-10 23:42:21.6943|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK64" stopped. 
+
+

Configure NLog Targets for output

+

Next step, see Configure NLog with nlog.config

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Getting-started-with-ASP.NET-Core-3/index.html b/wiki/Getting-started-with-ASP.NET-Core-3/index.html new file mode 100644 index 000000000..f2482f9a7 --- /dev/null +++ b/wiki/Getting-started-with-ASP.NET-Core-3/index.html @@ -0,0 +1,1505 @@ + + + + + + + + Getting started with ASP.NET Core 3 - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

⚠️ Missing the trace/debug logs? Check your appsettings.json

+
+

ℹ️ See also example in GitHub

+
+

This tutorial is for ASP.NET Core 3.1

+ +

0. Create a new ASP.NET Core project

+

In Visual Studio 2019.

+

1. Add dependency in csproj manually or using NuGet

+

Install the latest: +- NLog.Web.AspNetCore 4.9+ +- Update the NLog package if possible

+

in csproj:

+
<PackageReference Include="NLog.Web.AspNetCore" Version="4.*" />
+<PackageReference Include="NLog" Version="4.*" />
+
+

2. Create a nlog.config file.

+

Create nlog.config (lowercase all) file in the root of your project.

+

We use this example:

+
<?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">
+      autoReload="true"
+      throwConfigExceptions="true"
+      internalLogLevel="info"
+      internalLogFile="c:\temp\internal-nlog-AspNetCore3.txt">
+
+  <!-- enable asp.net core layout renderers -->
+  <extensions>
+    <add assembly="NLog.Web.AspNetCore"/>
+  </extensions>
+
+  <!-- the targets to write to -->
+  <targets>
+    <!-- File Target for all log messages with basic details -->
+    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore3-all-${shortdate}.log"
+            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
+
+    <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
+    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore3-own-${shortdate}.log"
+            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|" />
+
+    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
+    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
+  </targets>
+
+  <!-- rules to map from logger name to target -->
+  <rules>
+    <!--All logs, including from Microsoft-->
+    <logger name="*" minlevel="Trace" writeTo="allfile" />
+
+    <!--Output hosting lifetime messages to console target for faster startup detection -->
+    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
+
+    <!--Skip non-critical Microsoft logs and so log only own logs-->
+    <logger name="Microsoft.*" maxlevel="Info" final="true" />  <!-- BlackHole -->
+
+    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
+  </rules>
+</nlog>
+
+

More details of the config file are here.

+

Notice that one might have to pay special attention to the Hosting Lifetime Startup Messages, if removing all other LoggingProviders (Like Console) and only using NLog. As it can cause hosting environment (Visual Studio / Docker / Azure Container) to not see application as started.

+

If you like to include other targets or layout renderers, check the Platform support table, as there is a limited set implemented. Check the column NetStandard. To read more about NetStandard, see the docs from Microsoft. Check .NET Standard 2 for ASP.NET Core 3.

+

3. Enable copy to bin folder

+

Enable copy to bin folder for nlog.config

+

NLogConfig

+

or edit .csproj file manually and add:

+
  <ItemGroup>
+    <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
+  </ItemGroup>
+
+

4. Update program.cs

+

Update the program.cs to include UseNLog():

+
using System;
+using NLog.Web;
+using Microsoft.AspNetCore;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Hosting;
+
+public static void Main(string[] args)
+{
+    // Early init of NLog to allow startup and exception logging, before host is built
+    var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
+
+    try
+    {
+        logger.Debug("init main");
+        CreateHostBuilder(args).Build().Run();
+    }
+    catch (Exception exception)
+    {
+        //NLog: catch setup errors
+        logger.Error(exception, "Stopped program because of exception");
+        throw;
+    }
+    finally
+    {
+        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
+        NLog.LogManager.Shutdown();
+    }
+}
+
+public static IHostBuilder CreateHostBuilder(string[] args) =>
+    Host.CreateDefaultBuilder(args)
+        .ConfigureWebHostDefaults(webBuilder =>
+        {
+            webBuilder.UseStartup<Startup>();
+        })
+        .ConfigureLogging(logging =>
+        {
+            logging.ClearProviders();
+            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
+        })
+        .UseNLog();  // NLog: Register as Logging Provider
+
+

5. Configure appsettings.json

+

The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel. So either remove "Default": or adjust it correctly to your needs.

+
{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Trace",
+      "Microsoft": "Warning",
+      "Microsoft.Hosting.Lifetime": "Information"
+    }
+  },
+  "AllowedHosts": "*"
+}
+
+

Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json

+

6. Write logs

+

Inject the ILogger in your controller:

+
using Microsoft.Extensions.Logging;
+
+public class HomeController : Controller
+{
+    private readonly ILogger<HomeController> _logger;
+
+    public HomeController(ILogger<HomeController> logger)
+    {
+        _logger = logger;
+        _logger.LogDebug(1, "NLog injected into HomeController");
+    }
+
+    public IActionResult Index()
+    {
+        _logger.LogInformation("Hello, this is the index!");
+        return View();
+    }
+
+
+
+

7. Example Output

+

When starting the ASP.NET Core website, we get two files:

+

nlog-own-2019-10-14.log

+
2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main |url: |action: |ASP.NET_Core_3___VS2019.Program.Main
+2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController..ctor
+2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController.Index
+
+

nlog-all-2019-10-14.log

+
2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main 
+2019-10-14 23:15:10.9142|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\Users\Julian\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 
+2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 
+2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 
+2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Content root path: D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019 
+2019-10-14 23:15:11.3238|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/   
+2019-10-14 23:15:11.3434|0|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executing endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 
+2019-10-14 23:15:11.3867|3|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller ASP.NET_Core_3___VS2019.Controllers.HomeController (ASP.NET Core 3 - VS2019). 
+2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController 
+2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! 
+2019-10-14 23:15:11.4161|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executing ViewResult, running view Index. 
+2019-10-14 23:15:11.5831|4|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executed ViewResult - view Index executed in 167.626ms. 
+2019-10-14 23:15:11.5831|2|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Executed action ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019) in 196.6052ms 
+2019-10-14 23:15:11.5831|1|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executed endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 
+2019-10-14 23:15:11.5910|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 267.9366ms 200 text/html; charset=utf-8 
+2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/jquery/dist/jquery.min.js   
+2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/css/site.css   
+2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/css/bootstrap.min.css   
+2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/js/bootstrap.bundle.min.js   
+2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0   
+2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\js\site.js' 
+2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\css\site.css' 
+2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 28.7787ms 200 application/javascript 
+2019-10-14 23:15:11.6696|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 52.4825ms 200 text/css 
+2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.bundle.min.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\bootstrap\dist\js\bootstrap.bundle.min.js' 
+2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.min.css'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\bootstrap\dist\css\bootstrap.min.css' 
+2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.min.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\jquery\dist\jquery.min.js' 
+2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 50.937400000000004ms 200 application/javascript 
+2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 70.65100000000001ms 200 text/css 
+2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 71.51610000000001ms 200 application/javascript 
+
+
+

Configure NLog Targets for output

+

Next step, see Configure NLog with nlog.config

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Getting-started-with-ASP.NET-Core-5/index.html b/wiki/Getting-started-with-ASP.NET-Core-5/index.html new file mode 100644 index 000000000..04f8c5d07 --- /dev/null +++ b/wiki/Getting-started-with-ASP.NET-Core-5/index.html @@ -0,0 +1,1480 @@ + + + + + + + + Getting started with ASP.NET Core 5 - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

⚠️ Missing the trace/debug logs? Check your appsettings.json

+
+

ℹ️ See also example in GitHub

+
+

This tutorial is for ASP.NET Core 5.

+ +

0. Create a new ASP.NET Core project

+

In Visual Studio 2019. Version 16.8+ is needed

+

1. Add dependency in csproj manually or using NuGet

+

Install the latest: +- NLog.Web.AspNetCore 4.9+ +- Update the NLog package if possible

+

in csproj:

+
<ItemGroup>
+  <PackageReference Include="NLog.Web.AspNetCore" Version="4.*" />
+  <PackageReference Include="NLog" Version="4.*" />
+</ItemGroup>
+
+

2. Create a nlog.config file.

+

Create nlog.config (lowercase all) file in the root of your project.

+

We use this example:

+
<?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">
+      autoReload="true"
+      internalLogLevel="Info"
+      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">
+
+  <!-- enable asp.net core layout renderers -->
+  <extensions>
+    <add assembly="NLog.Web.AspNetCore"/>
+  </extensions>
+
+  <!-- the targets to write to -->
+  <targets>
+    <!-- File Target for all log messages with basic details -->
+    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
+            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
+
+    <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
+    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log"
+            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
+
+    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
+    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
+  </targets>
+
+  <!-- rules to map from logger name to target -->
+  <rules>
+    <!--All logs, including from Microsoft-->
+    <logger name="*" minlevel="Trace" writeTo="allfile" />
+
+    <!--Output hosting lifetime messages to console target for faster startup detection -->
+    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
+
+    <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
+    <logger name="Microsoft.*" maxlevel="Info" final="true" />
+    <logger name="System.Net.Http.*" maxlevel="Info" final="true" />
+
+    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
+  </rules>
+</nlog>
+
+

More details of the config file are here.

+

Notice that one might have to pay special attention to the Hosting Lifetime Startup Messages, if removing all other LoggingProviders (Like Console) and only using NLog. As it can cause hosting environment (Visual Studio / Docker / Azure Container) to not see application as started.

+

3. Update program.cs

+

Update the program.cs to include UseNLog():

+
using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using System;
+using NLog.Web;
+
+namespace ASP.NET_Core_5_NLog_Example
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            // Early init of NLog to allow startup and exception logging, before host is built
+            var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
+
+            try
+            {
+                logger.Debug("init main");
+                CreateHostBuilder(args).Build().Run();
+            }
+            catch (Exception exception)
+            {
+                //NLog: catch setup errors
+                logger.Error(exception, "Stopped program because of exception");
+                throw;
+            }
+            finally
+            {
+                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
+                NLog.LogManager.Shutdown();
+            }
+        }
+
+        public static IHostBuilder CreateHostBuilder(string[] args) =>
+            Host.CreateDefaultBuilder(args)
+                .ConfigureWebHostDefaults(webBuilder =>
+                {
+                    webBuilder.UseStartup<Startup>();
+                })
+                .ConfigureLogging(logging =>
+                {
+                    logging.ClearProviders();
+                    logging.SetMinimumLevel(LogLevel.Trace);
+                })
+                .UseNLog();  // NLog: Register as Logging Provider
+    }
+}
+
+

4. Configure appsettings.json

+

The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel. So either remove "Default": or adjust it correctly to your needs.

+
{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Trace",
+      "Microsoft": "Warning",
+      "Microsoft.Hosting.Lifetime": "Information"
+    }
+  },
+  "AllowedHosts": "*"
+}
+
+

Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json

+

5. Write logs

+

Inject the ILogger in your controller:

+
using Microsoft.Extensions.Logging;
+
+public class HomeController : Controller
+{
+    private readonly ILogger<HomeController> _logger;
+
+    public HomeController(ILogger<HomeController> logger)
+    {
+        _logger = logger;
+        _logger.LogDebug(1, "NLog injected into HomeController");
+    }
+
+    public IActionResult Index()
+    {
+        _logger.LogInformation("Hello, this is the index!");
+        return View();
+    }
+
+
+
+

6. Example Output

+

When starting the ASP.NET Core website, we get two files:

+

nlog-own-2020-12-29.log

+
2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main |url: |action: 
+2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index
+2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index
+
+
+

nlog-all-2020-12-29.log

+
2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main 
+2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 
+2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 
+2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Content root path: D:\nlog\NLog.Web\examples\ASP.NET Core 5\ASP.NET Core 5 NLog Example 
+2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController 
+2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index!  
+
+

Configure NLog Targets for output

+

Next step, see Configure NLog with nlog.config

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Getting-started-with-ASP.NET-Core-6/index.html b/wiki/Getting-started-with-ASP.NET-Core-6/index.html new file mode 100644 index 000000000..4f96d5c38 --- /dev/null +++ b/wiki/Getting-started-with-ASP.NET-Core-6/index.html @@ -0,0 +1,1378 @@ + + + + + + + + Getting started with ASP.NET Core 6 - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog integrates with the built-in ASP.NET Core logging infrastructure. Application code continues to use ILogger<T>, while NLog handles log routing, formatting, and writing to configured targets.

+

This guide shows how to configure NLog for a new or existing ASP.NET Core applications.

+

1. Install NLog

+

Install the NLog ASP.NET Core NuGet package:

+
+

dotnet add package NLog.Web.AspNetCore

+
+

2. Register NLog Logging Provider

+

Update Program.cs to include UseNLog():

+
using NLog.Web;
+
+var builder = WebApplication.CreateBuilder(args);
+
+// Remove default Microsoft logging providers
+builder.Logging.ClearProviders();
+// Register NLog
+builder.Host.UseNLog();
+
+var app = builder.Build();
+
+app.Run();
+
+

UseNLog() registers NLog as the logging provider for the ASP.NET Core host. From this point log messages will be processed by NLog.

+

3. Configure NLog

+

NLog supports several configuration approaches:

+ +

This guide uses an NLog.config XML file as the configuration example, but the alternatives above also work. Create a file named NLog.config in the application project root directory and add the following content:

+
<?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"
+         throwConfigExceptions="true"
+         autoReload="true">
+   <targets async="true">
+      <target xsi:type="Console" name="console" layout="${MicrosoftConsoleLayout}" />
+
+      <target xsi:type="File" name="file" fileName="logs/app-${shortdate}.log" maxArchiveFiles="7">
+         <layout xsi:type="MicrosoftConsoleJsonLayout" includeScopes="true" includeActivityIds="true">
+           <state name="url" layout="${aspnet-request-url}" />
+           <state name="method" layout="${aspnet-request-method}" />
+           <state name="statusCode" layout="${aspnet-response-statuscode}" />
+         </layout>
+      </target>
+   </targets>
+   <rules>
+       <!-- Reduce noise from ASP.NET framework, and route relevant logging to output targets -->
+       <logger name="System.*" finalMinLevel="Warning" />
+       <logger name="Microsoft.*" finalMinLevel="Warning" />
+       <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" /> 
+       <logger name="*" minLevel="Info" writeTo="console,file" />
+   </rules>
+</nlog>
+
+

This configuration includes:

+
    +
  • Targets — Define output destinations for writing log messages. See NLog Targets
  • +
  • Rules — Define how log messages are routed from loggers to output targets.
  • +
  • Layout — Define how log messages are formatted. See NLog Layouts
  • +
  • Layout Renderers - Provide additional details to include in log output. See NLog Layout Renderers
  • +
+

The Console-target ensures that ASP.NET Core hosting lifetime startup messages are available on the console. The file-target writes newline-delimited JSON log events that capture structured logging properties and trace context (TraceId and SpanId) for correlating logs with traces in distributed systems.

+

Ensure that the NLog.config file is copied to the output directory when building or publishing the application. In Visual Studio, set the Copy to Output Directory property to Copy if newer.

+

4. Start logging

+

NLog is now configured in the application. Start the application, and existing ILogger<T> calls will be processed by NLog and written to the configured targets.

+

If NLog is not working as expected, see the NLog Logging troubleshooting guide to identify configuration issues.

+
+

ℹ️ See also examples in GitHub

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/GroupByWrapper-target/index.html b/wiki/GroupByWrapper-target/index.html new file mode 100644 index 000000000..b3dc38a69 --- /dev/null +++ b/wiki/GroupByWrapper-target/index.html @@ -0,0 +1,1338 @@ + + + + + + + + GroupByWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Allow one to to take an entire batch of logevents and group-by ex. request-identifier. Splitting the batch into individual emails / reports.

+
+

Platforms Supported: All (Introduced with NLog 5.0)

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="GroupByWrapper"
+          name="String"
+          key="Layout">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+
    +
  • Key - Layout used for grouping the LogEvents into smaller batches.
  • +
+

Example

+

Creates a buffer of the last 50 LogEvents, and flushes when receiving LogEvent with LogLevel.Error. Then groups the LogEvents by their individual request (Using ${activity} other correlationid). Then generates output only containing the LogEvents matching the failed request.

+
  <target name="String" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Error" flushOnConditionOnly="true">
+    <target name="String" xsi:type="BufferingWrapper" bufferSize="50" overflowAction="Discard">
+      <target name="String" xsi:type="GroupByWrapper" key="${ActivityId}">
+        <target name="String" xsi:type="PostFilteringWrapper" defaultFilter="Ignore">
+           <when exists="level >= LogLevel.Error" filter="Log"/>
+           <target xsi:type="myTargetType" ...target properties... />
+        </target>
+      </target>
+    </target>
+  </target>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Guid-layout-renderer/index.html b/wiki/Guid-layout-renderer/index.html new file mode 100644 index 000000000..1f4badc5e --- /dev/null +++ b/wiki/Guid-layout-renderer/index.html @@ -0,0 +1,1324 @@ + + + + + + + + Guid layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Globally-unique identifier (GUID).

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${guid:format=String}
+
+

Parameters

+

Rendering Options

+
    +
  • format - GUID format as accepted by Guid.ToString() method. Default: N
  • +
  • GeneratedFromLogEvent - Creates a special GUID from the LogEvent, so if the LogEvent is written to multiple targets, then all targets will get the same GUID for the LogEvent (Like a CorrelationId). Default: False
    +

    Introduced with NLog 4.5

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/HTTP-target/index.html b/wiki/HTTP-target/index.html new file mode 100644 index 000000000..765bf1cbd --- /dev/null +++ b/wiki/HTTP-target/index.html @@ -0,0 +1,1455 @@ + + + + + + + + NLog.Targets.HTTP - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog.Targets.HTTP

+

Nuget (with prereleases)

+

NLog.Targets.HTTP is a HTTP POST target for NLog. +Combined with JSON formatter it can be used to send events to an +instance of Splunk and other HTTP based collectors.

+

Getting started

+

Add the library as an extension to nlog:

+
<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">
+  <extensions>
+    <add assembly="NLog.Targets.Http" />
+  </extensions>
+  <targets>
+    ...
+
+

Available Configuration Parameters

+

Listed below are available configuration parameters with their default values

+
<target name='target name' 
+        type='HTTP' 
+        URL='protocol://server:port/path'
+        Method='POST'
+        Authorization='phrase token' 
+        BatchSize='1'
+        MaxQueueSize='2147483647'
+        IgnoreSslErrors='true'
+        FlushBeforeShutdown='true'
+        ContentType='application/json'
+        Accept='application/json'
+        DefaultConnectionLimit='2'
+        Expect100Continue='false'
+        UseNagleAlgorithm='true'
+        ConnectTimeout='30000' 
+        InMemoryCompression='true'
+        ProxyUrl=''
+        ProxyUser=''
+        ProxyPassword=''
+    >
+
+
+

URL

+

The URL to send messages to (mandatory)

+

Method

+

HTTP method to use (GET,POST,PUT, etc.)

+

Authorization

+

The Authorization Header value to pass.

+

BatchSize

+

Number of messages to be sent together in one call separated by an empty new line

+

MaxQueueSize

+

Maximum number of messages awaiting to be send. Please note, that if this value is set, the logger might be blocking.

+

IgnoreSsslErrors

+

Some SSL certificates might be invalid or not-trusted.

+

FlushBeforeShutdown

+

Force all messages to be delivered before shutting down.

+

ContentType

+

HTTP ContentType Header value.

+

Accept

+

HTTP Accept Header value.

+

DefaultConnectionLimit

+

How many connections might be used at the same time. Changes ServicePointManager.DefaultConnectionLimit, which might affect other parts of your system.

+

Expect100Continue

+

See this article.

+

UseNagleAlgorithm

+

The Nagle algorithm is used to buffer small packets of data and transmit them as a single packet. This process, referred to as "nagling," is widely used +because it reduces the number of packets transmitted and lowers the overhead per packet. The Nagle algorithm is fully described in IETF RFC 896.

+

ConnectTimeout

+

How long should the client wait to connect (default is 30 seconds).

+

InMemoryCompression

+

Reduces the amount of memory consumed at the expense of increased CPU usage.

+

ProxyUrl

+

Designates a proxy server to use. Must include protocol (http|https) and port

+

ProxyUser

+

If proxy authentication is needed, you can specify it with a domain prefix, i.e. DOMAIN\USER.

+

ProxyPassword

+

Password to use for proxy authentication.

+

Sample SPLUNK Configuration

+
<?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='splunk' 
+            type='HTTP' URL='server:port/services/collector'
+            Authorization='Splunk auth-token' 
+            BatchSize='100'>
+      <layout type='JsonLayout'>
+        <attribute name='sourcetype' layout='_json' />
+        <attribute name='host' layout='${machinename}' />
+        <attribute name='event' encode='false'>
+          <layout type='JsonLayout'>
+            <attribute name='level' layout='${level:upperCase=true}' />
+            <attribute name='source' layout='${logger}' />
+            <attribute name='thread' layout='${threadid}' />
+            <attribute name='message' layout='${message}' />
+            <attribute name='utc' layout='${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}' />
+          </layout>
+        </attribute>
+      </layout>
+    </target>
+  </targets>
+  <rules>
+    <logger name="*" minlevel="Debug" writeTo="splunk" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Home/index.html b/wiki/Home/index.html new file mode 100644 index 000000000..980aed3df --- /dev/null +++ b/wiki/Home/index.html @@ -0,0 +1,1318 @@ + + + + + + + + Home - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog

+

Welcome to the NLog documentation! Just start with one of the tutorials to log messages within minutes!

+

NLog supports the .NET Frameworks 3.5 - 4.8 along with ASP.NET Core using Microsoft dependency injection. See the getting started pages.

+

For structured logging, introduced in NLog 4.5, see How to use structured logging

+

There are many available output options:

+ +

Are you missing some targets or layouts in NLog? Check extending NLog or even better, contribute to NLog!

+

Issues with logging? Check the Troubleshooting Guide

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Host-AppName-Layout-Renderer/index.html b/wiki/Host-AppName-Layout-Renderer/index.html new file mode 100644 index 000000000..5f0352d1c --- /dev/null +++ b/wiki/Host-AppName-Layout-Renderer/index.html @@ -0,0 +1,1316 @@ + + + + + + + + Host AppName Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

HostEnvironment ApplicationName

+
+

Platforms Supported: All

+

Introduced with NLog.Extensions.Hostting v6.0 and NLog.Web.AspNetCore v6.0

+
+

Configuration Syntax

+
${host-appname}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Host-Environment-Layout-Renderer/index.html b/wiki/Host-Environment-Layout-Renderer/index.html new file mode 100644 index 000000000..141491a87 --- /dev/null +++ b/wiki/Host-Environment-Layout-Renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + Host Environment Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

HostEnvironment EnvironmentName (DOTNET_ENVIRONMENT / ASPNETCORE_ENVIRONMENT)

+
+

Platforms Supported: All

+

Introduced with NLog.Extensions.Hostting v6.0 and NLog.Web.AspNetCore v6.0

+
+

Configuration Syntax

+
${host-environment}
+
+

Remarks

+

The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or "environment" as specified in any other configuration source.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Host-RootDir-Layout-Renderer/index.html b/wiki/Host-RootDir-Layout-Renderer/index.html new file mode 100644 index 000000000..37c9aba03 --- /dev/null +++ b/wiki/Host-RootDir-Layout-Renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + Host RootDir Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

HostEnvironment Content Root

+
+

Platforms Supported: All (Supported in Asp.NetCore and Asp.NET )

+

Introduced with NLog.Extensions.Hosting v6.0.0 and NLog.Web.AspNetCore v6.0.0 and NLog.Web v6.0.0

+
+

Configuration Syntax

+
${host-rootdir}
+
+

Remarks

+

Application base path is also known as the content root, while wwwroot-path is root directory for static content.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/HostName-Layout-Renderer/index.html b/wiki/HostName-Layout-Renderer/index.html new file mode 100644 index 000000000..798db75b1 --- /dev/null +++ b/wiki/HostName-Layout-Renderer/index.html @@ -0,0 +1,1319 @@ + + + + + + + + HostName Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The computer DNS HostName that the process is running on.

+
+

Platforms Supported: All

+

Introduced with NLog 4.6

+
+

Configuration Syntax

+
${hostname}
+
+

Remarks

+

See also ${machinename} For NetBIOS name

+

See also ${local-ip} For IP Address

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-Log-Exceptions/index.html b/wiki/How-to-Log-Exceptions/index.html new file mode 100644 index 000000000..fcff3000c --- /dev/null +++ b/wiki/How-to-Log-Exceptions/index.html @@ -0,0 +1,1347 @@ + + + + + + + + How to Log Exceptions - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Exceptions require special treatment in NLog. You need to call the method on the Logger class which takes an Exception as its first argument. The method name matches the log level. For instance, to log an exception using the Error loglevel, do:

+
logger.Error(ex, "Oops, an exception occured");
+
+

Please note: the methods have been changed in NLog 4.0. Previous versions expected the exception after the message.

+

Example

+

You typically log exceptions inside a catch handler. An example of logging an exception with the Error LogLevel is seen in the following:

+
try 
+{ 
+    // some code which may throw 
+} 
+catch (MyException ex) 
+{ 
+    logger.Error(ex, "Got exception.");  // NLog 4.0 and newer
+    logger.Error("Got exception.", ex);  // Before NLog 4.0, and now obsolete
+}
+
+

Exception Formatting

+

To write the details of the exception, use the ${exception} in your layout. Depending on the desired output you may want to specify different value for the format argument. The following example displays the result of calling ToString() on the exception object.

+
<nlog> 
+  <targets> 
+    <target name="f" type="File" 
+            layout="${longdate} ${message} ${exception:format=tostring}"/> 
+  </targets> 
+  <rules> 
+    <logger name="*" writeTo="f"/> 
+  </rules> 
+</nlog>
+
+

For simpler scenarios you may directly use the ${message:withException=true}, which is used in the default Layout in NLog v5.0:

+
<nlog> 
+  <targets> 
+    <target name="f" type="File" 
+            layout="${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}"/> 
+  </targets> 
+  <rules> 
+    <logger name="*" writeTo="f"/> 
+  </rules> 
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-create-Logger-for-sub-classes/index.html b/wiki/How-to-create-Logger-for-sub-classes/index.html new file mode 100644 index 000000000..ebda8737e --- /dev/null +++ b/wiki/How-to-create-Logger-for-sub-classes/index.html @@ -0,0 +1,1336 @@ + + + + + + + + How to create Logger for sub classes - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

When we wish to expose the logger into sub classes the following pattern could be used.

+
class BaseClass
+{
+    protected BaseClass()
+    {
+        Log = LogManager.GetLogger(GetType().ToString());
+    }
+
+    protected Logger Log { get; private set; }
+}
+
+class ExactClass : BaseClass
+{
+    public ExactClass() : base() { }
+    ...
+}
+
+

Alternative solution could be this:

+
class BaseClass
+{
+    protected virtual Logger Log { get { return _logger; } }
+    private static Logger _logger = LogManager.GetCurrentClassLogger();
+}
+
+class ExactClass : BaseClass
+{
+    protected override Logger Log { get { return _logger; } }
+    private static Logger _logger = LogManager.GetCurrentClassLogger();
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-use-structured-logging/index.html b/wiki/How-to-use-structured-logging/index.html new file mode 100644 index 000000000..5fcf5fe67 --- /dev/null +++ b/wiki/How-to-use-structured-logging/index.html @@ -0,0 +1,1505 @@ + + + + + + + + How to use structured logging - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog has always supported structured logging using LogEventInfo Properties with key-value pairs (aka. semantic logging). NLog 4.5 extended this by supporting message-templates and extracting named properties together with destructuring support. NLog supports the message templates syntax defined by: https://messagetemplates.org/

+

Why structured logging

+

Structured logging makes it easier to store and query log-events, as the logevent message-template and message-parameters are preserved, instead of just transforming them into a formatted message.

+

The normal .NET string.Format(...) will only accept input strings like this:

+
logger.Info("Logon by user:{0} from ip_address:{1}", "Kenny", "127.0.0.1");
+logger.Debug("Shopitem:{0} added to basket by user:{1}", "Jacket", "Kenny");
+
+

When storing these log-events in a database (or somewhere else), then it can be difficult to query all actions performed by a certain user. Also it could be hard to group similar events.

+

The workaround would then be to perform RegEx-queries to recognize logevent messages and convert them into a more structured format, and register which parameter index is the user. The RegEx might even have to extract the needed details from the formatted message, making it even more fragile. Maintaining these RegEx-queries can become rather cumbersome.

+

Instead of using the message-template to group LogEvents, then Microsoft recommends using EventId / EventName to make it easy to identify LogEvent patterns. This gives more freedom to change the message-template if needed, and the EventName provides a simple human-readable-identifier.

+

Further history: messagetemplates.org

+

Using structured logging

+

NLog has always supported log-event metadata called event-properties, but it requires a little effort to generate a log-event with properties. See also the Fluent-Logger-API

+

NLog 4.5 makes it possible to capture log-event-properties from the log-message-template, so they can be easily processed by the NLog destination target:

+
logger.Info("Logon by {user} from {ip_address}", "Kenny", "127.0.0.1"); // Logon by "Kenny" from "127.0.0.1"
+logger.Debug("{shopitem} added to basket by {user}", new { Id=6, Name = "Jacket", Color = "Orange" }, "Kenny");
+
+

Any NLog destination target that is able to handle log-event-properties will automatically experience the benefit of doing structured logging.

+

Formatting of the message

+

The formatting of message depends on the datatype of the parameters.

+

Example:

+
logger.Info("Order {orderid} created for {user}", 42, "Kenny");
+
+

Will be formatted as (Before NLog v6 strings would had quotes):

+

Order 42 created for Kenny

+

The formatting is controlled by the datatype of the parameter: +- null: printed as NULL +- list/ienumerable/array: item1, item2 +- dictionary: key1=value1, key2=value2 +- objects: ToString()

+

It's possible to control formatting by preceding @ or $:

+
    +
  • @ will format the object as JSON
  • +
  • $ forces ToString()
  • +
+

Examples

+
Object o = null;
+
+logger.Info("Test {value1}", o); // null case. Result:  Test NULL
+logger.Info("Test {value1}", new DateTime(2018,03, 25)); // datetime case. Result:  Test 25-3-2018 00:00:00 (locale ToString)
+logger.Info("Test {value1}", new List<string> { "a", "b" }); // list of strings. Result: Test a, b
+logger.Info("Test {value1}", new[] { "a", "b" }); // array. Result: Test a, b
+logger.Info("Test {value1}", new Dictionary<string, int> { { "key1", 1 }, { "key2", 2 } }); // dict. Result:  Test key1=1, key2=2
+
+var order = new Order
+{
+    OrderId = 2,
+    Status = OrderStatus.Processing
+};
+
+logger.Info("Test {value1}", order);  // object Result: Test MyProgram.Program+Order
+logger.Info("Test {@value1}", order); // object Result: Test {"OrderId":2, "Status":"Processing"}
+logger.Info("Test {value1}", new { OrderId = 2, Status = "Processing"});  // anonymous object. Result: Test { OrderId = 2, Status = Processing }
+logger.Info("Test {@value1}", new { OrderId = 2, Status = "Processing"}); // anonymous object. Result: Test {"OrderId":2, "Status":"Processing"}
+
+
+

Output captured properties

+

When formatting the log message, then it will automatically serialize the parameters (see Formatting of the message). It is also possible to configure NLog Layout to serialize the individual properties. This can be done by using ${event-properties} or ${all-event-properties}, for example:

+
    <target xsi:type="File" name="jsonFile" fileName="c:\temp\nlog-json-${shortdate}.log">
+      <layout>${longdate}|${level}|${logger}|${message}|${all-event-properties}{exception:format=tostring}</layout>
+    </target>
+
+

NLog Layouts with option includeEventProperties="true" (Before NLog 5.0 it was includeAllProperties="true") will output captured properties from structured logging:

+ +

It can be configured like this:

+
    <target xsi:type="File" name="jsonFile" fileName="c:\temp\nlog-json-${shortdate}.log">
+
+      <layout xsi:type="JsonLayout" includeEventProperties="true">
+        <attribute name="time" layout="${longdate}" />
+        <attribute name="level" layout="${level:upperCase=true}"/>
+        <attribute name="message" layout="${message}" />
+      </layout>
+
+    </target>
+
+

NLog 4.5 adds support for rendering the raw message-template, instead of just the formatted message: +* ${message:raw=true}

+

NLog 4.5 extends the following NLog LayoutRenderers with support for serializing with property reflection into JSON when format="@"

+ +

In code you can use LogEventInfo.Properties. If having special interest in format-options for the captured parameters then one can use LogEventInfo.MessageTemplateParameters

+

NLog Target Support

+

Any NLog destination target that handles event-properties will be able to take advantage of structured logging. Many targets already has support for the option includeEventProperties="true", that comes automatically when inheriting from TargetWithContext.

+

NLog Targets with supports for NLog Layout as payload will automatically support structured logging:

+ +

There are already many custom NLog targets that provide the ability to store log-events in central storage, and allow a Web-Application to query the log-events along with their event-properties. These targets will automatically benefit from structured logging, and allow the Web-Application to perform effective queries.

+

Transform captured properties

+

Extract single property

+

NLog 4.6.3 allows you to navigate into a complex object and extract a single property. Ex:

+
logger.Debug("{shopitem} added to basket by {user}", new { Id=6, Name = "Jacket", Color = "Orange" }, "Kenny");
+
+

Then one can extract specific details from shopItem-property:

+
      <layout xsi:type="JsonLayout">
+        <attribute name="shopitemId" layout="${event-properties:shopitem:objectPath=Id}" />
+      </layout>
+
+

Customize Object Reflection

+

To avoid object reflection for a custom type, then just implement the IFormattable-interface, and NLog will call ToString() instead of doing reflection of properties.

+

NLog 4.7 allows you to transform large (or dangerous) objects into a more reduced/safe object:

+
LogManager.Setup().SetupSerialization(s =>
+   s.RegisterObjectTransformation<System.Net.WebException>(ex => new {
+      Type = ex.GetType().ToString(),
+      Message = ex.Message,
+      StackTrace = ex.StackTrace,
+      Source = ex.Source,
+      InnerException = ex.InnerException,
+      Status = ex.Status,
+      Response = ex.Response.ToString(),  // Call your custom method to render stream as string
+   })
+);
+
+

This can also be used to output object-fields, as the NLog Object Reflection only sees object-properties. By transforming into an Anonymous Type, and assigning the wanted object-fields to named properties.

+

If more dynamic reflection is required, then one can also just return a Dictionary<string, object> instead of returning an Anonymous Type (The performance hit is a little higher).

+

Note when making an override for an object-type, then the returned object-type must be of a different object-type (Ex. anonymous object). Because NLog caches the reflection of the return object-type, and afterwards NLog skips checking for transformation for already cached object-types.

+

Advanced

+

How to override parameter value formatter

+

Create a new class that NLog.IValueFormatter and set NLog.Config.ConfigurationItemFactory.Default.ValueFormatter

+

How to override JSON formatter

+

You can override the builtin NLog JSON converter with a different implementation.

+

You need a custom NLog.IJsonConverter and set NLog.Config.ConfigurationItemFactory.Default.JsonConverter

+

Example of using JSON.NET that supports JSON.NET object annotations like [JsonIgnore]:

+
    internal class JsonNetSerializer : NLog.IJsonConverter
+    {
+        readonly JsonSerializerSettings _settings;
+
+        public JsonNetSerializer()
+        {
+           _settings = new JsonSerializerSettings
+                {
+                    Formatting = Formatting.Indented,
+                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
+                };
+        }
+
+        /// <summary>Serialization of an object into JSON format.</summary>
+        /// <param name="value">The object to serialize to JSON.</param>
+        /// <param name="builder">Output destination.</param>
+        /// <returns>Serialize succeeded (true/false)</returns>
+        public bool SerializeObject(object value, StringBuilder builder)
+        {
+            try
+            {
+                var jsonSerializer = JsonSerializer.CreateDefault(_settings);
+                var sw = new System.IO.StringWriter(builder, System.Globalization.CultureInfo.InvariantCulture);
+                using (var jsonWriter = new JsonTextWriter(sw))
+                {
+                    jsonWriter.Formatting = jsonSerializer.Formatting;
+                    jsonSerializer.Serialize(jsonWriter, value, null);
+                }
+            }
+            catch (Exception e)
+            {
+                NLog.Common.InternalLogger.Error(e, "Error when custom JSON serialization");
+                return false;
+            }
+            return true;
+        }
+    }
+
+

Combine indexed and structured logging

+

e.g. logging "Hello {0} with {Message}"

+

For backward compatibility (and performance), then NLog will by default skip full parsing if it detects the first parameter as being positional index. This will ensure repeated positional-placeholders supported by string.Format will continue to work:

+
string.Format("{1}{0}{2}{0}", Environment.NewLine, "Hello", "World");
+
+

When parseMessageTemplates='true' then NLog will always parse all parameters, and if one is non-numeric, then all the parameters will be treated as structured parameters. Mixing and numeric and structured parameters is not recommended, as it hurts performance (backtrack) and numeric parameters are most of the time not so descriptive.

+

Parameter Names

+

The Names of the parameters should be unique

+

I just need the template

+

e.g. Order {orderId}

+

Use ${message:raw=true}

+

Disabling Message Template Support

+

NLog will by default attempt to parse log-events as structured log-events. This gives a minor overhead, that will not be noticable by most.

+

It is possible to disable this behavior, telling NLog it should not attempt to parse log-events as structured log-events, with this xml-setting:

+
<nlog parseMessageTemplates="false">
+    ...
+</nlog>
+
+

Restore String Quotes

+

NLog v6 removed quotes for strings to behave like Microsoft Extensions Logging. To revert to old behavior with string-quotes:

+
LogManager.Setup().SetupSerialization(s => s.RegisterValueFormatterWithStringQuotes());
+
+

Alternative one can use @ to add string-quotes:

+
Logger.Info("Hello {@World}", "Earth"); // Outputs Hello "Earth"
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-write-a-Target/index.html b/wiki/How-to-write-a-Target/index.html new file mode 100644 index 000000000..b642496dd --- /dev/null +++ b/wiki/How-to-write-a-Target/index.html @@ -0,0 +1,1307 @@ + + + + + + + + How to write a Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+ + +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-write-a-custom-async-target/index.html b/wiki/How-to-write-a-custom-async-target/index.html new file mode 100644 index 000000000..e80dbab74 --- /dev/null +++ b/wiki/How-to-write-a-custom-async-target/index.html @@ -0,0 +1,1391 @@ + + + + + + + + How to write a custom async target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +
+

Introduced with NLog 4.6

+
+

It is really easy:

+
    +
  • Create a class that inherits from NLog.Targets.AsyncTaskTarget
  • +
  • Override the WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) method.
  • +
  • In the body of this method invoke this.RenderLogEvent(this.Layout, logEvent) to get the message text, and invoke this.GetAllProperties(logEvent) to get structured properties.
  • +
+

⚠️ Don't forget to Register-your-custom-component when loading NLog config!

+

Example

+
using NLog;
+using NLog.Config;
+using NLog.Targets;
+
+namespace MyNamespace 
+{ 
+    [Target("MyFirst")] 
+    public sealed class MyFirstTarget : AsyncTaskTarget
+    { 
+        public MyFirstTarget()
+        {
+            this.IncludeEventProperties = true; // Include LogEvent Properties by default
+        }
+
+        public Layout Host { get; set; } = "localhost";
+
+        protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
+        { 
+            string logMessage = this.RenderLogEvent(this.Layout, logEvent); 
+            string hostName = this.RenderLogEvent(this.Host, logEvent); 
+            IDictionary<string,object> logProperties = this.GetAllProperties(logEvent);
+            return SendTheMessageToRemoteHost(hostName, logMessage, logProperties); 
+        } 
+
+        private async Task SendTheMessageToRemoteHost(string hostName, string message, IDictionary<string, object> properties) 
+        { 
+            // TODO - write me 
+        } 
+    } 
+}
+
+

AsyncTaskTarget Features

+

AsyncTaskTarget has an internal queue (Initial capacity is 10000), so if the Tasks constantly performs timeout then at one point the queue will be filled. The OverflowAction will then take over (Default = Discard to avoid eating all memory).

+

Timeout and Retry Logic

+

There are several options:

+
    +
  • TaskTimeoutSeconds - How many seconds a Task is allowed to run before it is cancelled (Default 150 secs)
  • +
  • RetryDelayMilliseconds - How many milliseconds to wait before next retry (Default 500ms, and will be doubled on each retry).
  • +
  • RetryCount - How many attempts to retry the same Task, before it is aborted (Default 0)
  • +
+

If wanting to have more control of when to retry (Checking the Exception), or perform connection recovery on failure, then override this method:

+
protected override bool RetryFailedAsyncTask(Exception exception,
+                                             CancellationToken cancellationToken,
+                                             int retryCountRemaining,
+                                             out TimeSpan retryDelay)
+{
+   return base.RetryFailedAsyncTask(exception,
+                                    cancellationToken,
+                                    retryCountRemaining,
+                                    out retryDelay); // Default behavior
+}
+
+

Batch Logic

+

Activated when overriding this method:

+
protected override Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken)
+{
+   // TODO - write batch
+}
+
+

There are several options: +- BatchSize - Gets or sets the number of log events that should be processed in a batch by the lazy writer thread. (Default 1) +- TaskDelayMilliseconds - How many milliseconds to delay the actual write operation to optimize for batching (Default 1 ms) +- QueueLimit - Gets or sets the limit on the number of requests in the lazy writer thread request queue (Default 10000) +- OverflowAction - Gets or sets the action to be taken when the lazy writer thread request queue count exceeds the set limit (Default Discard).

+

TargetWithContext Features

+

AsyncTaskTarget inherits the TargetWithContext features, that allows one to configure additional context properties for extended structured logging capabilities.

+
<target type="MyFirst" name="first" includeEventProperties="true">
+   <contextproperty name="MachineName" layout="${machinename}" />
+   <contextproperty name="ThreadId" layout="${threadid}" />
+</target>
+
+

The structured properties can be retrieved inside WriteAsyncTask-method by calling this.GetAllProperties(logEvent).

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-write-a-custom-layout-renderer/index.html b/wiki/How-to-write-a-custom-layout-renderer/index.html new file mode 100644 index 000000000..9f5c6c065 --- /dev/null +++ b/wiki/How-to-write-a-custom-layout-renderer/index.html @@ -0,0 +1,1430 @@ + + + + + + + + How to write a custom layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Layout renderers can capture, format and output additional context details that can be used by NLog Layouts. There are 2 ways to create a custom layout renderer.

+

1) Register custom lambda-delegate-function with a symbol-name (Introduced with NLog v4.4) +2) Register custom class that inherits from LayoutRenderer that also supports additional configuration options.

+

⚠️ Don't forget to Register-your-custom-component when loading NLog config!

+

Lambda Function

+

NLog 4.7 introduces a fluent registration API using LogManager.Setup(), where you create a layout renderer with a lambda:

+
NLog.LogManager.Setup().SetupExtensions(s =>
+   s.RegisterLayoutRenderer("trace_id", (logevent) => CorrelationIdentifier.TraceId.ToString())
+);
+
+

NLog 4.4 was the first edition to support lambda function will accept 1 or 2 parameters and should return a string.

+
    +
  • 1 parameter: the logEventInfo.
  • +
  • 2 parameters: logEventInfo and the current NLog config.
  • +
+

Examples

+
//register ${text-fixed}
+LayoutRenderer.Register("text-fixed", (logEvent) => "2");
+
+//register ${trace-identifier}
+LayoutRenderer.Register("trace-identifier", (logEvent) => HttpContext.Current.TraceIdentifier);
+
+//Using logEventInfo, ${message-length}
+LayoutRenderer.Register("message-length", (logEvent) => logEvent.FormattedMessage.Length);
+
+//Using config, ${targetCount}
+LayoutRenderer.Register("targetCount",(logEvent, config) => config.AllTargets.Count);
+
+

ASP.NET HttpContext

+

Need the HTTP-context (e.g. Request, Session etc) for ASP.NET or ASP.NET Core?

+

Include the NLog.Web (ASP.NET Classic) or NLog.Web.AspNetCore nuget-package.

+

And usage:

+
using NLog;
+
+LogManager.Setup().SetupExtensions(builder =>
+{
+    builder.RegisterAspNetLayoutRenderer("SessionItem1",
+        (logEventInfo, httpContext, loggingConfiguration)
+            => httpContext.Session.GetString("SessionItem")); // usage ${SessionItem1}
+});
+
+

Class

+

Create a class that inherits from NLog.LayoutRenderers.LayoutRenderer, set the [LayoutRenderer("your-name")] on the class and override the Append(StringBuilder builder, LogEventInfo logEvent) method. +Invoke in this method builder.Append(..) to render your custom layout renderer.

+

Example

+

We create a ${hello-world} layout renderer, which renders..."hello world!".

+
[LayoutRenderer("hello-world")]
+public class HelloWorldLayoutRenderer : LayoutRenderer
+{
+    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
+    {
+        builder.Append("hello world!");
+    }
+}
+
+

How to pass configuration options to the layout render?

+

Use public class-properties for configuring the LayoutRenderer:

+
[LayoutRenderer("hello-world")]
+public class HelloWorldLayoutRenderer : LayoutRenderer
+{
+        /// <summary>
+        /// New special option
+        /// </summary>
+        [DefaultParameter]
+        public string SpecialOption{ get; set; }
+
+        /// <summary>
+        /// New extra option
+        /// </summary>
+        public bool ExtraOption{ get; set; }
+
+

The [DefaultParameter]-attribute can only be assigned to one class-property, and gives the ability to assign the class-property-value without specifying the class-property-name.

+

Example usages:

+
    +
  • ${hello-world:Bonus} - Assigns SpecialOption = Bonus.
  • +
  • ${hello-world:SpecialOption=Bonus} - Assigns SpecialOption = Bonus.
  • +
  • ${hello-world:ExtraOption=true} - Assigns ExtraOption = true.
  • +
  • ${hello-world:Bonus:ExtraOption=true} - Assigns SpecialOption = Bonus and ExtraOption = true.
  • +
+

If additional option-validation are required, then override void InitializeLayoutRenderer() and implement the necessary validation, and throw NLogConfigurationException("...") when issues are detected.

+

How to optimize performance for the layout renderer

+

NLog will automatically capture relevant context state, when using AsyncWrapper-target to perform actual writing on background-thread (to avoid logging objects after they have been disposed). The following class-attributes can used for the LayoutRenderer that enables additional performance:

+
    +
  • [ThreadAgnostic]
  • +
+

LayoutRenderer does not capture state from the application-thread logging. Ex. ${threadid} cannot be [ThreadAgnostic].

+

For LayoutRenderer marked as [ThreadAgnostic] then NLog can skip the overhead of capturing state.

+

If just a single LayoutRenderer in a Layout is not marked as [ThreadAgnostic], then NLog introduces the overhead of state capture.

+
    +
  • [ThreadSafe]
    +

    Introduced with NLog 4.5.3, and made obsolete with NLog 5.0 that expects all to be threadsafe.

    +
    +
  • +
+

LayoutRenderer will render correct output regardless of the number of application-threads running inside.

+

For LayoutRenderer marked as [ThreadSafe] then NLog will skip using "global" locks when capturing state, thus application-threads will + not experience lock-congestion inside NLog.

+

If just a single LayoutRenderer in a Layout is not marked as [ThreadSafe], then NLog introduces the overhead of "global" lock when doing state capture.

+

Example of class-attributes for LayoutRenderer:

+
using NLog.Config;
+
+[LayoutRenderer("hello-world")]
+[ThreadAgnostic]
+public class HelloWorldLayoutRenderer : LayoutRenderer
+{
+    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
+    {
+        builder.Append("hello world!");
+    }
+}
+
+

Multiple type-alias attributes

+

NLog 5.0 enables you to have multiple type-aliases for a single class. Before one had to inherit from the same class to provide additional type-names.

+
[LayoutRenderer("hello-world")]   // ${hello-world}
+[LayoutRenderer("hello-earth")]   // ${hello-earth}
+public class HelloWorldLayoutRenderer : LayoutRenderer
+{
+
+

The type-alias can then be used when wanting to use the LayoutRenderer in NLog SimpleLayout.

+

Notice NLog 5.0 automatically ignores dashes - in type-alias, so no extra alias is needed for this: Ex. ${helloworld}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-write-a-custom-target-for-structured-logging/index.html b/wiki/How-to-write-a-custom-target-for-structured-logging/index.html new file mode 100644 index 000000000..3faf0853e --- /dev/null +++ b/wiki/How-to-write-a-custom-target-for-structured-logging/index.html @@ -0,0 +1,1376 @@ + + + + + + + + How to write a custom target for structured logging - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +
+

Introduced with NLog 4.5

+
+

It is really easy:

+
    +
  • Create a class that inherits from NLog.Targets.TargetWithContext
  • +
  • Override the Write(LogEventInfo logEvent) method.
  • +
  • In the body of this method invoke this.RenderLogEvent(this.Layout, logEvent) to get the message text, and invoke this.GetAllProperties(logEvent) to get structured properties.
  • +
+

⚠️ Don't forget to Register-your-custom-component when loading NLog config!

+
+

See also the updated How to write a custom async target

+
+

Example

+
using NLog;
+using NLog.Config;
+using NLog.Targets;
+
+namespace MyNamespace 
+{ 
+    [Target("MyFirst")] 
+    public sealed class MyFirstTarget : TargetWithContext
+    { 
+        public MyFirstTarget()
+        {
+            this.IncludeEventProperties = true; // Include LogEvent Properties by default
+        }
+
+        public Layout Host { get; set; } = "localhost";
+
+        protected override void Write(LogEventInfo logEvent) 
+        { 
+            string logMessage = this.RenderLogEvent(this.Layout, logEvent); 
+            string hostName = this.RenderLogEvent(this.Host, logEvent); 
+            IDictionary<string,object> logProperties = this.GetAllProperties(logEvent);
+            SendTheMessageToRemoteHost(hostName, logMessage, logProperties); 
+        } 
+
+        private void SendTheMessageToRemoteHost(string hostName, string message, IDictionary<string, object> properties) 
+        { 
+            // TODO - write me 
+        } 
+    } 
+}
+
+

TargetWithContext Features

+

Additional Context Properties

+

Users can easily configure additional context information:

+
<target type="MyFirst" name="first">
+   <contextproperty name="MachineName" layout="${machinename}" />
+   <contextproperty name="ThreadId" layout="${threadid}" />
+</target>
+
+

Without needing to inject the details upfront when doing the logging. It is automatically captured by the NLog engine.

+

Include ScopeContext

+

ScopeContext Properties can be used to provide context-specific details (Ex. request-correlationid from ILogger.BeginScope).

+

To automatically capture properties injected into ScopeContext (Before NLog 5.0 it was called IncludeMDLC)

+
<target type="MyFirst" name="first" includeScopeProperties="true">
+   ...
+</target>
+
+

Custom Merge Properties

+

TargetWithContext will by default ensure that all captured property-values are included in output, and will automatically generate new unique key-name when name-collission. If wanting to merge properties, so one context can override another context, then one can do it like this:

+
<target type="MyFirst" excludeProperties="RequestId">
+     <contextproperty name="RequestId" layout="${event-properties:RequestId:whenEmpty=${scope-property=RequestId:whenEmpty=DefaultValue}}" />
+</sometarget>
+
+

Instead of DefaultValue then you could also use one of the NLog LayoutRenderers available. Ex. ${aspnet-TraceIdentifier} or ${activity:property=TraceId}. Or alternative skip whenEmpty=DefaultValue and rely on IncludeEmptyValue="false" (default).

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/How-to-write-a-custom-target/index.html b/wiki/How-to-write-a-custom-target/index.html new file mode 100644 index 000000000..a4bd4e261 --- /dev/null +++ b/wiki/How-to-write-a-custom-target/index.html @@ -0,0 +1,1381 @@ + + + + + + + + How to write a custom target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

It’s really easy:

+
    +
  1. Create a class that inherits from NLog.Targets.TargetWithLayout
  2. +
  3. Override the Write() method.
  4. +
  5. In the body of the method invoke this.Layout.Render() to get the message text, then send the text to the destination media.
  6. +
+

⚠️ Don't forget to Register-your-custom-component when loading NLog config!

+
+

See also the updated How to write a custom target for structured logging

+

See also the updated How to write a custom async target

+
+

Example

+

This is a skeleton target that writes messages to the specified host:

+
using NLog;
+using NLog.Config;
+using NLog.Targets;
+
+namespace MyNamespace 
+{ 
+    [Target("MyFirst")]
+    public sealed class MyFirstTarget: TargetWithLayout 
+    {
+        public Layout Host { get; set; } = "localhost";
+
+        protected override void Write(LogEventInfo logEvent) 
+        { 
+            string logMessage = RenderLogEvent(this.Layout, logEvent);
+            string hostName = RenderLogEvent(this.Host, logEvent);
+            SendTheMessageToRemoteHost(hostName, logMessage);
+        } 
+
+        private void SendTheMessageToRemoteHost(string hostName, string message) 
+        { 
+            // TODO - write me 
+        } 
+    } 
+}
+
+

How to pass configuration options to the target?

+

In the example above then one can see how the Host-property is used. Having a public property that sets the required configuration parameters is enough for NLog to use it.

+

Each attribute that you put in the <target /> definition gets passed to the appropriate public property. NLog takes care of the appropriate conversions necessary so that you can use integer, string, datetime, boolean parameters. Check also Properties-constraints-for-custom-extensions

+

It is recommended to use NLog Layouts or NLog Layout<T> for NLog Target Configuration options, as it will allow users to provide configuration-values from NLog LayoutRenderers (Ex. from appsettings.json, app.config or environment-variables)

+

How to handle object lifetime

+

When needing to create interfaces to external framework or start background-threads, then it is recommended to override InitializeTarget and close/release resources again in CloseTarget.

+
namespace MyNamespace
+{
+    [Target("MyFirst")]
+    public sealed class MyFirstTarget: TargetWithLayout
+    {
+        protected override void InitializeTarget()
+        {
+            base.InitializeTarget();
+            // TODO Custom Init Logic
+        }
+
+        protected override void CloseTarget()
+        {
+            // TODO Custom Close Logic
+            base.CloseTarget();
+        }
+    }
+}
+
+

It is possible for the same target object to be initialized and closed many times during the lifetime of the application. It is recommended not to use the constructor to start background-threads or initialize interfaces, but merely focus on setting up initial state without starting anything. It is possible to override the Dispose-method, but this method will only be called at the end of application-lifetime.

+

Multiple type-alias attributes

+

NLog 5.0 enables you to have multiple type-aliases for a single class. Before one had to inherit from the same class to provide additional type-aliases.

+
[Target("MyFirst")]
+[Target("MyInitial")]
+public sealed class MyFirstTarget: TargetWithLayout 
+{
+
+

The type-alias can then be used when wanting to use the target in the NLog Configuration File. Ex. <target type="MyFirst" name="..." />

+

Notice NLog 5.0 automatically ignores dashes - in type-aliases, so no extra alias is needed for this: Ex. <target type="My-First" name="..." />

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/IIS-site-name-Layout-Renderer/index.html b/wiki/IIS-site-name-Layout-Renderer/index.html new file mode 100644 index 000000000..b9eead9e0 --- /dev/null +++ b/wiki/IIS-site-name-Layout-Renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + IIS site name Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

IIS site name - printing HostingEnvironment.SiteName

+
+

Platforms Supported: All (Supported in AspNet and AspNetCore)

+
+

Configuration Syntax

+
${iis-site-name}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Identity-layout-renderer/index.html b/wiki/Identity-layout-renderer/index.html new file mode 100644 index 000000000..8fd000b14 --- /dev/null +++ b/wiki/Identity-layout-renderer/index.html @@ -0,0 +1,1338 @@ + + + + + + + + Identity layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Thread identity information (name and authentication information).

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${identity:authType=Boolean:separator=String:name=Boolean
+          :isAuthenticated=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • authType - Indicates whether to render Thread.CurrentPrincipal.Identity.AuthenticationType.Boolean Default: True
  • +
  • separator - Separator to be used when concatenating parts of identity information. Default: :
  • +
  • name - Indicates whether to render Thread.CurrentPrincipal.Identity.Name.Boolean Default: True
  • +
  • isAuthenticated - Indicates whether to render Thread.CurrentPrincipal.Identity.IsAuthenticated.Boolean Default: True
  • +
+

Notes

+ +

Note .NET Core 3

+

Set AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal) in the Main method of your application, otherwise this renderer could render empty unexpectedly. (Read more)

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ImpersonatingWrapper-target/index.html b/wiki/ImpersonatingWrapper-target/index.html new file mode 100644 index 000000000..77d8e0b59 --- /dev/null +++ b/wiki/ImpersonatingWrapper-target/index.html @@ -0,0 +1,1383 @@ + + + + + + + + ImpersonatingWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Impersonates another user for the duration of the write (Ex. give access-permission to file-target)

+
+

Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsIdentity since NLog 5.0

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="ImpersonatingWrapper"
+          name="String"
+          userName="Layout"
+          password="Layout"
+          domain="Layout"
+          revertToSelf="Boolean"
+          impersonationLevel="Enum"
+          logOnType="Enum"
+          logOnProvider="Enum">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Impersonation Options

+
    +
  • +

    userName - Username to change context to.

    +
    +

    NLog.WindowsIdentity v5.3 changed data-type from String to Layout

    +
    +
  • +
  • +

    password - User account password.

    +
    +

    NLog.WindowsIdentity v5.3 changed data-type from String to Layout

    +
    +
  • +
  • +

    domain - Windows domain name for user account. Default: .

    +
    +

    NLog.WindowsIdentity v5.3 changed data-type from String to Layout

    +
    +
  • +
  • +

    revertToSelf - Indicates whether to revert to the credentials of the process instead of impersonating another user. Boolean Default: False

    +
  • +
  • +

    impersonationLevel - Required impersonation level.
    +Possible values:

    +
  • +
  • Anonymous - Anonymous Level.
  • +
  • Delegation - Delegation Level.
  • +
  • Identification - Identification Level.
  • +
  • +

    Impersonation - Impersonation Level.

    +
  • +
  • +

    logOnType - Logon Type.
    +Possible values:

    +
  • +
  • Batch - Batch Logon.
  • +
  • Interactive - Interactive Logon.
  • +
  • Network - Network Logon.
  • +
  • NetworkClearText - Network Clear Text Logon.
  • +
  • NewCredentials - New Network Credentials.
  • +
  • +

    Service - Logon as a Service.

    +
  • +
  • +

    logOnProvider - Type of the logon provider.
    +Possible values:

    +
  • +
  • Default - Use the standard logon provider for the system.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/InstallContext-layout-renderer/index.html b/wiki/InstallContext-layout-renderer/index.html new file mode 100644 index 000000000..dccf07041 --- /dev/null +++ b/wiki/InstallContext-layout-renderer/index.html @@ -0,0 +1,1322 @@ + + + + + + + + InstallContext layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Installation Context Parameter Value.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${install-context:parameter=String}
+
+

See also Installing targets

+

See also InstallNLogConfig

+

Parameters

+

Rendering Options

+
    +
  • parameter - Name of the parameter. Required
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Installing-targets/index.html b/wiki/Installing-targets/index.html new file mode 100644 index 000000000..4b4b1ae96 --- /dev/null +++ b/wiki/Installing-targets/index.html @@ -0,0 +1,1362 @@ + + + + + + + + Installing targets - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Some targets support installing. Current the following targets support installing

+
    +
  • Database target
  • +
  • EventLogger target
  • +
  • PerformanceCounter target
  • +
+

Install

+

Install all targets used in the config:

+
LogManager.Configuration.Install(new InstallationContext());
+
+

Uninstall

+

Uninstall all targets used in the config:

+
LogManager.Configuration.Uninstall(new InstallationContext());
+
+

Example install database target

+
<target xsi:type="Database" name="db"
+        connectionStringName="LoggingDatabase">
+    <install-command>
+        <text>
+            <!--
+            NOTE: call LogManager.Configuration.Install(new InstallationContext()); 
+                  to execute this query.
+            -->
+            CREATE TABLE ${var:logTableName} (
+            Id bigint primary key not null identity(1,1),
+            Logged datetime2,
+            Level nvarchar(10),
+            LogMessage nvarchar(max),
+            MessageUid uniqueidentifier,
+            MessagePartUid uniqueidentifier,
+            MessagePartDataUid uniqueidentifier,
+            )
+        </text>
+        <ignoreFailures>false</ignoreFailures>
+    </install-command>
+
+

Troubleshooting installation issues

+

Installation log

+

You can enable the installation log by overriding the default output stream in your InstallationContext. For example, to have the installation log printed out to console, you can use:

+
LogManager.Configuration.Install(new InstallationContext(Console.Out));
+
+

You can also redirect the installation log to a string in memory:

+
var stringWriter = new StringWriter();
+LogManager.Configuration.Install(new InstallationContext(stringWriter));
+var installationLog = stringWriter.ToString();   // retrieve the installation output
+
+

Note that the log output can also be accessed via InstallationContext.LogOutput:

+
// This is equivalent to the previous example
+var installationContext = new InstallationContext(new StringWriter())
+LogManager.Configuration.Install(installationContext);
+var installationLog = installationContext.LogOutput.ToString();
+
+

A note on exceptions

+

Except for application critical exceptions (OutOfMemoryException. StackOverflowException and ThreadAbortException), LogManager.Configuration.Install() will not rethrow any other exception, even when NLog is Logging-troubleshooting#troubleshooting-steps.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Internal-Logging/index.html b/wiki/Internal-Logging/index.html new file mode 100644 index 000000000..34e57df80 --- /dev/null +++ b/wiki/Internal-Logging/index.html @@ -0,0 +1,1393 @@ + + + + + + + + Internal Logging - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

When Troubleshooting NLog logging issues, then it is a good idea to enable internal logging, which often helps to identify where the problem is. Internal log output can be sent to a file, console window or both.

+

Enabling internal logging using configuration file

+

When you configure NLog using Configuration File, you can enable internal logging by setting the following attribute on the <nlog> element:

+
    +
  • internalLogLevel="Off|Trace|Debug|Info|Warn|Error|Fatal" – determines internal log level. The higher the level, the less verbose the internal log output.
  • +
  • internalLogFile="file.txt" - adding internalLogFile cause NLog to write its internal debugging messages to the specified file. This includes any exceptions that may be thrown during logging.
  • +
+

Notice only basic layouts are supported, as the internal log needs to be as simple/stable as possible: + - Environment Variables e.g. %APPDATA% or %HOME% or %PROGRAMDATA% (Introduced with NLog 4.6+). + - ${currentdir} (Introduced with NLog 4.6+ but without options). + - ${basedir} (Introduced with NLog 4.6+ but without options). + - ${tempdir} (Introduced with NLog 4.6+ but without options). + - ${processdir} (Introduced with NLog 4.7.1+ but without options). + - ${commonApplicationDataDir}, ${userApplicationDataDir}, ${userLocalApplicationDataDir} (Introduced with NLog v5 but without options) +* internalLogToConsole="false|true" – sends internal logging messages to the console. +* internalLogToConsoleError="false|true" – sends internal logging messages to the console error output (stderr). +* internalLogIncludeTimestamp="false|true" - indicates whether timestamps should be included in the internal log output (NLog 4.3+)

+

Here is an example of a configuration file which enables internal logging to a file:

+
<nlog internalLogFile="c:\nlog-internal.txt" internalLogLevel="Debug">
+   <targets>
+      <!-- target configuration here -->
+   </targets>
+   <rules>
+      <!-- log routing rules -->
+   </rules>
+</nlog>
+
+

If not getting internal logger output, then make sure the NLog.config file has Build Action set to Copy if newer. See also Logging-troubleshooting. Alternative try to activate Internal Logging programmatically.

+

Enabling internal logging programmatically

+

Internal logging can be configured through code by setting the following properties on InternalLogger class: +* NLog.Common.InternalLogger.LogLevel - specifies internal logging level +* NLog.Common.InternalLogger.LogFile - specifies name of the log file (null will disable logging to a file) +* NLog.Common.InternalLogger.LogToConsole - enables or disables logging to the console +* NLog.Common.InternalLogger.LogToConsoleError - enables or disables logging to the console error stream +* NLog.Common.InternalLogger.LogWriter - specifies a TextWriter object to use for logging. +* NLog.Common.InternalLogger.IncludeTimestamp - enables or disables whether timestamps should be included in the internal log output

+
+

Introduced with NLog 4.3 +* NLog.Common.InternalLogger.InternalEventOccurred - event-callback for every internal logger event. +Introduced with NLog 6.0 and replaces the now obsolete LogMessageReceived

+
+

For best diagnostic output then make sure to enable NLog InternalLogger, before creating the first NLog Logger-object.

+

Here is an example of activating internal logging from code:

+
using NLog;
+
+class Program
+{
+  static void Main()
+  {
+    // enable internal logging to the console
+    NLog.Common.InternalLogger.LogToConsole = true;
+
+    // enable internal logging to a file
+    NLog.Common.InternalLogger.LogFile = "c:\\nlog-internal.txt"; // On Linux "/home/nlog-internal.txt"
+
+    // enable internal logging to a custom TextWriter. Ex. TextWriter writer = File.CreateText("C:\\perl.txt")
+    NLog.Common.InternalLogger.LogWriter = new StringWriter();
+
+    // set internal log level
+    NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Debug;
+
+    // Perform test output, ensure first NLog Logger is created after InternalLogger is enabled.
+    NLog.LogManager.GetLogger("Test").Info("Hello World");
+  }
+}
+
+

Enabling internal logging using environment variables

+

Before NLog 5.0 then environment variables and app.config settings would be automatically be applied on startup. But because of the startup overhead, then this has been disabled. Instead one now have to explicitly activate this behavior:

+
NLog.LogFactory.Setup().SetupInternalLogger(b => b.SetupFromEnvironmentVariables())
+
+

These are environment variables which control internal logging: +* NLOG_INTERNAL_LOG_LEVEL - sets the internal logging level. The available values are Trace, Debug, Info, Warn, Error or Fatal - the default is Info which should be appropriate for most cases, to get more detailed logging - set it to Debug or Trace. +* NLOG_INTERNAL_LOG_FILE - if this variable is found in the environment NLog will save internal log to the specified file. The file must be writable by the current user or it will not be created. +* NLOG_INTERNAL_LOG_TO_CONSOLE - if this variable is found in the environment, will outputs internal diagnostic information to the console +* NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR - sets internalLogToConsoleError +* NLOG_INTERNAL_INCLUDE_TIMESTAMP - sets internalLogIncludeTimestamp (introduced in NLog 4.3)

+

Description of InternalLogger LogLevels

+
    +
  • LogLevel.Fatal - Just before application is going to crash.
  • +
  • LogLevel.Error - Logging pipeline has failed, and logevents has been discarded.
  • +
  • LogLevel.Warn - Detected invalid configuration but can recover. Detected connection lost but can recover.
  • +
  • LogLevel.Info - Application lifetime events like logging configuration loaded, and shutting down logging engine.
  • +
  • LogLevel.Debug - Reporting interesting events for detailed diagnostics. Having reflection issues when serializing logevents.
  • +
  • LogLevel.Trace - Dumping verbose configuration details.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/JSON-Encode-Layout-Renderer/index.html b/wiki/JSON-Encode-Layout-Renderer/index.html new file mode 100644 index 000000000..19c20b25a --- /dev/null +++ b/wiki/JSON-Encode-Layout-Renderer/index.html @@ -0,0 +1,1335 @@ + + + + + + + + JSON Encode Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Escapes output of another layout using JSON rules.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${json-encode:jsonEncode=Boolean:inner=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:jsonEncode=Boolean}
+
+

Parameters

+

Transformation Options

+
    +
  • jsonEncode - Indicates whether to apply JSON encoding. Boolean Default: True
  • +
  • escapeUnicode - Indicates whether it should escape unicode characters (non-ascii) using \u. Boolean Default: True
    +

    Introduced in NLog 4.4.7

    +
    +
  • +
  • inner - Wrapped layout. Layout
  • +
  • EscapeForwardSlash - Should forward slashes be escaped? If true, / will be converted to \/. Default true
    +

    Introduced in NLog 4.6.8

    +
    +
  • +
+

Example

+
${event-properties:item=MyValue:jsonEncode=true}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/JsonArrayLayout/index.html b/wiki/JsonArrayLayout/index.html new file mode 100644 index 000000000..a6b5f835e --- /dev/null +++ b/wiki/JsonArrayLayout/index.html @@ -0,0 +1,1331 @@ + + + + + + + + JsonArrayLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders to JSON-Array. See also JsonLayout

+
+

Platforms Supported: All

+

Introduced with NLog 5.0

+
+
<target name="jsonFile" xsi:type="File" fileName="log-file.json" >
+      <layout xsi:type="JsonArrayLayout">
+            <item type='SimpleLayout' text='${date:format=o}' />
+            <item type='SimpleLayout' text='${level}' />
+            <item type='SimpleLayout' text='${message}' />
+       </layout>
+</target>
+
+

Example output:

+
[ "2010-01-01T12:34:56Z", "Info", "hello world" ]
+
+

Parameters

+
    +
  • Items
  • +
  • type - Required. The type of Layout (Ex. SimpleLayout, JsonLayout, etc.)
  • +
  • suppressSpaces - Enable to suppress extra spaces in the output JSON. Default: false.
  • +
  • renderEmptyObject - When no array-items, then it should still render empty array-value []. Default: true.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/JsonLayout/index.html b/wiki/JsonLayout/index.html new file mode 100644 index 000000000..9e4cd1ebb --- /dev/null +++ b/wiki/JsonLayout/index.html @@ -0,0 +1,1457 @@ + + + + + + + + JsonLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders to JSON.

+
+

Platforms Supported: All

+

Introduced with NLog 4.0

+
+
<target name="jsonFile" xsi:type="File" fileName="log-file.json" >
+      <layout xsi:type="JsonLayout" includeEventProperties="Boolean" excludeProperties="Comma-separated list (string)">
+              <attribute name="time" layout="${longdate}" />
+              <attribute name="level" layout="${level:upperCase=true}"/>
+              <attribute name="message" layout="${message}" />
+       </layout>
+</target>
+
+

Example output:

+
{ "time": "2010-01-01 12:34:56.0000", "level": "ERROR", "message": "hello, world" }
+
+

Added in NLog 4.1

+

Optional encode parameter.

+

You can disable JSON encoding by setting encode="false". This will let you to write any string without JSON encoding. Including custom JSON (Ex. boolean/numeric values)

+
<attribute name="OrderId" layout="${event-properties:item=IntegerOrderId}" encode="false" />
+<attribute name="Details" layout="${event-properties:item=JsonDocDetails}" encode="false" />
+
+

Parameters

+
    +
  • Attribute
  • +
  • name - Required. The name of the JSON-key
  • +
  • layout - The layout for the JSON-value (Can be a nested JsonLayout)
  • +
  • encode - Enable or disable JSON encoding for the attribute. Default = true + > Introduced in NLog 4.1
  • +
  • escapeUnicode - Escape unicode-characters (non-ascii) using \u. Default = true + > Introduced in NLog 4.4.7
  • +
  • IncludeEmptyValue - Include attribute when Layout output is empty. Default = false + > Introduced in NLog 4.5
  • +
  • EscapeForwardSlash - Should forward slashes also be escaped. Default = false, + > Introduced in NLog 4.6.8. Before NLog 5.0 the default was true. After NLog 6.0 it has no effect.
  • +
  • suppressSpaces - Enable to suppress extra spaces in the output JSON. Default = true.
    +

    Introduced in NLog 4.1. Before NLog 6.0 the default was false

    +
    +
  • +
  • indentJson - Enables indent for JSON pretty format with newlines. Default = false.
    +

    Introduced in NLog v5.1.4

    +
    +
  • +
  • renderEmptyObject - When no json-attributes, then it should still render empty object-value {}. Default = true.
    +

    Introduced in NLog 4.3.7

    +
    +
  • +
  • IncludeGdc - Indicates whether to include contents of the GDC-Layout-Renderer (GDC) dictionary. Default = false.
    +

    Introduced in NLog 4.4.10

    +
    +
  • +
  • IncludeEventProperties - Include LogEvent Properties dictionary? Default = false.
    +

    Before NLog 5.0 option was named IncludeAllProperties

    +
    +
  • +
  • IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default = false.
    +

    Before NLog 5.0 option was named IncludeMdlc or IncludeMdc

    +
    +
  • +
  • excludeProperties - comma separated string with names which properties to exclude. Only used when includeEventProperties is true. Case insensitive. Default empty +When a name contains a comma, single quote the value. E.g. 'value,withquote',value2.
    +

    Introduced in NLog 4.4

    +
    +
  • +
  • excludeEmptyProperties - Exclude event properties with value null or empty (Also checks GDC, MDC, MDLC).
    +

    Introduced in NLog 4.7.7

    +
    +
  • +
  • EscapeUnicode - escape non-ascii characters? Boolean. Default true.
    +

    Introduced in NLog 4.4.7

    +
    +
  • +
  • MaxRecursionLimit - How far should the JSON serializer follow object references before backing off. Integer. Default 1 (0 = No object reflection)
    +

    Introduced in NLog 4.5. Before NLog 5.0 the default was 0(No object reflection)

    +
    +
  • +
  • EscapeForwardSlash - Should forward slashes be escaped? If true, / will be converted to \/. Default = false.
    +

    Introduced in NLog 4.6.8. Before NLog 5.0 the default was true

    +
    +
  • +
  • DottedRecursion - Flatten object-property-names when using IncludeEventProperties for compact Json-documents. Default = false.
    +

    Introduced in NLog 6.1

    +
    +
  • +
+

Advanced examples

+

From the API:

+
var jsonLayout = new JsonLayout
+{
+    Attributes =
+    {
+        new JsonAttribute("time", "${longdate}"),
+        new JsonAttribute("level", "${level}"),
+        new JsonAttribute("message", "${message}"),
+        new JsonAttribute("properties", new JsonLayout { IncludeEventProperties = true, MaxRecursionLimit = 2 }, encode: false),
+        new JsonAttribute("exception", new JsonLayout
+        {
+            Attributes =
+            {
+                new JsonAttribute("type", "${exception:format=type}"),
+                new JsonAttribute("message", "${exception:format=message}"),
+                new JsonAttribute("stacktrace", "${exception:format=tostring}"),
+            }
+        },
+        encode: false) // don't escape layout
+    }
+};
+
+

From XML

+
<nlog>
+  <targets>
+    <target xsi:type="File" name="jsonFile" fileName="c:\temp\nlog-json-nested-${shortdate}.log">
+      <layout xsi:type="JsonLayout">
+         <attribute name="time" layout="${longdate}" />
+         <attribute name="level" layout="${level}" />
+         <attribute name="message" layout="${message}" />
+         <attribute name="properties" encode="false" >
+             <layout xsi:type="JsonLayout" includeEventProperties="true" maxRecursionLimit="2" />
+         </attribute>
+         <attribute name="exception" encode="false">
+             <layout xsi:type="JsonLayout">
+                 <attribute name="type" layout="${exception:format=type}" />
+                 <attribute name="message" layout="${exception:format=message}" />
+                 <attribute name="stacktrace" layout="${exception:format=tostring}" />
+             </layout>
+         </attribute>
+      </layout>
+    </target>
+  </targets>
+  <rules>
+      <logger name="*" minlevel="Debug" writeTo="jsonFile" />
+  </rules>
+</nlog>
+
+

will render: { "time": "2016-10-30 13:30:55.0000", "level": "Info", "message": "this is message", "properties": { "myProperty": "myValue" }, "exception": { "type": "System.NullReferenceException", "message": "null is bad!" } }

+

pretty printed:

+
{
+  "time": "2016-10-30 13:30:55.0000",
+  "level": "Info",
+  "message": "this is message",
+  "properties": {
+    "myProperty": "myValue"
+  },
+  "exception": {
+    "type": "System.NullReferenceException",
+    "message": "null is bad!"
+  }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Layout-Renderers/index.html b/wiki/Layout-Renderers/index.html new file mode 100644 index 000000000..33fe23d4e --- /dev/null +++ b/wiki/Layout-Renderers/index.html @@ -0,0 +1,1315 @@ + + + + + + + + Layout Renderers - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Layout renderers are template macros that are used in Layouts, e.g. ${message}, ${level} etc

+

Layout Renderers

+

List of available layout renderers can be found here: https://nlog-project.org/config/?tab=layout-renderers

+

NLog can also be extended with new custom layout renderers. See also: Extending NLog

+

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}

+

Passing Custom Values to a Layout

+

Even though the layout renderers provide many pre-defined values, you may need to pass application specific values to your Layouts. You can provide own Context state, that can then be rendered by different Layouts. For example by using LogEvent Properties, that can be rendered using using the ${event-properties} renderer.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Layout/index.html b/wiki/Layout/index.html new file mode 100644 index 000000000..c0f1cc46a --- /dev/null +++ b/wiki/Layout/index.html @@ -0,0 +1,1307 @@ + + + + + + + + Layout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

See Layouts

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/LayoutWithHeaderAndFooter/index.html b/wiki/LayoutWithHeaderAndFooter/index.html new file mode 100644 index 000000000..951e5f273 --- /dev/null +++ b/wiki/LayoutWithHeaderAndFooter/index.html @@ -0,0 +1,1332 @@ + + + + + + + + LayoutWithHeaderAndFooter - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that supports header and footer.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target>
+    <layout xsi:type="LayoutWithHeaderAndFooter">
+      <!-- Layout Options -->
+      <layout xsi:type="layoutType">Layout</layout>
+      <header xsi:type="layoutType">Layout</header>
+      <footer xsi:type="layoutType">Layout</footer>
+
+    </layout>
+  </target>
+</targets>
+
+

Parameters

+

Layout Options

+
    +
  • layout - Body layout (can be repeated multiple times). Layout
  • +
  • header - Header layout. Layout
  • +
  • footer - Footer layout. Layout
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Layouts/index.html b/wiki/Layouts/index.html new file mode 100644 index 000000000..bdc71fc3a --- /dev/null +++ b/wiki/Layouts/index.html @@ -0,0 +1,1356 @@ + + + + + + + + Layouts - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

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

+

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"
+      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>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Left-layout-renderer/index.html b/wiki/Left-layout-renderer/index.html new file mode 100644 index 000000000..1f951828f --- /dev/null +++ b/wiki/Left-layout-renderer/index.html @@ -0,0 +1,1336 @@ + + + + + + + + Left layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Left part of a text.

+
+

Platforms Supported: All

+

Introduced in NLog 4.6

+
+

Related:

+ +

Configuration Syntax

+

Explicit usage:

+
${left:inner=Layout:length=Integer}
+
+

Ambient property truncate can be used as a shortcut (Introduced with NLog ver. 4.6.3)

+
${message:truncate=80}
+
+

Read more about using the Configuration File.

+

Parameters

+

Transformation Options

+
    +
  • +

    inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout

    +
  • +
  • +

    length - Length in characters. Integer Required.

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Level-layout-renderer/index.html b/wiki/Level-layout-renderer/index.html new file mode 100644 index 000000000..496ecd8aa --- /dev/null +++ b/wiki/Level-layout-renderer/index.html @@ -0,0 +1,1423 @@ + + + + + + + + Level layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The log level.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${level:format=Ordinal}
+
+

Alternatively, add padding to align the message.

+
${pad:padding=5:inner=${level:uppercase=true}}
+
+

Alternatively, truncate to align the message:

+
${level:format=TriLetter:uppercase=true}
+
+

Parameters

+
    +
  • uppercase - Output level in upper-case. Default: false
    +

    Introduced with NLog v5.0 to simplify default Layout, instead of using the ambient uppercase-property

    +
    +
  • +
  • format - Output format of the level. Introduced in 4.4.6 Default: Name
    + Possible values:
  • +
  • Name - Render the standard level name. + > Introduced in NLog 4.4.6
  • +
  • FullName - Render the full level name (Expands "Info" and "Warn") + > Introduced in NLog 4.7
  • +
  • FirstCharacter - Render the first character of the level. + > Introduced in NLog 4.4.6
  • +
  • Ordinal - Render the ordinal (aka number) for the level. + > Introduced in NLog 4.4.6
  • +
  • TriLetter - Renders LogLevel as 3 letter abbreviations (Trc, Dbg, Inf, Wrn, Err, Ftl) + > Introduced in NLog 5.0.5
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameFullNameTriLetterFirstCharacterOrdinal
TraceTraceTrcT0
DebugDebugDbgD1
InfoInformationInfI2
WarnWarningWrnW3
ErrorErrorErrE4
FatalFatalFtlF5
OffOffOffO6
+

Examples

+

Basic

+

Configuration:

+
${level}
+
+

Code:

+
logger.Debug("Test Message")
+
+

Result:

+
Debug
+
+

Format

+

Configuration:

+
${level:format=FirstCharacter}
+
+

Code:

+
logger.Debug("Test Message")
+
+

Result:

+
D
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/LimitingWrapper-target/index.html b/wiki/LimitingWrapper-target/index.html new file mode 100644 index 000000000..29ad8b913 --- /dev/null +++ b/wiki/LimitingWrapper-target/index.html @@ -0,0 +1,1337 @@ + + + + + + + + LimitingWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Limits the number of logs written to the wrapped target in a given time interval.

+
+

Platforms Supported: All

+

Introduced in NLog 4.4.

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="LimitingWrapper"
+          name="String"
+          messageLimit="Integer"
+          interval="TimeSpan">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Limiting Options

+
    +
  • +

    messageLimit - Indicates the maximum number of log events written per Interval. Log events in the current interval received after the message limit has been reached will be discarded. Integer Default: 1000

    +
  • +
  • +

    interval - Indicates a time interval in which messages will be written up to the maximum number of messages (messageLimit). TimeSpanDefault: "01:00" (1 hour)

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Literal-Layout-Renderer/index.html b/wiki/Literal-Layout-Renderer/index.html new file mode 100644 index 000000000..4aca6f65b --- /dev/null +++ b/wiki/Literal-Layout-Renderer/index.html @@ -0,0 +1,1333 @@ + + + + + + + + Literal Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A string literal.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${literal:text=String}
+
+

Parameters

+

Rendering Options

+
    +
  • text - Literal text.
  • +
+

Remarks

+

This is used to escape '${' sequence as ;${literal:text=${}'.

+

Examples

+

Basic

+

Configuration:

+
${literal:text=Some Text with ${ in it}
+
+

Code:

+
logger.Debug("Test Message")
+
+

Result:

+
Some Text with ${ in it
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Local-IP-Address-Layout-Renderer/index.html b/wiki/Local-IP-Address-Layout-Renderer/index.html new file mode 100644 index 000000000..59757e36d --- /dev/null +++ b/wiki/Local-IP-Address-Layout-Renderer/index.html @@ -0,0 +1,1324 @@ + + + + + + + + Local IP Address Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The local IP address whether IPv4 or IPv6 from NetworkInterface.GetAllNetworkInterfaces

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6

+

Introduced with NLog 4.6.8

+
+

Configuration Syntax

+
${local-ip:addressFamily=InterNetwork}
+
+

Parameters

+
    +
  • AddressFamily - Explicitly prioritize IP addresses from a certain AddressFamily (Ex. InterNetwork / InterNetworkV6)
  • +
+

Improving Performance

+

The lookup of the active IP-address on the local machine has a performance hit. For better performance then it is recommended to use it with cachedSeconds like this:

+
${local-ip:cachedSeconds=60}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Log-levels/index.html b/wiki/Log-levels/index.html new file mode 100644 index 000000000..937fe95b5 --- /dev/null +++ b/wiki/Log-levels/index.html @@ -0,0 +1,1307 @@ + + + + + + + + Log levels - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

See Configuration-file

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Log4JXMLEvent-Layout-Renderer/index.html b/wiki/Log4JXMLEvent-Layout-Renderer/index.html new file mode 100644 index 000000000..99346feb1 --- /dev/null +++ b/wiki/Log4JXMLEvent-Layout-Renderer/index.html @@ -0,0 +1,1387 @@ + + + + + + + + Log4JXMLEvent Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

XML event description compatible with log4j, Chainsaw and NLogViewer.

+
+

Platforms Supported: All (Since NLog v6 then it has been replaced by Log4JXmlEventLayout)

+
+

Notice that Log4JXml-target works as a combined solution for sending Log4j-XML events over TCP / UDP / HTTP.

+

Configuration Syntax

+
${log4jxmlevent:includeEventProperties=Boolean:includeSourceInfo=Boolean:includeCallSite=Boolean
+               :includeNdc=Boolean:ndcItemSeparator=String:appInfo=String:indentXml=Boolean}
+
+

Parameters

+

Payload Options

+
    +
  • +

    appInfo - AppInfo field. By default it's the friendly name of the current AppDomain.

    +
  • +
  • +

    loggerName - Logger field. By default it's the output of ${logger}

    +
    +

    Introduced in NLog 4.5

    +
    +
  • +
  • +

    formattedMessage - Message field. By default it's the output of ${message}

    +
    +

    Introduced in NLog 5.3

    +
    +
  • +
  • +

    includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean

    +
  • +
  • +

    includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean

    +
  • +
  • +

    IncludeEventProperties - Include all events properties of a logevent? Default: true.

    +
    +

    Before NLog 5.0 option was named IncludeAllProperties with Default: false

    +
    +
  • +
  • +

    IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeMdlc or IncludeMdc

    +
    +
  • +
  • +

    IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeNdlc

    +
    +
  • +
  • +

    ScopeNestedSeparator - NDC item separator. Default:

    +
    +

    Before NLog 5.0 option was named NdlcItemSeparator

    +
    +
  • +
  • +

    includeNdc - Indicates whether to include ScopeNested-Layout-Renderer. Default: false.

    +
  • +
  • +

    ndcItemSeparator - NDC item separator. Default:

    +
  • +
  • +

    WriteThrowableCData - Write Exception as CDATA in log4j:throwable xml-element (Not supported by all viewers). Default: false

    +
    +

    Introduced in NLog 5.0

    +
    +
  • +
  • +

    indentXml - Indicates whether to enable XmlWriterSettings.Indent for XML indentation. Default: false.

    +
  • +
  • +

    includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: false.

    +
    +

    Before NLog 5.0 option had Default: true.

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Log4JXml-Target/index.html b/wiki/Log4JXml-Target/index.html new file mode 100644 index 000000000..095b459a6 --- /dev/null +++ b/wiki/Log4JXml-Target/index.html @@ -0,0 +1,1544 @@ + + + + + + + + Log4JXml Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to the remote instance of Log4J XML Viewer applications (Like Chainsaw).

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network

+

Introduced with NLog 6.0 where Chainsaw-Target and NLogViewer-Target was merged together into this.

+
+

This target inherits from the Network Target, and so it has also all the properties of the Network Target available. Using the Log4JXmlEventLayout to produce Log4J XML output.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Log4JXml"
+          name="String"
+          address="Layout"
+          newLine="Boolean"
+          onOverflow="Enum"
+          maxMessageSize="Integer"
+          encoding="Encoding"
+          connectionCacheSize="Integer"
+          lineEnding="CRLF|LF|CR|None"
+          maxConnections="Integer"
+          maxQueueSize="Integer"
+          keepConnection="Boolean"
+          onConnectionOverflow="Enum"
+          includeSourceInfo="Boolean"
+          includeCallSite="Boolean"
+          appInfo="String"
+          ndcItemSeparator="String"
+          includeNdc="Boolean">
+    <parameter name="String" layout="Layout" /><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • +

    layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout

    +
  • +
  • +

    encoding - Encoding to be used. Encoding Default: utf-8

    +
  • +
  • +

    newLine - Indicates whether to append newline at the end of log message. Boolean Default: False

    +
  • +
  • +

    lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF. Not used if newLine is false. +Possible values:

    +
  • +
  • CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default)
  • +
  • CR - Carriage Return (ASCII 13).
  • +
  • LF - Line Feed (ASCII 10).
  • +
  • NULL - Null terminator (ASCII 0)
  • +
  • +

    None - No end of line characters.

    +
  • +
  • +

    maxMessageSize - Maximum message size in bytes. Integer Default: 65000

    +
  • +
  • +

    onOverflow - Action that should be taken if the message-size is larger than maxMessageSize. +Possible values:

    +
  • +
  • Discard - Discard the entire message.
  • +
  • Error - Report an error.
  • +
  • Split - Split the message into smaller pieces (Default)
  • +
+

Connection Options

+
    +
  • +

    connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5

    +
  • +
  • +

    address - Network address. Layout +The network address can be:

    +
  • +
  • tcp://host:port - TCP (auto select IPv4/IPv6)
  • +
  • tcp4://host:port - force TCP/IPv4
  • +
  • tcp6://host:port - force TCP/IPv6
  • +
  • udp://host:port - UDP (auto select IPv4/IPv6)
  • +
  • udp4://host:port - force UDP/IPv4
  • +
  • udp6://host:port - force UDP/IPv6
  • +
  • http://host:port/pageName - HTTP using POST verb
  • +
  • +

    https://host:port/pageName - HTTPS using POST verb +For SOAP-based webservice support over HTTP use WebService target.

    +
  • +
  • +

    keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True

    +
  • +
  • +

    maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16. Not used if keepConnection is true.

    +
  • +
  • +

    onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections. + Possible enum values:

    +
  • +
  • Discard - Discard new messages when reaching limit (Default)
  • +
  • Grow - Send message and ignore limit
  • +
  • +

    Block - Block until pending connections has beeen freed.

    +
  • +
  • +

    maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer. Default: 10000

    +
  • +
  • +

    onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize.

    +
  • +
  • Discard - Discard the entire message (Default)
  • +
  • Grow - Ignore limit and grow the queue.
  • +
  • +

    Block - Block until queue is below limit.

    +
  • +
  • +

    KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true.

    +
  • +
  • +

    sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. + Possible values (combination allowed, comma separated):

    +
  • +
  • None - No SSL/TLS is used
  • +
  • Default - Accepts Tls or Ssl3
  • +
  • Ssl2 - really not recommended
  • +
  • Ssl3 - not recommended
  • +
  • Tls - TLS 1.0
  • +
  • Tls11 - TLS 1.1
  • +
  • +

    Tls12 - TLS 1.2

    +
  • +
  • +

    SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation)

    +
  • +
  • +

    SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile

    +
  • +
  • +

    SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine)

    +
    +

    Introduced in NLog.Targets.Network v6.1.6

    +
    +
  • +
+

Payload Options

+
    +
  • +

    IncludeEventProperties - Include all events properties of a logevent? Default: true.

    +
  • +
  • +

    IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false.

    +
  • +
  • +

    includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean

    +
  • +
  • +

    includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean

    +
  • +
  • +

    IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false.

    +
  • +
  • +

    ScopeNestedSeparator - NDC item separator. Default:

    +
  • +
  • +

    includeNdc - Indicates whether to include ScopeNested-Layout-Renderer. Default: false.

    +
  • +
  • +

    ndcItemSeparator - NDC item separator. Default:

    +
  • +
  • +

    appInfo - AppInfo field. By default it's the friendly name of the current AppDomain.

    +
  • +
  • +

    loggerName - Logger field. By default it's the output of ${logger}

    +
  • +
  • +

    formattedMessage - Message field. By default it's the output of ${message}

    +
  • +
  • +

    parameter - Additional context properties that should be included.

    +
  • +
  • name - Name of Parameter. Required.
  • +
  • layout - The layout for the Parameter-Value. Required.
  • +
+

Example

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <extensions>
+    <add assembly="NLog.Targets.Network"/>
+  </extensions>
+
+  <targets>
+    <target name="log4j" xsi:type="Log4JXml" address="udp://127.0.0.1:5001" />
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="log4j" />
+  </rules>
+</nlog>
+
+

Available Log4J-XML viewers (See also LogViewer Tools) +- Sentinel - Avoid using TCP since not complete. +- Log2Console +- Logazmic +- Loginator +- Logbert +- LogViewer +- Lilith +- OtrosLogViewer

+

Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this:

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <extensions>
+    <add assembly="NLog.Targets.Network"/>
+  </extensions>
+
+  <targets>
+    <target name="throttle_log4j" type="AsyncWrapper" timeToSleepBetweenBatches="100" batchSize="1" overflowAction="Block">
+      <target name="log4j" type="Log4JXml" address="tcp://127.0.0.1:5001" newline="true" />
+    </target>
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="throttle_log4j" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Log4JXmlEventLayout/index.html b/wiki/Log4JXmlEventLayout/index.html new file mode 100644 index 000000000..73ec87064 --- /dev/null +++ b/wiki/Log4JXmlEventLayout/index.html @@ -0,0 +1,1401 @@ + + + + + + + + Log4JXmlEventLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders Log4j-compatible XML events.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6

+
+

Notice that Log4JXml-target works as a combined solution for sending Log4j-XML events over TCP / UDP / HTTP.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="SomeTarget">
+    <layout xsi:type="Log4JXmlEventLayout" includeEventProperties="true">
+       <parameter name="processId" value="${processid}" /> <!-- Repeated -->
+    </layout>
+  </target>
+</targets>
+
+

Parameters

+
    +
  • +

    appInfo - AppInfo field. By default it's the friendly name of the current AppDomain.

    +
    +

    Introduced in NLog 5.0

    +
    +
  • +
  • +

    loggerName - Logger field. By default it's the output of ${logger}

    +
    +

    Introduced in NLog 5.0

    +
    +
  • +
  • +

    formattedMessage - Message field. By default it's the output of ${message}

    +
    +

    Introduced in NLog 5.3

    +
    +
  • +
  • +

    IncludeEventProperties - Include all events properties of a logevent as log4j:data ? Default: true.

    +
    +

    Before NLog 5.0 option was named IncludeAllProperties with Default: false

    +
    +
  • +
  • +

    IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer as log4j:data. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeMdlc or IncludeMdc

    +
    +
  • +
  • +

    IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeNdlc

    +
    +
  • +
  • +

    ScopeNestedSeparator - NDC item separator. Default:

    +
    +

    Before NLog 5.0 option was named NdlcItemSeparator

    +
    +
  • +
  • +

    includeNdc - Indicates whether to include ScopeNested-Layout-Renderer. Default: false.

    +
  • +
  • ndcItemSeparator - NDC item separator. Default:
  • +
  • includeSourceInfo - Indicates whether to include source info (file name and line number). Default: false.
    +

    Introduced in NLog 4.6.5

    +
    +
  • +
  • +

    includeCallSite - Indicates whether to include call site (class and method name). Default: false.

    +
    +

    Introduced in NLog 4.6.5

    +
    +
  • +
  • +

    includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: false.

    +
    +

    Before NLog 5.0 option had Default: true.

    +
    +
  • +
  • +

    WriteThrowableCData - Write Exception as CDATA in log4j:throwable xml-element (Not supported by all viewers). Default: false.

    +
    +

    Introduced in NLog 5.0

    +
    +
  • +
  • +

    parameter - Additional context properties that should be included as log4j:data

    +
    +

    Introduced in NLog 4.6.4

    +
    +
  • +
  • name - Name of Parameter. Required.
  • +
  • layout - The layout for the Parameter-Value. Required.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/LogEvent-Context-Information/index.html b/wiki/LogEvent-Context-Information/index.html new file mode 100644 index 000000000..418f1b01a --- /dev/null +++ b/wiki/LogEvent-Context-Information/index.html @@ -0,0 +1,1307 @@ + + + + + + + + LogEvent Context Information - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Moved to https://github.com/NLog/NLog/wiki/Context

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/LogReceiverService-target/index.html b/wiki/LogReceiverService-target/index.html new file mode 100644 index 000000000..c27e2a075 --- /dev/null +++ b/wiki/LogReceiverService-target/index.html @@ -0,0 +1,1399 @@ + + + + + + + + LogReceiverService target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to a NLog Receiver Service (using WCF or Web Services).

+
+

Platforms Supported: All - Requires nuget-package NLog.Wcf since NLog 5.0

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="LogReceiverService"
+          name="String"
+          endpointConfigurationName="String"
+          endpointAddress="String"
+          useBinaryEncoding="Boolean"
+          clientId="Layout"
+          includeEventProperties="Boolean">
+    <parameter layout="Layout" name="String" type="System.Type"/><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Note it is recommended to also apply BufferingWrapper-target with a FlushTimeout of 200ms (or higher), as LogReceiverService-target will by default create/open new connection for each batch of LogEvents.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Connection Options

+
    +
  • +

    endpointAddress - Endpoint address. Required.

    +
  • +
  • +

    endpointConfigurationName - Name of the endpoint configuration in WCF configuration file

    +
    +

    Only supported on .NET Framework platform with app.config. Trying to enable on .NET Core fails with: +System.PlatformNotSupportedException: Configuration files are not supported.

    +
    +
  • +
+

Payload Options

+
    +
  • +

    useBinaryEncoding - Indicates whether to use binary message encoding. Boolean

    +
  • +
  • +

    parameters - The list of parameters. Collection
    +Each collection item is represented by \ element with the following attributes:

    +
  • +
  • layout - Layout that should be use to calculate the value for the parameter. Layout Required.
  • +
  • name - Name of the parameter.
  • +
  • +

    type - Type of the parameter.System.Type

    +
  • +
  • +

    clientId - Application Client Identifier, translates into NLogEvents.ClientName Layout

    +
  • +
  • +

    includeEventProperties - Indicates whether to include per-event properties in the payload sent to the server. Boolean

    +
  • +
+

Examples

+

Passing Parameters

+

Parameters are passed to the WCF LogReceiverService target using one or more configuration lines such as:

+
<parameter name="MyParameter" layout="My Value!" />
+<parameter name="nlogdir" layout="${nlogdir}" />
+
+

These parameters are passed over the network to the service and can be accessed by emitting events from your receiver application.

+

Application for receiving events

+
namespace MyLogReceiverApp
+{
+   using System;
+   using NLog;
+   using NLog.LogReceiverService;
+
+   /// <summary>
+   /// Log service server object that logs messages.
+   /// </summary>
+   public class LogReceiverServer : ILogReceiverServer
+   {
+       public void ProcessLogMessages(NLogEvents nevents)
+       {
+           var events = nevents.ToEventInfo("Client.");
+           Console.WriteLine("in: {0} {1}", nevents.Events.Length, events.Count);
+
+           foreach (var ev in events)
+           {
+               var logger = LogManager.GetLogger(ev.LoggerName);
+               logger.Log(ev);
+           }
+       }
+   }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Logger-Layout-Renderer/index.html b/wiki/Logger-Layout-Renderer/index.html new file mode 100644 index 000000000..bc9f811de --- /dev/null +++ b/wiki/Logger-Layout-Renderer/index.html @@ -0,0 +1,1325 @@ + + + + + + + + Logger Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Renders name of the Logger that produced the LogEvent. The Logger name is assigned when it is created using NLog.LogManager.GetLogger("myLoggerName") or NLog.LogManger.GetCurrentClassLogger() (capture class-type-name as Logger-name)

+

The Logger-name is often used to describe the source-location where the LogEvent was produced. The NLog Logging-Rules are optimized for doing filtering / redirection of LogEvents based on the Logger-name. It is not recommended to generate Logger-name from Guid or Timestamp, as it can lead to memory-leak with huge Logger-cache.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${logger:shortName=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • shortName - Indicates whether to render short logger name (the part after the last trailing dot character). Boolean Default: False
  • +
  • prefixName - Indicates whether to render prefix-part of logger name (the part before the last trailing dot character). Boolean Default: False
    +

    Introduced with NLog v5.3

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Logging-Rules-FinalMinLevel/index.html b/wiki/Logging-Rules-FinalMinLevel/index.html new file mode 100644 index 000000000..c3bdd762e --- /dev/null +++ b/wiki/Logging-Rules-FinalMinLevel/index.html @@ -0,0 +1,1479 @@ + + + + + + + + Logging Rules FinalMinLevel - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

finalMinLevel is an option for Logging Rules, +that have been introduced with NLog ver 5.0. It is conceptually similar to the combination of the maxLevel and final option.

+

The main reason for the finalMinLevel option is to easily silence +all noisy loggers from one subcomponent (like Microsoft.*), while +overriding this behavior for a single logger of that subcomponent +(like Microsoft.Hosting.Lifetime). This is similar to how the +filtering works in Microsoft Extension Logging.

+

finalMinLevel is intended for configurations that have +catch-all log-targets at the bottom of the logging rules.

+

Here's a small example to start with: if logs coming from +Microsoft.* should only be logged if the log level is Warn or +higher, and all other logs should be logged if the level is Info or +higher, then the following configuration could be used:

+
<rules>
+    <logger name="Microsoft.*" finalMinLevel="Warn" />
+    <logger name="*" minLevel="Info" writeTo="console" />
+</rules>
+
+

This can also be implemented using maxLevel and final in NLog v4:

+
<rules>
+    <logger name="Microsoft.*" maxLevel="Info" final="true" />
+    <logger name="*" minLevel="Info" writeTo="console" />
+</rules>
+
+

In both examples, the first rule is a "black hole" that swallows the +applicable logs. Also keep in mind that the order of the logger-rules +are always very important.

+

The advantage of finalMinLevel is that it is easier to read, +comprehend and reduces the configuration required, especially with +more complex configurations. Additionally, it allows overriding +previous finalMinLevel filters, such a pattern is not possible +otherwise.

+

Levels

+

The following table describes which log levels are enabled depending +on the finalMinLevel value:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FinalMinLevelOrdinalEnabled log levels
Trace0Trace, Debug, Info, Warn, Error and Fatal
Debug1Debug, Info, Warn, Error and Fatal
Info2Info, Warn, Error and Fatal
Warn3Warn, Error and Fatal
Error4Error and Fatal
Fatal5Fatal
Off6
+

NLog includes LogLevel Off, that can be used to suppress all output from a noisy logger:

+
<rules>
+    <logger name="NoisyLogger.*" finalMinLevel="Off" />
+    <logger name="*" minLevel="Info" writeTo="console" />
+</rules>
+
+

This can also be implemented using maxLevel and final in NLog v4:

+
<rules>
+    <logger name="NoisyLogger.*" maxLevel="Off" final="true" />
+    <logger name="*" minLevel="Info" writeTo="console" />
+</rules>
+
+

Overrides

+

As mentioned before, finalMinLevel can override previous rules. For +example, if we want Warn logs of higher from Microsoft.*, but +Info logs or higher from Microsoft.Hosting.Lifetime, then this is +a possible configuration:

+
<rules>
+    <logger name="Microsoft.*" finalMinLevel="Warn" />
+    <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" />
+    <logger name="*" minLevel="Info" writeTo="console" />
+</rules>
+
+

Keep in mind that the order is still important. If the "Microsoft.* +and Microsoft.Hosting.Lifetime* were reversed, then Microsoft.* +would override Microsoft.Hosting.Lifetime* and both would be set to +Warn.

+

Microsoft Extensions Logging Filters

+

The Microsoft Logging filters specified in appsettings.json are ignored by default when using NLog 5.0. +This is to avoid that new users think NLog Logging Rules are not working, because Microsoft LoggerFactory filters are interfering.

+

The default logging logging configuration in appsettings.json:

+
{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft": "Warning",
+      "Microsoft.Hosting.Lifetime": "Information"
+    }
+  }
+}
+
+

Can be configured through NLog.config like this:

+
<rules>
+    <logger name="Microsoft.*" finalMinLevel="Warn" />
+    <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" />
+    <logger name="*" minLevel="Info" writeTo="console" />
+</rules>
+
+

Notice that the logger named Microsoft.Hosting.Lifetime* overrides the Microsoft.* logger. See also Microsoft Hosting Lifetime Startup Messages

+

See also Tutorial for using NLog with ASP.NET Core

+

Complete example

+

This example also filters logs from System.* and separates +informative logs and error logs between the stdout and stderr +output streams.

+

It is a good configuration for new ASP.NET projects.

+
<?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="stdout" xsi:type="Console" />
+    <target name="stderr" xsi:type="Console" stdErr="true" />
+  </targets>
+
+  <rules>
+    <logger name="System.*" finalMinLevel="Warn" />
+    <logger name="Microsoft.*" finalMinLevel="Warn" />
+    <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" />
+    <logger name="*" minLevel="Info" maxLevel="Warn" writeTo="stdout" />
+    <logger name="*" minLevel="Error" writeTo="stderr" />
+  </rules>
+</nlog>
+
+

FinalMinLevel in combination with minLevel

+

It can be useful to combine finalMinLevel with MinLevel. Suppose +there's a sub-module RequestLogger that should have its own +dedicated log-target, but at the same time all Error or higher logs +should flow to the catch-all log-target. This can be achieved through:

+
<logger name="RequestLogger" minLevel="Debug" writeTo="requestTarget" finalMinLevel="Error" />
+<logger name="*" minLevel="Info" writeTo="catchAllTarget" />
+
+

It can also be configured like this if using NLog v4:

+
<logger name="RequestLogger" minLevel="Debug" writeTo="requestTarget" />
+<logger name="RequestLogger" maxLevel="Warn" final="true" />
+<logger name="*" minLevel="Info" writeTo="catchAllTarget" />
+
+

All logs coming from RequestLogger with a level between Debug and +higher will be logged to requestTarget. All other logs with a level +Info or higher will be logged to catchAllTarget, including Error +and Fatal logs from RequestLogger.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Logging-Troubleshooting/index.html b/wiki/Logging-Troubleshooting/index.html new file mode 100644 index 000000000..e7bc70852 --- /dev/null +++ b/wiki/Logging-Troubleshooting/index.html @@ -0,0 +1,1454 @@ + + + + + + + + Logging Troubleshooting - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Possible causes

+

When no log output is produced, the issue may originate in NLog configuration, the application, or the runtime environment. Common causes include:

+
    +
  • NLog cannot find the configuration file. Ensure NLog.config has:
  • +
  • Build Action = Content
  • +
  • Copy to Output Directory = Copy if newer
  • +
  • The configuration file contains invalid XML or NLog configuration errors.
  • +
  • Logging rules do not match the logger name or log level.
  • +
  • The logging code is never executed.
  • +
  • The application exits before logs are flushed. Call NLog.LogManager.Shutdown() during application shutdown to flush pending events.
  • +
  • The logging target fails at runtime (e.g., missing file permissions).
  • +
  • Log output is written to an unexpected location.
  • +
  • A different configuration is used at deployment time (overriding the expected NLog.config).
  • +
  • Environment differences (hosting, container, or filesystem) compared to local development.
  • +
+

Troubleshooting steps

+

These steps help isolate the problem area: +configuration loading → initialization → rule matching → target writing → application execution

+
+

1. Verify configuration file loading

+

Ensure NLog.config xml-file is located in the application’s base directory, as the primary location of the multiple file location scanned by NLog at startup.

+
    +
  • Ensure NLog.config has:
  • +
  • Build Action = Content
  • +
  • Copy to Output Directory = Copy if newer
  • +
  • On Linux, file name must be nlog.config (all lowercase as case-sensitive)
  • +
  • Some NuGet packages may modify Web.config or App.config and override logging configuration
  • +
  • Do NOT use the deprecated NLog.Config NuGet-package, which may overwrite or reset configuration during deployment.
  • +
  • Verify that the deployed configuration matches the expected version.
  • +
+
+

2. Enable configuration exception reporting

+

NLog will by default suppress any configuration errors, instead of causing the application to fail. But this also means that application will not produce any logging output.

+

Enabling throwConfigExceptions will make NLog throw exceptions to report any issues detected in the NLog Configuration at startup:

+
<nlog throwConfigExceptions="true">
+    <targets>
+        ...
+    </targets>
+    <rules>
+        ...
+    </rules>
+</nlog>
+
+
+

3. Enable InternalLogger

+

Enable the NLog InternalLogger and use the output to help diagnose: +- Configuration loading issues +- Logger rules decisions +- Target initialization failures +- Target writing failures (File permission problems, File path issues, Ex.) +- Etc.

+
<nlog internalLogLevel="Debug"
+      internalLogFile="c:\temp\nlog-internal.txt"
+      internalLogToConsole="true"
+      throwConfigExceptions="true">
+    <targets>
+        ...
+    </targets>
+    <rules>
+        ...
+    </rules>
+</nlog>
+
+
+

4. Enable InternalLogger early in startup

+

If no InternalLogger output appears, then it either NLog.config could not be found or failed to load. It can also be that the InternalLogger was enabled after initial attempt to load the NLog logging configuration.

+

Try to enable NLog InternalLogger from code at application startup. Ensure it happens before any logger usage (like static Logger objects), as configuration is initially loaded when first Logger is created.

+
class Program
+{
+    // Temporarily disable static logger initialization
+    // readonly static Logger = LogManager.GetCurrentClassLogger();
+
+    static void Main()
+    {
+        NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Debug;
+        NLog.Common.InternalLogger.LogToConsole = true;
+        NLog.Common.InternalLogger.LogFile = @"c:\temp\nlog-internal.txt";
+
+        var logger = LogManager.GetLogger("foo");
+        logger.Info("Program started");
+
+        LogManager.Shutdown();
+    }
+}
+
+
+

5. Simplify logging rules

+

Reduce logging rule complexity to eliminate matching issues, by adding catch-all rule that matches all loggers and all levels at the beginning of your <rules> section:

+
<nlog throwConfigExceptions="true">
+  <targets>
+    <target name="file" type="File" fileName="C:/Logs/log.txt" />
+    <target name="console" type="Console" />
+  </targets>
+
+  <rules>
+    <logger name="*" minLevel="Trace" writeTo="file,console" />
+  </rules>
+</nlog>
+
+

If still no logs appear:

+
    +
  • Verify that the logging call is actually executed in the application code.
  • +
  • Ensure explicit flush is made before application shutdown, in case NLog target is having delays in network communication. Ex. by calling NLog.LogManager.Shutdown().
  • +
  • If using file-target then make sure to use absolute file-path as more predictable.
  • +
+
+

6. Enable runtime exception reporting (last resort)

+

Enable runtime exception propagation only for diagnostics:

+
NLog.LogManager.ThrowExceptions = true;
+
+

⚠️ Use only ThrowExceptions = true for troubleshooting and unit-testing. Should never be kept enabled in production, as it can cause application runtime crashes. Different from throwConfigExceptions="true" that only enables configuration verification at startup.

+
class Program
+{
+    static void Main()
+    {
+        NLog.LogManager.ThrowExceptions = true; // TODO Remove after troubleshooting
+
+        NLog.Common.InternalLogger.LogLevel = LogLevel.Debug;
+        NLog.Common.InternalLogger.LogToConsole = true;
+        NLog.Common.InternalLogger.LogFile = @"c:\temp\nlog-internal.txt";
+
+        var logger = LogManager.GetLogger("foo");
+        logger.Info("Program started");
+
+        LogManager.Shutdown();
+    }
+}
+
+

Other tools and techniques

+

External tools can help determine whether the issue is inside NLog or the environment:

+ +

These help distinguish between "NLog not writing" vs "Operating System prevented writing".

+
+

Key questions to guide troubleshooting

+

Focus on observable behavior:

+
    +
  • Is the configuration loaded?
  • +
  • Is the logger initialized?
  • +
  • Is the logging call executed?
  • +
  • Is the log event routed?
  • +
  • Is the target writing successfully?
  • +
+

Answering these typically identifies the failing component quickly.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Longdate-Layout-Renderer/index.html b/wiki/Longdate-Layout-Renderer/index.html new file mode 100644 index 000000000..bd45c4a67 --- /dev/null +++ b/wiki/Longdate-Layout-Renderer/index.html @@ -0,0 +1,1323 @@ + + + + + + + + Longdate Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The date and time in a long, sortable format yyyy-MM-dd HH:mm:ss.ffff.

+
+

Platforms Supported: All

+

Alternative ${date:format=yyyy-MM-dd_HH} can be used to customize the DateTime-format.

+
+

Configuration Syntax

+
${longdate:universalTime=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • universalTime - Indicates whether to output UTC time instead of local time.Boolean Default: False
  • +
+

Time Source Precision

+

NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount. For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Lowercase-Layout-Renderer/index.html b/wiki/Lowercase-Layout-Renderer/index.html new file mode 100644 index 000000000..c6c02f419 --- /dev/null +++ b/wiki/Lowercase-Layout-Renderer/index.html @@ -0,0 +1,1330 @@ + + + + + + + + Lowercase Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Converts the result of another layout output to lower case.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${lowercase:lowercase=Boolean:inner=Layout:culture=Culture}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:lowercase=Boolean}
+
+

Parameters

+

Transformation Options

+
    +
  • lowercase - Indicates whether lower case conversion should be applied. Boolean Default: True. Required when using as ambient.
  • +
  • inner - Wrapped layout. Layout
  • +
  • culture - Culture used for rendering. Culture
  • +
+

Examples

+
${lowercase:${level}}
+${lowercase:Inner=${level}}
+${level:lowercase=true}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MDC-Layout-Renderer/index.html b/wiki/MDC-Layout-Renderer/index.html new file mode 100644 index 000000000..6c047d973 --- /dev/null +++ b/wiki/MDC-Layout-Renderer/index.html @@ -0,0 +1,1367 @@ + + + + + + + + MDC Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +
+

⚠️ NLog 5.0 introduces ScopeContext that replaces MDLC + MDC

+
+

Mapped Diagnostics Context (MDC) - a thread-local structure that keeps a dictionary of strings and provides methods to output them in layouts.

+
+

Platforms Supported: All (NLog 4.1 supports any Object type, not just String)

+
+

MDC is considered legacy, and instead is recommended to use MDLC that includes support for async Tasks. See also NLog Context

+

Configuration Syntax

+
${mdc:item=String}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Name of the item. Required. Note: case sensitive!
  • +
+

Example

+

Simple Properties

+

The following example demonstrates the basic usage of the Mapped Diagnostics Context.

+
MappedDiagnosticsContext.Set("PropertyName", "PropertyValue");
+MappedDiagnosticsContext.Set("Property2", new { Part1 = 2.0m, Part2 = "Two parts" });
+MappedDiagnosticsContext.Set("Property3", AnyObjectOrString);
+
+

Add the following to your logger configuration to reference the above properties.

+
${mdc:item=PropertyName}
+${mdc:item=Property2}
+${mdc:item=Property3}
+
+

Dynamic Properties

+

The following example demonstrates a Mapped Diagnostics Context property that renders the value of Environment.TickCount at the time that the context item is rendered.

+
public class MdcTickProperty 
+{
+   public static readonly MdcTickProperty Default = new MdcTickProperty();
+
+   private MdcTickProperty () 
+   {
+   }
+
+   public override string ToString () 
+   {
+      return Environment.TickCount.ToString();
+   }
+}
+
+

Add the MdcTickProperty instance to the Mapped Diagnostics Context. This will only affect the current thread, as the Mapped Diagnostics Context is thread-local.

+
MappedDiagnosticsContext.Set("TickCount", MdcTickProperty.Default);
+
+

In the logging configuration, include:

+
${mdc:item=TickCount}
+
+

Scoped item

+

The SetScoped method returns an IDisposable that removes the added item when disposed. It can be used in conjunction with the using statement to limit the scope during which the item will be present in the context.

+
using (MappedDiagnosticsContext.SetScoped("Property", "PropertyValue")) {
+    // "Property" item is present in current context
+}
+// "Property" item has been removed from current context
+
+

Notes

+

When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MDLC-Layout-Renderer/index.html b/wiki/MDLC-Layout-Renderer/index.html new file mode 100644 index 000000000..c8e3518ce --- /dev/null +++ b/wiki/MDLC-Layout-Renderer/index.html @@ -0,0 +1,1352 @@ + + + + + + + + MDLC Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +
+

⚠️ NLog 5.0 introduces ScopeContext that replaces MDLC + MDC

+
+

Mapped Diagnostic Logical Context (MDLC) acts like a dictionary of named properties with values, that are stored in an Async-Local structure (Similar to "Thread Context Map" in Log4j). It is the async version of MDC Layout Renderer.

+
+

Platforms Supported: All

+

Introduced with NLog 4.1 (NLog 4.1.1 add support for any Object type, not just String)

+
+

It enables one to assign one or more named properties to the active scope (Ex. a request CorrelationId). Then all logger-events created within the scoped logical context, can automatically capture the scope-properties without needing to specify it with each LogEvent. The specified scope properties will automatically flow together with async Tasks.

+

See also NLog Context.

+

Configuration Syntax

+
${mdlc:item=String}
+
+

Parameters

+

Rendering Options

+
    +
  • item - Name of the item. Required. Note: case sensitive!
  • +
+

Example

+

Simple Properties

+

The following example demonstrates the basic usage of the Mapped Diagnostic Logical Context.

+
MappedDiagnosticsLogicalContext.Set("PropertyName", "PropertyValue");
+MappedDiagnosticsLogicalContext.Set("PropertyName2", "AnotherPropertyValue");
+
+

Add the following to your logger configuration to reference the above properties.

+
${mdlc:item=PropertyName}
+${mdlc:item=PropertyName2}
+
+

Scoped item

+

The SetScoped method returns an IDisposable that removes the added item when disposed. It can be used in conjunction with the using statement to limit the scope during which the item will be present in the context.

+
using (MappedDiagnosticsLogicalContext.SetScoped("Property", "PropertyValue")) {
+    // "Property" item is present in current context
+}
+// "Property" item has been removed from current context
+
+

.NET Core logging

+

When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options:

+
//note: render userId via ${mdlc:userid}
+using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("userid", request.UserId) }))
+{
+   _logger.LogDebug("Start process {ProccessName}, "Main");
+}
+
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MSMQ-target/index.html b/wiki/MSMQ-target/index.html new file mode 100644 index 000000000..6927bb7d9 --- /dev/null +++ b/wiki/MSMQ-target/index.html @@ -0,0 +1,1380 @@ + + + + + + + + MSMQ target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to the Microsoft Message Queue (MSMQ).

+
+

Platforms Supported: Limited - Windows only as it depends on mqrt.dll, and requires nuget-package NLog.MSMQ

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="MSMQ"
+          name="String"
+          useXmlEncoding="Boolean"
+          encoding="Encoding"
+          layout="Layout"
+          recoverable="Boolean"
+          singleTransaction="Boolean"
+          createQueueIfNotExists="Boolean"
+          checkIfQueueExists="Boolean"
+          label="Layout"
+          queue="Layout" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+
    +
  • +

    name - Name of the target.

    +
  • +
  • +

    useXmlEncoding - Indicates whether to use the XML format when serializing message. Boolean Default: False

    +
  • +
  • +

    encoding - Encoding to be used when writing text to the queue. Encoding

    +
  • +
  • +

    layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withException=true}

    +
  • +
+

Queue Options: +* queue - Name of the queue to write to. Layout Required.
+To write to a private queue on a local machine use .\private$\QueueName. For other available queue names, consult MSMQ documentation.

+
    +
  • +

    label - Label to associate with each message. Layout Default: ""

    +
    +

    Changed default value from "NLog" to "" with NLog.MSMQ ver. 5.3

    +
    +
  • +
  • +

    recoverable - Indicates whether to use recoverable messages (with guaranteed delivery). Boolean Default: False

    +
  • +
  • +

    singleTransaction - Indicates whether to send single-transaction-style to transactional queue. Boolean Default: False

    +
    +

    Introduced with NLog.MSMQ ver. 5.3

    +
    +
  • +
  • +

    checkIfQueueExists - If true then it will check if queue exists for every message sent, which can be useful if troubleshooting. The queue exist check might cause Exception to be thrown when private-remote-queue, and prevent message send. Boolean Default: False

    +
    +

    Changed default value from true to false with NLog.MSMQ ver. 5.3

    +
    +
  • +
  • +

    createQueueIfNotExists - Indicates whether to create the queue if it doesn't exists. Notice this means it will check if queue exists for every message sent. Boolean Default: False

    +
  • +
+

Notes

+

The MSMQ target requires that: +* Installing Nuget-package NLog.MSMQ (Before NLog 5.0 it was NLog.Extended) +* The machine doing the logging have MSMQ installed with the Active Directory Domain Services Integration option. If the option is not installed, the target will throw an exception. +* The queue being written to is NOT transactional.

+
+

Introduced SingleTransaction with NLog.MSMQ ver. 5.3, that should support transactional queues.

+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Machinename-Layout-Renderer/index.html b/wiki/Machinename-Layout-Renderer/index.html new file mode 100644 index 000000000..1576e6302 --- /dev/null +++ b/wiki/Machinename-Layout-Renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + Machinename Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The NetBIOS Machine name that the process is running on.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${machinename}
+
+

Remarks

+

NetBIOS name is limited to MAX_COMPUTERNAME_LENGTH which is 15 for Windows.

+

${hostname} has support for the full DNS-name.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Mail-target/index.html b/wiki/Mail-target/index.html new file mode 100644 index 000000000..2543c5a94 --- /dev/null +++ b/wiki/Mail-target/index.html @@ -0,0 +1,1579 @@ + + + + + + + + Mail target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages by email using SMTP protocol.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Mail since NLog v6, or alternative MailKit

+
+ +

Configuration Syntax

+
<targets>
+  <target xsi:type="Mail"
+          name="String"
+          header="Layout"
+          footer="Layout"
+          layout="Layout"
+          html="Boolean"
+          addNewLines="Boolean"
+          replaceNewlineWithBrTagInHtml="Boolean"
+          encoding="Encoding"
+          subject="Layout"
+          to="Layout"
+          bcc="Layout"
+          cc="Layout"
+          from="Layout"
+          body="Layout"
+          smtpUserName="Layout"
+          enableSsl="Boolean"
+          secureSocketOption="None|Auto|SslOnConnect|StartTls|StartTlsWhenAvailable"*
+          smtpPassword="Layout"
+          smtpAuthentication="Enum"
+          smtpServer="Layout"
+          smtpPort="Integer"
+          useSystemNetMailSettings="Boolean"
+          deliveryMethod="Enum"
+          pickupDirectoryLocation="String"
+          timeout="Integer"
+          skipCertificateValidation="Boolean"
+          priority="Layout">
+     <mailheader name="header-name" layout="header-value" /> <!-- repeatable -->
+ </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • +

    header - Header for the message-body. Layout

    +
  • +
  • +

    footer - Footer for the message-body. Layout

    +
  • +
  • +

    layout - Text to be rendered for message-body. Layout Required. Default: ${message}${newline}.

    +
  • +
  • +

    html - Indicates whether to send message as HTML instead of plain text. Boolean Default: false

    +
  • +
  • +

    addNewLines - Indicates whether to add new lines between log entries. Boolean

    +
  • +
  • +

    replaceNewlineWithBrTagInHtml - Indicates whether NewLine characters in the body should be replaced with <br/> tags. Boolean Default: false

    +
  • +
  • +

    encoding - Encoding to be used for sending e-mail. Encoding Default: UTF-8

    +
  • +
+

Message Options

+
    +
  • +

    subject - Mail subject. Layout Required. Default: Message from NLog on ${machinename}

    +
  • +
  • +

    to - Recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout.

    +
  • +
  • +

    bcc - BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout

    +
  • +
  • +

    cc - CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout

    +
  • +
  • +

    from - Sender's email address (e.g. joe@domain.com). Layout Required.

    +
  • +
  • +

    body - Same as Layout property. Mail message body (repeated for each log message send in one mail). Layout Default: ${message}${newline}

    +
  • +
  • +

    priority - The mail message priority. Low / Normal / High

    +
  • +
  • NLog.MailKit v3.2 (and newer) accepts NonUrgent / Low , Normal , Urgent / High (Supports MimeKit.MessagePriority)
  • +
+

SMTP Options

+
    +
  • +

    smtpServer - SMTP Server to be used for sending. Layout Required.

    +
  • +
  • +

    smtpPort - Port number that SMTP Server is listening on. Integer Default: 25. Note: port 465 isn't working with SSL. See issue 1226

    +
  • +
  • +

    smtpAuthentication - SMTP Authentication mode. Default: None
    +Possible values:

    +
  • +
  • Basic - Basic - username and password.
  • +
  • None - No authentication.
  • +
  • Ntlm - NTLM Authentication using network credentials of user currently logged on (Same as SmtpClient.UseDefaultCredentials = true)
  • +
  • +

    OAuth2 - NLog.Mailkit ver. 6.1.3 (and newer) supports OAuth2 authentication where SmtpUserName provides clientid, and SmtpPassword provides clientSecret/accessToken.

    +
  • +
  • +

    smtpUserName - Username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). Layout

    +
  • +
  • +

    smtpPassword - Password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). Layout

    +
  • +
  • +

    enableSsl - Indicates whether SSL (secure sockets layer) should be used when communicating with SMTP server. Boolean Default: False.

    +
    +

    Notice SMTP/SSL, SMTP over SSL, or SMTPS with port 465 is only supported by NLog.MailKit. See issue 1226

    +
    +
  • +
  • +

    secureSocketOption - NLog.Mailkit ver. 2.1 (and newer) supports both SSL / TLS encryption. Default: StartTlsWhenAvailable. +Possible values:

    +
  • +
  • None - No SSL or TLS encryption should be used.
  • +
  • Auto - Allow the MailKit.IMailService to decide which SSL or TLS options to use. If the server does not support SSL or TLS, then no encryption.
  • +
  • SslOnConnect - The connection should use SSL or TLS encryption immediately.
  • +
  • StartTls - The connection should use TLS encryption immediately.
  • +
  • +

    StartTlsWhenAvailable - Elevates the connection to use TLS encryption immediately, when supported by server.

    +
  • +
  • +

    useSystemNetMailSettings - Force using smtp configuration from system.net/mailSettings. Boolean Default: False

    +
  • +
  • +

    timeout - Indicates the SMTP client timeout in milliseconds. Integer Default: 10000 (10 seconds)

    +
  • +
  • +

    pickupDirectoryLocation - Gets or sets the folder where applications save mail messages to be processed by the local SMTP server (introduced in NLog 4.2).

    +
  • +
  • +

    deliveryMethod - Specifies how outgoing email messages will be handled (introduced in NLog 4.2). Default: Network +Possible values:

    +
  • +
  • Network - Email is sent through the network to an SMTP server.
  • +
  • PickupDirectoryFromIis - Email is copied to the pickup directory used by a local Internet Information Services (IIS) for delivery.
  • +
  • +

    SpecifiedPickupDirectory - Email is copied to the directory specified by the PickupDirectoryLocation property for delivery by an external application.

    +
  • +
  • +

    skipCertificateValidation - NLog.Mailkit ver. 1.1 (and newer) can skip SSL certificate validation check. Maybe useful for self-signed certificates, but not recommended for production.

    +
  • +
  • +

    mailheader - Specify one or more email-message-headers (Ex. Message-Id)

    +
    +

    Introduced with NLog v5.1.3 and NLog.MailKit v5.1

    +
    +
  • +
+

Remarks

+

.NET Standard 1.x / MailKit package

+

The SmtpClient is not part of .NET Standard 1.x. Also notice that the original SmtpClient of .NET is obsolete in favor of MailKit:

+

image

+

The NLog.MailKit is the Mail target implementation which uses MailKit. Including the NLog.MailKit package will replace the original mail target and has the same options as the original mail target

+
    +
  • Install-Package NLog.MailKit
  • +
+

or use

+
<PackageReference Include="NLog.MailKit" Version="3.0.0" />
+
+

And add to your nlog.config:

+
<nlog>
+  <extensions>
+    <add assembly="NLog.MailKit"/>
+  </extensions>
+  ...
+
+

Bug/feature requests for NLog.MailKit please on the NLog.MailKit repo

+

Application Configuration File

+

If the application config file contains mail settings, fx.:

+
<system.net>
+  <mailSettings>
+    <smtp from="mail@domain.com" deliveryMethod="SpecifiedPickupDirectory">
+      <network host="localhost" port="25"/>
+      <specifiedPickupDirectory pickupDirectoryLocation="C:/Temp/Email"/>
+    </smtp>
+  </mailSettings>
+</system.net>
+
+

These values will be used, if target doesn't override them (see useSystemNetMailSettings attribute). +* NetStandard2.X does not support mail settings in the application config file.

+

Email Address Format

+

It is possible to use an address in format "John Doe <john.doe@example.com>" but the special characters < and > must be escaped. The result would be John Doe &lt;john.doe@example.com&gt;

+

MailKit Target using Amazon AWS SMTP:

+
<target name="MailAWS" xsi:type="Mail"
+            smtpServer="email-smtp.us-east-1.amazonaws.com"
+            smtpPort="587"
+            smtpAuthentication="Basic"
+            smtpUserName="xxxxxxxx"
+            smtpPassword="xxxxxxxxxx"
+            secureSocketOption="StartTls"
+            from="logger@xxxx.xxx" to="xxx@gmail.com" />
+
+

Mail Target wrapped by FallbackGroup Target

+

Example configuration for a Mailserver Fallback with multiple hosts.

+
<target xsi:type="FallbackGroup" 
+        name="mail"
+        returnToFirstOnSuccess="true">
+    <target xsi:type="Mail"
+            name="mailserver1"
+            subject="Layout"
+            to="Layout"
+            from="Layout"
+            smtpServer="mx1.example.com" 
+            smtpPort="Integer"
+            layout="Layout" />
+    <target xsi:type="Mail"
+            name="mailserver2" 
+            subject="Layout"
+            to="Layout"
+            from="Layout"
+            smtpServer="mx2.example.com" 
+            smtpPort="Integer"
+            layout="Layout" />
+</target>
+
+

Mail Target send LogEvent history on error

+

Example configuration that buffers LogEvents and sends entire batch on error LogEvent:

+
  <target xsi:type="AutoFlushWrapper" name="MailErrorFlush"
+    condition="level >= LogLevel.Error"
+    flushOnConditionOnly="true">
+     <target xsi:type="BufferingWrapper" name="MailBuffer"
+       bufferSize="50"
+       overflowAction="Discard">
+        <target xsi:type="Mail" name="MailTarget" />
+     </target>
+  </target>
+
+

Using Mail-Target with GMail

+

smtpAuthentication="Basic" enables use of NetworkCredentials for login, which can be used for sending OAuth ClientId (smtpUserName) and OAuth ClientSecret/AccessToken (smtpPassword). Consider to set From-address same as the username to reduce chance to be seen as spam.

+
<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="gmail" xsi:type="Mail"
+            smtpServer="smtp.gmail.com"
+            smtpPort="587"
+            enableSsl="true"
+            smtpAuthentication="Basic"
+            smtpUserName="user@gmail.com"
+            smtpPassword="password"
+            from="user@gmail.com"
+            to="recipient@example.com"
+            cc="alice@example.com;bob@example.com;charlie@example.com"
+          />
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Debug" writeTo="gmail" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Memory-target/index.html b/wiki/Memory-target/index.html new file mode 100644 index 000000000..3ad454cd3 --- /dev/null +++ b/wiki/Memory-target/index.html @@ -0,0 +1,1357 @@ + + + + + + + + Memory target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log messages to an ArrayList in memory for programmatic retrieval.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="Memory" name="String" layout="Layout" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • +

    layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}

    +
  • +
  • +

    MaxLogsCount Max count, will remove first if over this threshold. Default: 0 (No limit).

    +
    +

    Introduced with NLog v4.6

    +
    +
  • +
+

Examples

+

Setup MemoryTarget and enumerate messages

+
var config = new NLog.Config.LoggingConfiguration();
+var memoryTarget = new NLog.Targets.MemoryTarget();
+memoryTarget.Layout = "${message}";   // Message format
+config.AddRuleForAllLevels(memoryTarget);
+LogManager.Configuration = config;
+
+Logger logger = LogManager.GetLogger("Example");
+logger.Debug("log message");
+
+foreach (string logMsg in memoryTarget.Logs)
+{
+    Console.Write("logged: {0}", logMsg);
+}
+
+

See also Memory Target Tests

+

See also Memory Simple Example.cs

+

Reading from existing target

+
var target = LogManager.Configuration.FindTargetByName<MemoryTarget>("target1");
+var logEvents = target.Logs;
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Message-Layout-Renderer/index.html b/wiki/Message-Layout-Renderer/index.html new file mode 100644 index 000000000..c115e1c3a --- /dev/null +++ b/wiki/Message-Layout-Renderer/index.html @@ -0,0 +1,1330 @@ + + + + + + + + Message Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The formatted log message.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${message:exceptionSeparator=String:withException=Boolean:raw=Boolean}
+
+

Parameters

+

Layout Options

+
    +
  • exceptionSeparator - String that separates message from the exception.
  • +
  • withException - Indicates whether to log exception along with message. Boolean
  • +
  • raw - Render the unformatted input message without using input parameters (Message-Template for structured logging). Boolean
    +

    Introduced with NLog 4.5

    +
    +
  • +
+

Text tranformations

+

NLog provides several text transformations, that can be useful. Ex: +- Truncate - ${message:truncate=1000} +- Replace Newlines - ${replace-newlines:${message}} +- Replace with RegEx support - ${replace:${message}:searchFor=abc:replaceWith=xyz}

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MessageBox-target/index.html b/wiki/MessageBox-target/index.html new file mode 100644 index 000000000..0c89f0b70 --- /dev/null +++ b/wiki/MessageBox-target/index.html @@ -0,0 +1,1307 @@ + + + + + + + + MessageBox target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+ + +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MethodCall-target/index.html b/wiki/MethodCall-target/index.html new file mode 100644 index 000000000..356809306 --- /dev/null +++ b/wiki/MethodCall-target/index.html @@ -0,0 +1,1440 @@ + + + + + + + + MethodCall target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Calls the specified static method on each log message and passes contextual parameters to it.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="MethodCall"
+          name="String"
+          methodName="String"
+          className="String">
+    <parameter layout="Layout" name="String" type="System.Type"/><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Invocation Options

+
    +
  • methodName - Method name. The method must be public and static.
  • +
  • className - Class name. Do include the assembly name, e.g. "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests"
  • +
+

Parameter Options

+
    +
  • parameters - The array of parameters to be passed. Collection
    +Each collection item is represented by <parameter /> element with the following attributes:
  • +
  • layout - Layout that should be use to calculate the value for the parameter. Layout Required.
  • +
  • name - Name of the parameter.
  • +
  • type - Type of the parameter. System.Type
  • +
+

Note: Since NLog 4.3 these parameters can be optional.

+

Examples

+

Configure call of lambda at runtime

+
+

Introduced with NLog ver. 4.5.8

+
+

One can make it call a user defined delegate using Configuration API:

+
public class Example
+{
+    static void Main(string[] args)
+    {
+        MethodCallTarget target = new MethodCallTarget("MyTarget", (logEvent, args) => Console.WriteLine(logEvent.FormattedMessage));
+        NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
+        config.AddRuleForAllLevels(target)
+        NLog.LogManager.Configuration = config;
+
+        Logger logger = LogManager.GetLogger("Example");
+        logger.Info("log message");
+    }
+}
+
+

Or using the Fluent-Configuration-API introduced with NLog v5:

+
public class Example
+{
+    static void Main(string[] args)
+    {
+        var logger = LogManager.Setup().LoadConfiguration(c =>
+        {
+           c.ForLogger().WriteToMethodCall((logEvent, args) => Console.WriteLine(logEvent.FormattedMessage));
+        }).GetCurrentClassLogger();
+        logger.Info("log message");
+    }
+}
+
+

Configure call of static method with NLog.config

+

In order to send all logs to a static method, use the following configuration file:

+
<?xml version="1.0" ?>
+<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="m" xsi:type="MethodCall" className="SomeNamespace.MyClass, MyAssembly" methodName="LogMethod">
+            <parameter layout="${level}" />
+            <parameter layout="${message}" />
+        </target>
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="m" />
+    </rules>
+</nlog>
+
+

Per the configuration, the log method needs to be called "LogMethod" be declared in "SomeNamespace.MyClass" class. The class must be compiled to MyAssembly.dll. Each parameter of the log method must correspond to \ entry in the target configuration.

+
namespace SomeNamespace
+{
+    using System;
+
+    public class MyClass
+    {
+        public static void LogMethod(string level, string message)
+        {
+            Console.WriteLine("l: {0} m: {1}", level, message);
+        }
+    }
+}
+
+

Names of parameters are not important, only their order is. The default type of each parameter is string, but it can be overridden by adding type attribute to <parameter /> element.

+

Configure call of static method at runtime

+

It is also possible to configure logging using Configuration API:

+
using System;
+
+using NLog;
+using NLog.Targets;
+using System.Diagnostics;
+
+public class Example
+{
+    public static void LogMethod(string level, string message)
+    {
+        Console.WriteLine("l: {0} m: {1}", level, message);
+    }
+
+    static void Main(string[] args)
+    {
+        MethodCallTarget target = new MethodCallTarget() { Name = "MyTarget" };
+        target.ClassName = typeof(Example).AssemblyQualifiedName;
+        target.MethodName = "LogMethod";
+        target.Parameters.Add(new MethodCallParameter("${level}"));
+        target.Parameters.Add(new MethodCallParameter("${message}"));
+
+        NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
+        config.AddRuleForAllLevels(target)
+        NLog.LogManager.Configuration = config;
+
+        Logger logger = LogManager.GetLogger("Example");
+        logger.Debug("log message");
+        logger.Error("error message");
+    }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MicrosoftConsoleJsonLayout/index.html b/wiki/MicrosoftConsoleJsonLayout/index.html new file mode 100644 index 000000000..afd821674 --- /dev/null +++ b/wiki/MicrosoftConsoleJsonLayout/index.html @@ -0,0 +1,1353 @@ + + + + + + + + MicrosoftConsoleJsonLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A custom NLog JsonLayout that renders to JSON to simulate Microsoft Logging AddJsonConsole.

+
+

Platforms Supported: All - Requires nuget-package NLog.Extensions.Logging

+

Introduced with NLog.Extensions.Logging ver. 5.0

+
+
<target name="jsonFile" xsi:type="File" fileName="${logFileNamePrefix}.json" >
+      <layout xsi:type="MicrosoftConsoleJsonLayout" includeScopes="Boolean" includeActivityIds="Boolean">
+         <attribute name="extraPropertyName" layout="extraPropertyValue" />
+         <state name="extraStateName" layout="extraStateValue" />
+      </layout>
+</target>
+
+

This would write:

+
{ "Timestamp": "2010-01-01 12:34:56.0000Z", "EventId": 110, "LogLevel": "Debug", "Category": "ConsoleApp.Program", "message": "hello, world", "State": { "location:" "world", "{OriginalFormat}": "hello, {location}" } }
+
+

Parameters

+
    +
  • +

    Attribute - Additional attributes.

    +
  • +
  • +

    State - Additional state attributes, besides the message properties.

    +
  • +
  • +

    IncludeScopes - Include ScopeContext Nested states as additional Scopes-attribute.

    +
  • +
  • +

    IncludeActivityIds - Includes TraceId + SpanId + ParentId from System.Diagnostics.Activity.Current

    +
    +

    Introduced with NLog.Extensions.Logging ver. 6.1.3 - Simulates ActivityTrackingOptions.TraceId | ActivityTrackingOptions.SpanId | ActivityTrackingOptions.ParentId

    +
    +
  • +
  • +

    TimestampFormat - Override the format of the UTC Timestamp. Default = "O"

    +
  • +
  • +

    IndentJson - Enables indent for JSON pretty format with newlines (From JsonLayout). Default = false

    +
  • +
  • +

    DottedRecursion - Flatten object-property-names (From JsonLayout). Default = false

    +
    +

    Introduced with NLog.Extensions.Logging ver. 6.1.1

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MicrosoftConsoleLayout/index.html b/wiki/MicrosoftConsoleLayout/index.html new file mode 100644 index 000000000..84fd1c2bd --- /dev/null +++ b/wiki/MicrosoftConsoleLayout/index.html @@ -0,0 +1,1341 @@ + + + + + + + + MicrosoftConsoleLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders like default Microsoft Console Logger with Microsoft AddConsole Formatter.

+
+

Platforms Supported: All - Requires nuget-package NLog.Extensions.Logging

+

Introduced with NLog.Extensions.Logging ver. 1.7.2

+
+
<nlog>
+  <targets>
+    <target name="lifetimeConsole" xsi:type="Console" layout="${MicrosoftConsoleLayout}"  />
+  </targets>
+  <rules>
+     <logger name="Microsoft.Hosting.Lifetime" level="Info" writeTo="lifetimeConsole" final="true" /> 
+  </rules>
+</nlog>
+
+

This would write:

+
info: Microsoft.Hosting.Lifetime[0]
+      Application started. Press CTRL-C to shut down.
+
+

Parameters

+
    +
  • TimestampFormat - Override the format to output the LogEvent Timestamp. Default (null) means skip timestamp. Can be any argument accepted by DateTime.ToString(format).
    +

    Introduced with NLog.Extensions.Logging ver. 5.0

    +
    +
  • +
  • UseUtcTimestamp - Configure whether to use UTC timezone for the LogEvent Timestamp. Default false.
    +

    Introduced with NLog.Extensions.Logging ver. 5.0

    +
    +
  • +
+

Notes

+ + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/MicrosoftILogger-Target/index.html b/wiki/MicrosoftILogger-Target/index.html new file mode 100644 index 000000000..8e78bed5a --- /dev/null +++ b/wiki/MicrosoftILogger-Target/index.html @@ -0,0 +1,1362 @@ + + + + + + + + MicrosoftILogger Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Forwards messages to Microsoft Extensions Logging (MEL) ILogger-interface.

+
+

Introduced with NLog.Extensions.Logging ver. 1.5.0

+
+

Target can be used in Azure functions for capturing output from existing components that already uses NLog Loggers.

+

Target can also be used for transforming standard log-messages into Json-output.

+

Configuration Parameters

+
    +
  • EventId - Layout for rendering ILogger EventId Layout
  • +
  • EventName - Layout for rendering ILogger EventName Layout
  • +
  • includeMdlc - Include contents of the async MDLC-Layout-Renderer dictionary. Boolean
  • +
  • ContextProperties - Collection of additional context properties
  • +
  • Name - Name of context property
  • +
  • Layout - Value for the context property Layout
  • +
+

Example

+
var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger);
+var nlogConfig = new NLog.Config.LoggingConfiguration();
+nlogConfig.AddRuleForAllLevels(loggerTarget);
+NLog.LogManager.Configuration = nlogConfig;
+var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
+nlogLogger.Info("Hello {planet}", "Earth");
+
+

Example with extra context properties

+
var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger);
+loggerTarget.IncludeMdlc = true;
+loggerTarget.ContextProperties.Add(new TargetPropertyWithContext("threadid", "${threadid}"));
+loggerTarget.ContextProperties.Add(new TargetPropertyWithContext("hostname", "${hostname}"));
+
+var nlogConfig = new NLog.Config.LoggingConfiguration();
+nlogConfig.AddRuleForAllLevels(loggerTarget);
+NLog.LogManager.Configuration = nlogConfig;
+var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
+using (NLog.MappedDiagnosticsLogicalContext.SetScoped("TraceId", Guid.NewGuid())
+{
+   nlogLogger.Info("Hello {planet}", "Earth");
+}
+
+

Example with JsonLayout

+
var jsonLayout = new NLog.Layouts.JsonLayout();
+jsonLayout.IncludeEventProperties = true;
+var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger) { Layout = jsonLayout };
+var nlogConfig = new NLog.Config.LoggingConfiguration();
+nlogConfig.AddRuleForAllLevels(loggerTarget);
+NLog.LogManager.Configuration = nlogConfig;
+var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
+nlogLogger.Info("Hello {planet}", "Earth");
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NDC-Layout-Renderer/index.html b/wiki/NDC-Layout-Renderer/index.html new file mode 100644 index 000000000..8af31ef29 --- /dev/null +++ b/wiki/NDC-Layout-Renderer/index.html @@ -0,0 +1,1344 @@ + + + + + + + + NDC Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +
+

⚠️ NLog 5.0 introduces ScopeContext that replaces NDLC + NDC

+
+

Nested Diagnostics Context - a thread-local structure that keeps a stack of strings and provides methods to output them in layouts.

+
+

Platforms Supported: All

+
+

NDC is considered legacy, and instead is recommended to use NDLC-Layout-Renderer that includes support for async Tasks. See also NLog Context

+

Configuration Syntax

+
${ndc:bottomFrames=Integer:topFrames=Integer:separator=String}
+
+

Parameters

+

Rendering Options

+
    +
  • bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer. Default -1.
  • +
  • topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer. Default -1
  • +
  • separator - Separator to be used for concatenating nested diagnostics context output. string. Default (space)
  • +
+

Examples

+

One level

+
NestedDiagnosticsContext.Push("entering method X");
+... // log here
+NestedDiagnosticsContext.Pop(); //leaving methods
+
+

Then in the log config:

+
${ndc}
+
+

logs entering method X if logged between push() and pop()

+

Multiple levels

+

c# +NestedDiagnosticsContext.Push("entering method X1"); +NestedDiagnosticsContext.Push("entering method X2"); +... // log here +NestedDiagnosticsContext.Pop(); //leaving method X2 +NestedDiagnosticsContext.Pop(); //leaving method X1

+

logs entering method X1 entering method X2

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NDLC-Layout-Renderer/index.html b/wiki/NDLC-Layout-Renderer/index.html new file mode 100644 index 000000000..0c6f31f15 --- /dev/null +++ b/wiki/NDLC-Layout-Renderer/index.html @@ -0,0 +1,1344 @@ + + + + + + + + NDLC Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +
+

⚠️ NLog 5.0 introduces ScopeContext that replaces NDLC + NDC

+
+

Nested Diagnostics Logical Context (NDLC) acts like a stack of string, that are stored in an Async-Local structure (Similar to "Thread Context Stack" or "Nested Diagnostic Context" or in Log4j). It is the async version of NDC-Layout-Renderer

+
+

Platforms Supported: All

+

Introduced in NLog 4.4.1

+
+

It enables one to assign a scope-name to the active scope (Ex. a request method-name). Then all logger-events created within the scoped logical context, can automatically capture the scope-name without needing to specify it with each LogEvent. The specified scope states will automatically flow together with async Tasks.

+

See also NLog Context.

+

Configuration Syntax

+
${ndlc:bottomFrames=Integer:topFrames=Integer:separator=String}
+
+

Parameters

+

Rendering Options

+
    +
  • bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer. Default -1.
  • +
  • topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer. Default -1
  • +
  • separator - Separator to be used for concatenating nested diagnostics context output. string. Default (space)
  • +
+

Examples

+
using (NLog.NestedDiagnosticsLogicalContext.Push("Outer Scope"))
+{
+   Logger.Info("Hello Outer");
+   await InnerOperationAsync();
+}
+
+static async Task InnerOperationAsync()
+{
+    using (NLog.NestedDiagnosticsLogicalContext.Push("Inner Scope"))
+    {
+        Logger.Info("Hello Inner");
+        await Task.Yield();
+    }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NLog-Install/index.html b/wiki/NLog-Install/index.html new file mode 100644 index 000000000..7b58d17f2 --- /dev/null +++ b/wiki/NLog-Install/index.html @@ -0,0 +1,1330 @@ + + + + + + + + NLog Install - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Installing NLog

+ +

Standard install

+
    +
  1. Install the latest NLog from NuGet.
  2. +
  3. Setup initial NLog.config xml-file
  4. +
  5. Example NLog.config can be downloaded and just added to your main application project.
  6. +
  7. Set "Copy To Output Directory" to "Copy if newer" for the NLog.config.
  8. +
+

That's it, you can now compile and run your application and it will be able to use NLog.

+

Tutorial

+

Next step, see Tutorial

+

Troubleshooting

+

If something is not working as expected then check here: +* Troubleshooting Configuration +* Troubleshooting Logging +* Check Internal Logging +* FAQ +* External articles and tutorials

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NLog-Trace-Listener-for-System-Diagnostics-Trace/index.html b/wiki/NLog-Trace-Listener-for-System-Diagnostics-Trace/index.html new file mode 100644 index 000000000..18a0d2529 --- /dev/null +++ b/wiki/NLog-Trace-Listener-for-System-Diagnostics-Trace/index.html @@ -0,0 +1,1372 @@ + + + + + + + + NLogTraceListener - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLogTraceListener

+

Captures output from System Diagnostics Trace and redirects to NLog Targets.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6

+
+

Attributes

+
    +
  • DisableFlush - Ignore flush operations from System.Diagnostics.Trace (Default = True)
  • +
  • DefaultLogLevel - Use this default LogLevel for all LogEvents without any LogLevel.
  • +
  • ForceLogLevel - Always use this LogLevel for all LogEvents (independent on the one provided).
  • +
  • AutoLoggerName - Always capture StackTrace for each LogEvent and resolve Logger-name from callsite (Default = False)
  • +
+

Example config

+

Update app.config to redirect from the WCF ServiceModel-source to NLog Target output:

+
  <system.diagnostics>
+    <sources>
+      <source name="System.ServiceModel.MessageLogging" switchValue="All">
+        <listeners>
+          <add name="nlog" />
+        </listeners>
+      </source>
+    </sources>
+    <sharedListeners>
+      <add name="nlog" type="NLog.NLogTraceListener, NLog"  />
+    </sharedListeners>
+  </system.diagnostics>
+
+

and

+
  <system.serviceModel>
+    <diagnostics>
+        <messageLogging logEntireMessage="true"
+                        logMalformedMessages="true"
+                        logMessagesAtServiceLevel="true"
+                        logMessagesAtTransportLevel="true"
+                        />
+    </diagnostics>
+  </system.serviceModel>
+
+

Example from code:

+
System.Diagnostics.Trace.Listeners.Clear();
+System.Diagnostics.Trace.Listeners.Add(new NLog.NLogTraceListener { Name = "NLog" });
+System.Diagnostics.Trace.WriteLine("Hello World");
+
+

Performance Optimizations

+

NLogTraceListener is threadsafe and supports multithreading. To improve concurrency then ensure useGlobalLock is false (Default = true). See also LowLevelDesign.org - Case of deadlock

+

NLogTraceListener does not need help with flushing, since this is handled automatically by the NLog engine. To improve performance then ensure autoflush is false (Default = false).

+
  <system.diagnostics>
+    <trace useGlobalLock="false" />
+    <trace autoflush="false" />
+  </system.diagnostics>
+
+

StackOverflow Pitfall

+

If having setup NLogTraceListener and at the same time using custom NLog Target that depends on System.Diagnostics.Trace for diagnostics tracing, then one can experience StackOverflowException. Since it is just like calling NLog Logger from NLog Target, which is also forbidden.

+

Possible solution is to setup filtering of the particular Trace-source, so it doesn't become a recursive loop.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NLog-config-Example/index.html b/wiki/NLog-config-Example/index.html new file mode 100644 index 000000000..9ce855c88 --- /dev/null +++ b/wiki/NLog-config-Example/index.html @@ -0,0 +1,1442 @@ + + + + + + + + NLog config Example - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Save this file as "nlog.config" in the root of your application (Add to project with Copy if newer)

+

Simple config example:

+
<?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">
+      autoReload="true"
+      internalLogLevel="Warn"
+      internalLogFile="${basedir}/nlog-internal.txt">
+
+    <variable name="defaultLayout" value="${longdate}|${level}|${message:withException=true}" />
+
+    <targets>
+        <target name="logfile" xsi:type="File" fileName="file.txt" layout="${defaultLayout}" />
+        <target name="console" xsi:type="ColoredConsole" layout="${defaultLayout}" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Debug" writeTo="logfile" />
+        <logger name="*" minlevel="Info" writeTo="console" />
+    </rules>
+</nlog>
+
+

Advanced config example:

+

```xml

+ +

+ autoReload="true" + internalLogLevel="Warn" + internalLogFile="${basedir}/logs/nlog-internal.txt">

+

+

+

+ + +

+ +

+ +

+
<!-- write log message to database -->
+<target xsi:type="Database" name="db">
+  <!-- SQL command to be executed for each entry -->
+  <commandText>INSERT INTO [LogEntries](TimeStamp, Message, Level, Logger) VALUES(getutcdate(), @msg, @level, @logger)</commandText>
+
+  <!-- parameters for the command -->
+  <parameter name="@msg" layout="${message}" />
+  <parameter name="@level" layout="${level}" />
+  <parameter name="@logger" layout="${logger}" />
+
+  <!-- connection string -->
+  <dbProvider>System.Data.SqlClient</dbProvider>
+  <connectionString>server=.\SQLEXPRESS;database=MyLogs;integrated security=sspi</connectionString>
+
+  <!-- commands to install database -->
+  <install-command>
+    <text>CREATE DATABASE MyLogs</text>
+    <connectionString>server=.\SQLEXPRESS;database=master;integrated security=sspi</connectionString>
+    <ignoreFailures>true</ignoreFailures>
+  </install-command>
+
+  <install-command>
+    <text>
+      CREATE TABLE LogEntries(
+      id int primary key not null identity(1,1),
+      TimeStamp datetime2,
+      Message nvarchar(max),
+      level nvarchar(10),
+      logger nvarchar(128))
+    </text>
+  </install-command>
+
+  <!-- commands to uninstall database -->
+  <uninstall-command>
+    <text>DROP DATABASE MyLogs</text>
+    <connectionString>server=.\SQLEXPRESS;database=master;integrated security=sspi</connectionString>
+    <ignoreFailures>true</ignoreFailures>
+  </uninstall-command>
+</target>
+
+<!-- log message to event log -->
+<target xsi:type="EventLog" name="eventLog" source="NLog Demo"
+        layout="${message}${newline}Call site: ${callsite:className=true:methodName=true}${newline}Logger: ${logger}">
+</target>
+
+<!-- increase the performance counter -->
+<target xsi:type="PerfCounter" name="pc1" categoryName="My Log" counterName="My Counter">
+</target>
+
+<!-- send mail through GMail server -->
+<target xsi:type="Mail"
+        name="mail"
+        smtpServer="smtp.gmail.com"
+        smtpPort="587"
+        enableSsl="true"
+        smtpAuthentication="Basic"
+        smtpUserName="${gmailUsername}"
+        smtpPassword="${gmailPassword}"
+        from="${gmailUsername}"
+        to="${gmailUsername}"
+        subject="NLogDemo logs"
+        addNewLines="true"
+        />
+
+<!-- send mail asynchronously, so that it does not block the calling thread -->
+<wrapper-target xsi:type="AsyncWrapper" name="asyncMail">
+  <target-ref name="mail"/>
+</wrapper-target>
+
+<wrapper-target xsi:type="AspNetBufferingWrapper" name="allOutputs">
+  <wrapper-target xsi:type="PostFilteringWrapper">
+    <compound-target xsi:type="SplitGroup">
+      <target-ref name="file" />
+      <target-ref name="db" />
+      <target-ref name="eventLog" />
+      <target-ref name="pc1" />
+      <target-ref name="asyncMail" />
+    </compound-target>
+
+    <!-- during normal execution only log Info messages -->
+    <defaultFilter>level >= LogLevel.Info</defaultFilter>
+
+    <!-- if there is at least one error, log everything from trace level -->
+    <when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
+  </wrapper-target>
+</wrapper-target>
+
+

+

+ + + +````

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NLogDir-Layout-Renderer/index.html b/wiki/NLogDir-Layout-Renderer/index.html new file mode 100644 index 000000000..c3ace3239 --- /dev/null +++ b/wiki/NLogDir-Layout-Renderer/index.html @@ -0,0 +1,1321 @@ + + + + + + + + NLogDir Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The directory where NLog.dll is located.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${nlogdir:dir=String:file=String}
+
+

Parameters

+

Advanced Options

+
    +
  • dir - Name of the directory to be Path.Combine()'d with the directory name.
  • +
  • file - Name of the file to be Path.Combine()'d with the directory name.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NLogViewer-target/index.html b/wiki/NLogViewer-target/index.html new file mode 100644 index 000000000..633135154 --- /dev/null +++ b/wiki/NLogViewer-target/index.html @@ -0,0 +1,1537 @@ + + + + + + + + NLogViewer target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to the remote instance of Log4J XML Viewer.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6

+
+

⚠️ This target uses an non-standard Log4J-format that includes special NLog-schema-values (IncludeNLogData=true). For correct Log4J-xml-format, then use Chainsaw-Target

+

⚠️ This target is not related to the different WPF-Controls like dojo90 NLogViewer or erizet NlogViewer.

+

This target inherits from the Network Target, and so it has also all the properties of the Network Target available. Using the Log4JXmlEventLayout to produce Log4J XML output.

+

ℹ️ NLog v6 has merged NLogViewer-Target and ChainSaw-Target into Log4JXml-Target

+

Configuration Syntax

+
<targets>
+  <target xsi:type="NLogViewer"
+          name="String"
+          address="Layout"
+          newLine="Boolean"
+          onOverflow="Enum"
+          maxMessageSize="Integer"
+          encoding="Encoding"
+          connectionCacheSize="Integer"
+          lineEnding="CRLF|LF|CR|None"
+          maxConnections="Integer"
+          maxQueueSize="Integer"
+          keepConnection="Boolean"
+          onConnectionOverflow="Enum"
+          includeSourceInfo="Boolean"
+          includeCallSite="Boolean"
+          appInfo="String"
+          ndcItemSeparator="String"
+          includeNdc="Boolean"
+          includeNLogData="Boolean">
+    <parameter layout="Layout" name="String"/><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • +

    layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout

    +
  • +
  • +

    encoding - Encoding to be used. Encoding Default: utf-8

    +
  • +
  • +

    newLine - Indicates whether to append newline at the end of log message. Boolean Default: False

    +
  • +
  • +

    lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF. Not used if newLine is false. Introduced in 4.3.8. +Possible values:

    +
  • +
  • CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default)
  • +
  • CR - Carriage Return (ASCII 13).
  • +
  • LF - Line Feed (ASCII 10).
  • +
  • NULL - Null terminator (ASCII 0)
  • +
  • +

    None - No end of line characters.

    +
  • +
  • +

    maxMessageSize - Maximum message size in bytes. Integer Default: 65000

    +
  • +
  • +

    onOverflow - Action that should be taken if the message-size is larger than maxMessageSize. +Possible values:

    +
  • +
  • Discard - Discard the entire message.
  • +
  • Error - Report an error.
  • +
  • Split - Split the message into smaller pieces (Default)
  • +
+

Connection Options

+
    +
  • +

    connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5

    +
  • +
  • +

    address - Network address. Layout
    +The network address can be:

    +
  • +
  • tcp://host:port - TCP (auto select IPv4/IPv6)
  • +
  • tcp4://host:port - force TCP/IPv4
  • +
  • tcp6://host:port - force TCP/IPv6
  • +
  • udp://host:port - UDP (auto select IPv4/IPv6)
  • +
  • udp4://host:port - force UDP/IPv4
  • +
  • udp6://host:port - force UDP/IPv6
  • +
  • http://host:port/pageName - HTTP using POST verb
  • +
  • +

    https://host:port/pageName - HTTPS using POST verb + For SOAP-based webservice support over HTTP use WebService target.

    +
  • +
  • +

    keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True

    +
  • +
  • +

    maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16. Not used if keepConnection is true.

    +
    +

    Introduced with NLog v4.2.1. Default became 16 with NLog v4.5 (Before 0)

    +
    +
  • +
  • +

    onConnectionOverflow - Action that should be taken if the will be more connections than maxConnections.

    +
    +

    Introduced with NLog v4.2.1. Default became Block with NLog v4.5 (Before AllowNewConnnection)

    +
    +
  • +
+

Possible values: + * AllowNewConnnection - Just allow it. + * Block - Block until there's more room in the queue. (default) + * DiscardMessage - Discard the connection item.

+
    +
  • +

    maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer. Default: 10000 (Before NLog 5.0 the default was 0)

    +
    +

    NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. +NLog 5.0.0 enabled queue-support for UDP.

    +
    +
  • +
  • +

    onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize.

    +
    +

    Introduced with NLog 5.0

    +
    +
  • +
  • Discard - Discard the entire message (Default)
  • +
  • Grow - Ignore limit and grow the queue.
  • +
  • Block - Block until queue is below limit.
  • +
+

Payload Options

+
    +
  • +

    includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Default: false.

    +
  • +
  • +

    includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Default: false.

    +
  • +
  • +

    includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: true.

    +
  • +
  • +

    IncludeEventProperties - Include all events properties of a logevent? Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeAllProperties

    +
    +
  • +
  • +

    IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeMdlc or IncludeMdc

    +
    +
  • +
  • +

    IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeNdlc

    +
    +
  • +
  • +

    ScopeNestedSeparator - NDC item separator. Default:

    +
    +

    Before NLog 5.0 option was named NdlcItemSeparator

    +
    +
  • +
  • +

    includeNdc - Indicates whether to include ScopeNested-Layout-Renderer. Default: false.

    +
  • +
  • +

    ndcItemSeparator - NDC item separator. Default:

    +
  • +
  • +

    appInfo - AppInfo field. By default it's the friendly name of the current AppDomain.

    +
  • +
  • +

    loggerName - Logger field. By default it's the output of ${logger}

    +
    +

    Introduced in NLog 4.5

    +
    +
  • +
  • +

    formattedMessage - Message field. By default it's the output of ${message}

    +
    +

    Introduced in NLog 5.3

    +
    +
  • +
  • +

    parameter - Additional context properties that should be included.

    +
  • +
  • name - Name of Parameter. Required.
  • +
  • layout - The layout for the Parameter-Value. Required.
  • +
+

Example

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <targets>
+    <target name="log4view" xsi:type="NLogViewer" address="udp://127.0.0.1:5001" />
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="log4view" />
+  </rules>
+</nlog>
+
+

Available Log4J-XML viewers (See also LogViewer Tools) +- Sentinel - Avoid using TCP since not complete. +- Log2Console +- Logazmic +- Loginator +- Logbert +- LogViewer +- Lilith +- OtrosLogViewer

+

Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this:

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <targets>
+    <target name="throttle_log4view" type="AsyncWrapper" timeToSleepBetweenBatches="50" batchSize="1" overflowAction="Block">
+      <target name="log4view" type="NLogViewer" address="tcp://127.0.0.1:5001" newline="true" />
+    </target>
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="throttle_log4view" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NdlcTiming-Layout-Renderer/index.html b/wiki/NdlcTiming-Layout-Renderer/index.html new file mode 100644 index 000000000..a254e9ddb --- /dev/null +++ b/wiki/NdlcTiming-Layout-Renderer/index.html @@ -0,0 +1,1325 @@ + + + + + + + + NdlcTiming Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NDLC allows one to give a scope name for an operation that can be async. When the scope begins then it automatically captures a timestamp. This can be used to show duration of the active scope.

+
+

Platforms Supported: All

+

Introduced in NLog 4.5

+

NLog 5.0 introduces ScopeContext that unifies MDLC + MDC into a single context.

+
+

See also NLog Context.

+

Configuration Syntax

+
${ndlctiming:currentScope=Boolean:scopeBeginTime=Boolean:format=String}
+
+

Parameters

+

Rendering Options

+
    +
  • currentScope - Whether to only include the duration of the last scope created. Boolean. Default False.
  • +
  • scopeBeginTime - Whether to just display the scope creation time, and not the duration. Boolean. Default False
  • +
  • format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format). string. Default null
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Network-target/index.html b/wiki/Network-target/index.html new file mode 100644 index 000000000..10e148365 --- /dev/null +++ b/wiki/Network-target/index.html @@ -0,0 +1,1502 @@ + + + + + + + + Network target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages over the network using Tcp / Udp / Tls / Http / Https

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6

+
+

For SOAP-based webservice support over HTTP and HTTPS use WebService target, and if needing batch-support to HTTP/HTTPS-EndPoint use NLog.Targets.HttpClient.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Network"
+          name="String"
+          address="Layout"
+          onOverflow="Enum"
+          newLine="Boolean"
+          lineEnding="CRLF|LF|CR|Null|None"
+          layout="Layout"
+          maxMessageSize="Integer"
+          encoding="Encoding"
+          connectionCacheSize="Integer"
+          maxConnections="Integer"
+          maxQueueSize="Integer"
+          keepConnection="Boolean"
+          onConnectionOverflow="Enum"
+          keepAliveTimeSeconds="Integer"
+          sslProtocols="Enum" 
+/>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Payload Options

+
    +
  • +

    layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}

    +
  • +
  • +

    encoding - Encoding to be used. Encoding Default: utf-8

    +
  • +
  • +

    newLine - Indicates whether to append newline at the end of log message. Boolean Default: False

    +
  • +
  • +

    lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF. Not used if newLine is false. Introduced in 4.3.8. +Possible values:

    +
  • +
  • CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default)
  • +
  • CR - Carriage Return (ASCII 13).
  • +
  • LF - Line Feed (ASCII 10).
  • +
  • NULL - Null terminator (ASCII 0)
  • +
  • +

    None - No end of line characters.

    +
  • +
  • +

    compress - Use compression to reduce message size. Default: None

    +
    +

    Introduced with NLog 5.0

    +
    +
  • +
  • None - No compression (Default)
  • +
  • GZip - GZip with optimal compression
  • +
  • +

    GZipFast - GZip with fastest compression

    +
  • +
  • +

    compressMinBytes - Use compression only when message size is higher than limit to reduce overhead in cpu-usage and additional headers. Default: 0

    +
    +

    Introduced with NLog 5.0

    +
    +
  • +
  • +

    maxMessageSize - Maximum message size in bytes. Integer Default: 65000

    +
    +

    Notice when using UDP and the message-size exceeds MTU-size (default 1500 bytes), then IP fragmentation will happen. If network-switch/router has DontFragment enabled, then it will drop large network packets. Usually UDP is only used on local network since no authentication or security, and the network-switch seldom has DontFragment enabled (or under your control to be configured).

    +
    +
  • +
  • +

    onOverflow - Action that should be taken if the message-size is larger than maxMessageSize. +Possible values:

    +
  • +
  • Discard - Discard the entire message.
  • +
  • Error - Report an error.
  • +
  • Split - Split the message into smaller pieces (Default)
  • +
+

Connection Options

+
    +
  • address - Network address. Layout
    +The network address can be:
  • +
  • tcp://host:port - TCP (auto select IPv4/IPv6)
  • +
  • tcp4://host:port - force TCP/IPv4
  • +
  • tcp6://host:port - force TCP/IPv6
  • +
  • udp://host:port - UDP (auto select IPv4/IPv6)
  • +
  • udp4://host:port - force UDP/IPv4
  • +
  • udp6://host:port - force UDP/IPv6
  • +
  • http://host:port/pageName - HTTP using POST verb
  • +
  • +

    https://host:port/pageName - HTTPS using POST verb

    +
  • +
  • +

    keepConnection - Indicates whether to keep connection open whenever possible. Not used for stateless protocols (= http, https) Boolean Default: True

    +
  • +
  • +

    connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5

    +
  • +
  • +

    maxConnections - Maximum current connections when keepConnection = false. 0 = no limit. Integer Default: 100 (Before NLog 5.0 the default was 0)

    +
    +

    Introduced in NLog 4.2.1

    +
    +
  • +
  • +

    onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections.

    +
    +

    Introduced in NLog 4.2.1.

    +
    +
  • +
+

Possible enum values: + * Discard - Discard new messages when reaching limit (Default) (Before NLog 5.0 it was enum value DiscardMessage) + * Grow - Send message and ignore limit (Before NLog 5.0 it was enum value AllowNewConnnection) + * Block - Block until pending connections has been freed.

+
    +
  • +

    maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer. Default: 10000 (Before NLog 5.0 the default was 0)

    +
    +

    NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. +NLog 5.0.0 enabled queue-support for UDP.

    +
    +
  • +
  • +

    onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize.

    +
    +

    Introduced with NLog 5.0

    +
    +
  • +
  • Discard - Discard the entire message (Default)
  • +
  • Grow - Ignore limit and grow the queue.
  • +
  • +

    Block - Block until queue is below limit.

    +
  • +
  • +

    KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer. Default: 0 (Disabled)

    +
    +

    Introduced in NLog 4.6

    +
    +
  • +
  • +

    SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer. Default: 0 (Disabled)

    +
    +

    Introduced in NLog 5.3.4

    +
    +
  • +
  • +

    NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true.

    +
    +

    Introduced in NLog 5.5. Before NLog 6.0 it was default = false.

    +
    +
  • +
  • +

    sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported.

    +
    +

    Introduced in NLog 4.6

    +
    +
  • +
+

Possible values (combination allowed, comma separated): + * None - No SSL/TLS is used + * Default - Accepts Tls or Ssl3 + * Ssl2 - really not recommended + * Ssl3 - not recommended + * Tls - TLS 1.0 + * Tls11 - TLS 1.1 + * Tls12 - TLS 1.2

+
    +
  • +

    SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation)

    +
    +

    Introduced in NLog.Targets.Network v6.0

    +
    +
  • +
  • +

    SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile

    +
    +

    Introduced in NLog.Targets.Network v6.0

    +
    +
  • +
  • +

    SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine)

    +
    +

    Introduced in NLog.Targets.Network v6.1.6

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Newline-Layout-Renderer/index.html b/wiki/Newline-Layout-Renderer/index.html new file mode 100644 index 000000000..ae321346a --- /dev/null +++ b/wiki/Newline-Layout-Renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + Newline Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A newline literal.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${newline}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/NoRawValue-layout-renderer/index.html b/wiki/NoRawValue-layout-renderer/index.html new file mode 100644 index 000000000..d4b1f1088 --- /dev/null +++ b/wiki/NoRawValue-layout-renderer/index.html @@ -0,0 +1,1318 @@ + + + + + + + + NoRawValue layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Prevents the output of another layout renderer to be treated as raw value.

+
+

Platforms Supported: All

+

Introduced in NLog 4.6

+
+

Some NLog targets are able to extract the raw value directly from the layout renderer without first rendering as string.

+

Specifying norawvalue=true will force rendering as string.

+

Configuration Syntax

+
${date:format=yyyy-MM-dd:norawvalue=true}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Null-target/index.html b/wiki/Null-target/index.html new file mode 100644 index 000000000..3168d6cbd --- /dev/null +++ b/wiki/Null-target/index.html @@ -0,0 +1,1342 @@ + + + + + + + + Null target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Discards log messages. Used mainly for debugging and benchmarking.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="Null" name="String" formatMessage="Boolean" layout="Layout" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • +

    formatMessage - Indicates whether to perform layout calculation. Boolean Default: False

    +
  • +
  • +

    layout - Layout used to format log messages. Boolean Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}

    +
  • +
+

Example

+

This example is useful for testing the performance of the NLog engine. Logging rule without any writeTo= option is much faster way to do filtering (Zero allocation).

+
<targets>
+  <target xsi:type="Null" name="BlackHole" formatMessage="false"  />
+</targets>
+<rules>
+   <!-- ignore events written that are written to a logger which starts with "Namespace." -->
+   <logger name="Namespace.*" minlevel="Debug" writeTo="BlackHole" final="true" />     
+</rules>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ObjectPath-Layout-Renderer/index.html b/wiki/ObjectPath-Layout-Renderer/index.html new file mode 100644 index 000000000..0726a6954 --- /dev/null +++ b/wiki/ObjectPath-Layout-Renderer/index.html @@ -0,0 +1,1329 @@ + + + + + + + + ObjectPath Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render a property of an object.

+

Introducted in NLog 4.6.7

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${object-path:${exception}:path=String:Format=String:Culture=String}
+${exception:objectpath=String} // Ambient way
+
+

Parameters

+

Rendering Options

+
    +
  • objectpath - Path to the property. Nested properties are supported. Arrays aren't supported.
  • +
  • format - Format when rendering.
  • +
  • culture - Culture code used for formatting.
  • +
+

Example

+

Assume we catch new ExternalException("Exception with errorCode", 5000)

+
${exception:objectpath=HResult} // results in 5000
+${object-path:${exception}:path=HResult:Culture=NL-nl:format=N2}"; // results in 5.000,00
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/OnException-Layout-Renderer/index.html b/wiki/OnException-Layout-Renderer/index.html new file mode 100644 index 000000000..1e75e4f36 --- /dev/null +++ b/wiki/OnException-Layout-Renderer/index.html @@ -0,0 +1,1321 @@ + + + + + + + + OnException Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Only outputs the inner layout when exception has been defined for log message.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${onexception:inner=Layout}
+
+

Parameters

+

Transformation Options

+
    +
  • inner - Wrapped layout. Layout
  • +
  • else - Layout if the condition is not true (introduced in NLog 5.0.5)
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/OnHasProperties-Layout-Renderer/index.html b/wiki/OnHasProperties-Layout-Renderer/index.html new file mode 100644 index 000000000..5fa6398dc --- /dev/null +++ b/wiki/OnHasProperties-Layout-Renderer/index.html @@ -0,0 +1,1325 @@ + + + + + + + + OnHasProperties Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Only outputs the inner layout when event properties from structured logging are included with the logevent.

+
+

Platforms Supported: All

+

Introduced with NLog 4.7

+
+

Configuration Syntax

+
${onHasProperties:inner=Layout}
+
+

Parameters

+

Transformation Options

+
    +
  • inner - Wrapped layout. Layout
  • +
  • else - Layout if the condition is not true (introduced in NLog 5.0.5)
  • +
+

Example:

+
${onHasProperties:, Properties\: ${all-event-properties}}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/OutputDebugString-target/index.html b/wiki/OutputDebugString-target/index.html new file mode 100644 index 000000000..3acb24232 --- /dev/null +++ b/wiki/OutputDebugString-target/index.html @@ -0,0 +1,1340 @@ + + + + + + + + OutputDebugString target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Outputs log messages through the OutputDebugString Win32 API. That can be monitored using DebugView or Harvester

+
+

Platforms Supported: Limited - Requires Windows and requires nuget-package NLog.OutputDebugString since NLog 5.0

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="OutputDebugString" name="String" layout="Layout" />
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Layout Options

+
    +
  • layout - Layout used to format log messages. Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
  • +
  • header - Layout used to format header-output when initializing. Layout
    +

    Introduced with NLog 5.0

    +
    +
  • +
  • footer - Layout used to format footer-output when closing. Layout
    +

    Introduced with NLog 5.0

    +
    +
  • +
+

Notes

+

Alternative targets for diagnostic output: +- Trace-target for output to System.Diagnostics.Trace +- DebugSystem-target for output to System.Diagnostics.Debug +- Debugger-target for output to System.Diagnostics.Debugger.Log

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Pad-Layout-Renderer/index.html b/wiki/Pad-Layout-Renderer/index.html new file mode 100644 index 000000000..d42285cd9 --- /dev/null +++ b/wiki/Pad-Layout-Renderer/index.html @@ -0,0 +1,1329 @@ + + + + + + + + Pad Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Applies padding to another layout output.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${pad:padCharacter=Char:padding=Integer:fixedLength=Boolean
+     :inner=Layout:alignmentOnTruncation=PaddingHorizontalAlignment}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:padding=5}
+
+

Parameters

+

Transformation Options

+
    +
  • padCharacter - Padding character. Char Default: (space character)
  • +
  • padding - Number of characters to pad the output to. +Positive padding values cause left padding, negative values cause right padding to the desired width. Integer
  • +
  • fixedLength - Indicates whether to trim the rendered text to the absolute value of the padding length. Boolean Default: False
  • +
  • inner - Wrapped layout. Layout
  • +
  • alignmentOnTruncation - Indicates whether a value that has been truncated due to fixedLength=true is aligned to the left (characters removed from the right) or right (characters removed from the left). This is independent of the alignment applied when padding shorter strings out to padding characters. This property was introduced in NLog 4.0. Earlier versions always apply an alignment equivalent to alignmentOnTruncation=left. PaddingHorizontalAlignment Default: Left
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/PerfCounter-target/index.html b/wiki/PerfCounter-target/index.html new file mode 100644 index 000000000..132002d45 --- /dev/null +++ b/wiki/PerfCounter-target/index.html @@ -0,0 +1,1387 @@ + + + + + + + + PerfCounter target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

PerformanceCounterTarget updates specified Windows Performance Counter on each write.

+
+

Platforms Supported: Limited - Windows only and requires nuget-package NLog.PerformanceCounter since NLog 5.0

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="PerfCounter"
+          counterName="String"
+          categoryName="String"
+          instanceName="String"
+          counterHelp="String"
+          counterType="Enum"
+          autoCreate="Boolean"
+          incrementValue="Layout"
+           />
+</targets>
+
+

The actual Performance Counter can be created by Installing targets, or by using autoCreate="true".

+

Read more about using the Configuration File.

+

Parameters

+
    +
  • +

    counterName - Name of the performance counter. Required.

    +
  • +
  • +

    categoryName - Name of the performance counter category. Required.

    +
  • +
  • +

    instanceName - Performance counter instance name.

    +
  • +
  • +

    counterHelp - Counter help text.

    +
  • +
  • +

    counterType - Performance counter type. Default: NumberOfItems32
    +Possible values:

    +
  • +
  • AverageBase
  • +
  • AverageCount64
  • +
  • AverageTimer32
  • +
  • CounterDelta32
  • +
  • CounterDelta64
  • +
  • CounterMultiBase
  • +
  • CounterMultiTimer
  • +
  • CounterMultiTimer100Ns
  • +
  • CounterMultiTimer100NsInverse
  • +
  • CounterMultiTimerInverse
  • +
  • CounterTimer
  • +
  • CounterTimerInverse
  • +
  • CountPerTimeInterval32
  • +
  • CountPerTimeInterval64
  • +
  • ElapsedTime
  • +
  • NumberOfItems32
  • +
  • NumberOfItems64
  • +
  • NumberOfItemsHEX32
  • +
  • NumberOfItemsHEX64
  • +
  • RateOfCountsPerSecond32
  • +
  • RateOfCountsPerSecond64
  • +
  • RawBase
  • +
  • RawFraction
  • +
  • SampleBase
  • +
  • SampleCounter
  • +
  • SampleFraction
  • +
  • Timer100Ns
  • +
  • +

    Timer100NsInverse

    +
  • +
  • +

    autoCreate - Indicates whether performance counter should be automatically created. Default: false.

    +
  • +
  • +

    incrementValue - The value by which to increment the counter. Layout. Default: 1.

    +
    +

    Introduced in NLog v4.2

    +
    +
  • +
+

Notes

+

Alternative one can use NLog.ETW for writing to ETW EventCounter using EtwEventCounter-Target.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Performance/index.html b/wiki/Performance/index.html new file mode 100644 index 000000000..0a3281f6c --- /dev/null +++ b/wiki/Performance/index.html @@ -0,0 +1,1370 @@ + + + + + + + + Performance - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog has been created with performance in mind, and is optimized to have minimal impact on the actual application-code. It can easily handle 500.000 messages/sec, but if using NLog in ways not intended, then you might not get the expected performance.

+

Logger optimizations

+

When using the NLog Logger, then there are some things that affects optimal performance:

+
    +
  • Avoid constantly calling LogManager.GetLogger() and LogManager.GetCurrentClassLogger(), instead use static readonly variables.
  • +
  • Defer message-formatting by not using string.format and string interpolation (Ex $"Hello {world}") but pass the arguments to the log method.
  • +
  • Avoid logging synchronous to slow NLog targets (Ex. console or file), instead it is recommend to apply the AsyncWrapper.
  • +
  • Conditional logging is recommended when creation of the log-message has an overhead, and logging is not always turned on.
  • +
+

Defer message-formatting

+

NLog has a strong focus on being able to defer the message-formatting. When using <targets async="true"> or AsyncWrapper target then the formatting and writing can be done by a background-thread. The async message-formatting requires that all parameters are immutable. To ensure that they don't change after having called the Logger (Ex logging an object and disposing the object afterwards should not log a disposed object).

+

The NLog Logger (During the creation of LogEventInfo) checks whether all parameters are immutable / primitive. If one is complex-object, then message-formatting is not deferred. When having more than 5 parameters then it will skip the performance optimization, because checking the immutable state of the parameters has a cost.

+

Notice when using Microsoft Extension Logging with NLog, then NLog is not able to perform this optimization, because Microsoft Extension Logging handles the message-parsing and -formatting upfront.

+

Layout configuration

+

Many NLog LayoutRenderers have little overhead, and allows deferring the layout logic to background-thread when enabled with <targets async="true"> (Activates AsyncWrapper target).

+

But if using NLog LayoutRenders that requires context capture of the current application-thread like ${threadid}, then the application-thread will get extra overhead to perform this context capture. This also happens with most ${aspnet-request}-layout-renderers as they have to extract values from the active HttpContext. If performance is very important then one should focus on using ${longdate}, ${logger}, ${level}, ${message} and ${event-properties}.

+

One should be careful with using ${callsite} and ${stacktrace} that outputs the call-site of the application-thread, because NLog makes the application-thread capture its current StackTrace, which is very expensive. NLog 5.0 introduces a new fluent Logger-API, that support caller-member-attributes, and reduces the overhead from using ${callsite}.

+

Conditional logging

+

NLog Logger has very little overhead when LogLevel is not enabled for any targets. But it might be noticeable if running in a tight loop and doing almost nothing, besides calling NLog Logger.

+

If having a complex logging statement, then one can consider checking if LogLevel is enabled before executing it:

+
if (Logger.IsDebugEnabled)
+    Logger.Debug(GenerateMassiveLogEvent());
+
+

Starting of NLog 4.0 it’s possible to only include the Trace and Debug calls for DEBUG-builds. Instead of:

+
Logger.Debug("entering method {0}", methodname);
+
+

Then use:

+
Logger.ConditionalDebug("entering method {0}", methodname);
+
+

This call will be removed by the .Net compiler if the DEBUG conditional compilation symbol is not set – default for release build.

+

InternalLogger overhead

+

NLog Internal Logging is very useful for troubleshooting. To be alerted about potential logging issues, then one can enable internalLogLevel="Warn" to get warnings and errors.

+

During troubleshooting sessions then one might use internalLogLevel="Trace", but make sure to turn it off again when issue has been resolved. The InternalLogger is not written for performance, and will give a significant performance hit.

+

Automatic Extension Loading

+

NLog 4.0 automatically scans for assemblies that contains extensions for NLog at initial startup. This will automatically trigger loading of debugging symbols. This will be give the experience that NLog slows down the application startup.

+

NLog 5.0 no longer scans for assemblies at startup because of the startup overhead, and also because it doesn't work with the new csproj <packagereference>.

+

To skip the assembly scan for NLog v4, then execute this statement before loading NLog Config or creating NLog Logger:

+
NLog.Config.ConfigurationItemFactory.Default = new NLog.Config.ConfigurationItemFactory(typeof(NLog.ILogger).GetTypeInfo().Assembly);
+
+

Visual Studio Debugger pauses during NLog initialization

+

Visual Studio is slow the first time when debugging application and having configured to load relevant debug symbol information.

+

To avoid these pauses then one can configure Visual Studio to 'Enable Just My Code`

+

It is a checkbox in Visual Studio Options. See Just my Code

+

File Logging Performance

+

Single process applications (in single AppDomain) can optimize performance by configuring the FileTarget attributes: +- keepFileOpen = True +- concurrentwrites = False

+

See also FileTarget - Performance

+

To avoid the blocking file write operation, then one can consider to wrap the FileTarget within a AsyncWrapper (Very important if using keepFileOpen = False). This will also optimize the writing to disk, as it will be done in batches. Be careful as the default behavior is to discard log operations if they come fast. So it is recommended to change the overflow-policy for non-network targets:

+
<targets>
+   <default-wrapper xsi:type="AsyncWrapper" overflowAction="Block" />
+
+   ... Your File Targets Here ...
+</targets>
+
+

Remember to Flush is very important, to ensure background threads have completed writing before application exit.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/PerformanceCounter-Layout-Renderer/index.html b/wiki/PerformanceCounter-Layout-Renderer/index.html new file mode 100644 index 000000000..be62bebdb --- /dev/null +++ b/wiki/PerformanceCounter-Layout-Renderer/index.html @@ -0,0 +1,1343 @@ + + + + + + + + PerformanceCounter Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render value retrieved from Windows Performance Counter.

+
+

Platforms Supported: Limited - Windows only and requires nuget-package NLog.PerformanceCounter since NLog 5.0

+
+

Configuration Syntax

+
${performancecounter:Category=String:Counter=PerformanceCounterType:Instance=String
+                    :IncrementValue=Integer:MachineName:string
+                     format=String:culture=Culture}
+
+

Parameters

+

Performance Counter Options

+
    +
  • Counter - Name of the performance counter. Required.
  • +
  • Category - Name of the counter category. Required.
  • +
  • Instance - Name of the performance counter instance. Optional.
    +

    NLog 4.6 will automatically use current process as Instance-Id when Category = "Process" (Supports multi-instance)

    +
    +
  • +
  • MachineName The name of the machine to read the performance counter from. Optional.
  • +
+

Rendering Options

+
    +
  • +

    Format - Format string for conversion from float to string.

    +
    +

    Introduced with NLog v4.6

    +
    +
  • +
  • +

    Culture - Culture used for rendering. Culture

    +
    +

    Introduced with NLog v4.6

    +
    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Platform-Support/index.html b/wiki/Platform-Support/index.html new file mode 100644 index 000000000..abbc24158 --- /dev/null +++ b/wiki/Platform-Support/index.html @@ -0,0 +1,1310 @@ + + + + + + + + Platform Support - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The platform support is now integrated with the config options list.

+

See https://nlog-project.org/config/

+

screenshot:

+

image

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/PostFilteringWrapper-target/index.html b/wiki/PostFilteringWrapper-target/index.html new file mode 100644 index 000000000..8f651e1dd --- /dev/null +++ b/wiki/PostFilteringWrapper-target/index.html @@ -0,0 +1,1349 @@ + + + + + + + + PostFilteringWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Filters buffered log entries based on a set of conditions that are evaluated on a group of events.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="AsyncWrapper" name="String">
+     <target xsi:type="PostFilteringWrapper" name="String" defaultFilter="Condition">
+       <target xsi:type="wrappedTargetType" ...target properties... />
+       <when exists="Condition" filter="Condition"/><!-- repeated -->
+     </target>
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Filtering Options

+
    +
  • defaultFilter - Default filter to be applied when no specific rule matches. Conditions
  • +
+

Filtering Rules

+
    +
  • rules - The collection of filtering rules. The rules are processed top-down and the first rule that matches determines the filtering condition to be applied to log events. Collection
    +Each collection item is represented by \ element with the following attributes:
  • +
  • exists - Condition to be tested. Conditions Required.
  • +
  • filter - Resulting filter to be applied when the condition matches. Conditions Required.
  • +
+

Remarks

+

Before NLog 4.6.4 then the filtering only worked when using PostFilteringWrapper with some type of buffering target or wrapper, such as AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper. It is still a good idea add the wrapper when using the rules filtering-logic (will inspect the entire batch when a single logevent matches exists).

+
<targets>
+  <target name="file" xsi:type="BufferingWrapper" bufferSize="100">
+    <target xsi:type="PostFilteringWrapper" defaultFilter="level &gt;= LogLevel.Info">
+      <target xsi:type="File" fileName="${basedir}/file.txt" />
+      <when exists="level &gt;= LogLevel.Warn" filter="level &gt;= LogLevel.Debug"/>
+    </target>
+  </target>
+</targets>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ProcessDir-Layout-Renderer/index.html b/wiki/ProcessDir-Layout-Renderer/index.html new file mode 100644 index 000000000..aaf02aad0 --- /dev/null +++ b/wiki/ProcessDir-Layout-Renderer/index.html @@ -0,0 +1,1329 @@ + + + + + + + + ProcessDir Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The current process executable directory of the application.

+
+

Platforms Supported: All

+

Introduced in NLog v4.7.1.

+

See also ${basedir}, ${specialfolder}, ${currentdir}, ${tempdir}

+
+

Configuration Syntax

+

${processdir:dir=String:file=String}

+

Parameters

+

Advanced Options

+
    +
  • +

    dir: Name of the directory to be Path.Combine()'d with the process directory.

    +
  • +
  • +

    file: Name of the file to be Path.Combine()'d with the process directory.

    +
  • +
+

Remarks

+

This is the same as using ${basedir:processDir=true}.

+

See also: FileTarget FileName Directory

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ProcessId-Layout-Renderer/index.html b/wiki/ProcessId-Layout-Renderer/index.html new file mode 100644 index 000000000..b1840365b --- /dev/null +++ b/wiki/ProcessId-Layout-Renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + ProcessId Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The identifier of the current process.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${processid}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ProcessInfo-Layout-Renderer/index.html b/wiki/ProcessInfo-Layout-Renderer/index.html new file mode 100644 index 000000000..ccfb6f455 --- /dev/null +++ b/wiki/ProcessInfo-Layout-Renderer/index.html @@ -0,0 +1,1365 @@ + + + + + + + + ProcessInfo Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The information about the running process returned by Process.GetCurrentProcess()

+
+

Platforms Supported: All

+

⚠️ NLog v6.2 has marked this as obsolete, because the Process-object has lots of dependencies when AOT. Instead use alternatives ${processid} or ${processname} or ${processstart} or ${processtime} or ${gc:WorkingSet}

+
+

Configuration Syntax

+
${processinfo:property=Enum:format=string}
+
+

Parameters

+

Rendering Options

+
    +
  • property - Property to retrieve. Default: Id
    + Possible values:
  • +
  • ExitCode - Exit Code (Not available for current process).
  • +
  • ExitTime - Exit Time (Not available for current process).
  • +
  • Handle - Process Handle.
  • +
  • HandleCount - Handle Count.
  • +
  • HasExited - Whether process has exited (Not available for current process).
  • +
  • Id - Process ID.
  • +
  • MachineName - Machine name.
  • +
  • MainWindowHandle - Handle of the main window.
  • +
  • MainWindowTitle - Title of the main window.
  • +
  • MaxWorkingSet - Maximum Working Set.
  • +
  • MinWorkingSet - Minimum Working Set.
  • +
  • NonPagedSystemMemorySize - Non-paged System Memory Size.
  • +
  • NonPagedSystemMemorySize64 - Non-paged System Memory Size (64-bit).
  • +
  • PagedMemorySize - Paged Memory Size.
  • +
  • PagedMemorySize64 - Paged Memory Size (64-bit)..
  • +
  • PagedSystemMemorySize - Paged System Memory Size.
  • +
  • PagedSystemMemorySize64 - Paged System Memory Size (64-bit).
  • +
  • PeakPagedMemorySize - Peak Paged Memory Size.
  • +
  • PeakPagedMemorySize64 - Peak Paged Memory Size (64-bit).
  • +
  • PeakVirtualMemorySize - Peak Virtual Memory Size.
  • +
  • PeakVirtualMemorySize64 - Peak Virtual Memory Size (64-bit)..
  • +
  • PeakWorkingSet - Peak Working Set Size.
  • +
  • PeakWorkingSet64 - Peak Working Set Size (64-bit).
  • +
  • PriorityBoostEnabled - Whether priority boost is enabled.
  • +
  • PriorityClass - Priority Class.
  • +
  • PrivateMemorySize - Private Memory Size.
  • +
  • PrivateMemorySize64 - Private Memory Size (64-bit).
  • +
  • PrivilegedProcessorTime - Privileged Processor Time.
  • +
  • ProcessName - Process Name.
  • +
  • Responding - Whether process is responding.
  • +
  • SessionId - Session ID.
  • +
  • StartTime - Process Start Time.
  • +
  • TotalProcessorTime - Total Processor Time.
  • +
  • UserProcessorTime - User Processor Time.
  • +
  • VirtualMemorySize - Virtual Memory Size.
  • +
  • VirtualMemorySize64 - Virtual Memory Size (64-bit).
  • +
  • WorkingSet - Working Set Size.
  • +
  • +

    WorkingSet64 - Working Set Size (64-bit)

    +
  • +
  • +

    format formatstring in the value is formatable. Ex. formatting process StartTime. Introduced in NLog 4.4

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ProcessStart-Layout-Renderer/index.html b/wiki/ProcessStart-Layout-Renderer/index.html new file mode 100644 index 000000000..18cdfe450 --- /dev/null +++ b/wiki/ProcessStart-Layout-Renderer/index.html @@ -0,0 +1,1323 @@ + + + + + + + + ProcessStart Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The start time of the current process.

+
+

Platforms Supported: All

+

Introduced with NLog v6.2

+
+

Configuration Syntax

+
${processstart:Format=String:UniversalTime=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • Format - DateTime ToString(...) Format specifier. Default = yyyy-MM-dd HH:mm:ss
  • +
  • UniversalTime - DateTime UTC time. Default = False.
  • +
  • Culture - DateTime formatting culture. Default = Invariant.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Processname-Layout-Renderer/index.html b/wiki/Processname-Layout-Renderer/index.html new file mode 100644 index 000000000..b651bf7f6 --- /dev/null +++ b/wiki/Processname-Layout-Renderer/index.html @@ -0,0 +1,1320 @@ + + + + + + + + Processname Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The name of the current process.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${processname:fullName=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • fullName - Indicates whether to write the full path to the process executable. Boolean Default: False
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Processtime-Layout-Renderer/index.html b/wiki/Processtime-Layout-Renderer/index.html new file mode 100644 index 000000000..020262c74 --- /dev/null +++ b/wiki/Processtime-Layout-Renderer/index.html @@ -0,0 +1,1330 @@ + + + + + + + + Processtime Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The process lifetime in short sortable format HH:mm:ss.fff.

+
+

Platforms Supported: All

+

See also ${time}, ${date}, ${longdate}, ${shortdate}

+
+

Configuration Syntax

+
${processtime:invariant=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • invariant - Indicates whether to output in invariant time format, and not lookup of current cultureinfo. Boolean Default: true (Before NLog 5.0 the default was false)
    +

    Introduced with NLog 4.5.2

    +
    +
  • +
  • culture - Culture used for time format. Default: InvariantCulture
    +

    Introduced with NLog 5.0

    +
    +
  • +
+

Time Source Precision

+

NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount. For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Properties-constraints-for-custom-extensions/index.html b/wiki/Properties-constraints-for-custom-extensions/index.html new file mode 100644 index 000000000..f9641df0f --- /dev/null +++ b/wiki/Properties-constraints-for-custom-extensions/index.html @@ -0,0 +1,1367 @@ + + + + + + + + Properties constraints for custom extensions - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Custom Targets, layout etc. could have properties. When configuring from the XML config, there are some limitations on the types.

+

Supported types

+

Supported types for Targets, Layouts and Layout renderers:

+
    +
  • .NET primitive types: e.g. bool, char, decimal, double, float, int, uint, etc.
  • +
  • Enums (use short name in the XML)
  • +
  • Encoding
  • +
  • CultureInfo
  • +
  • Type
  • +
  • LineEndingMode
  • +
  • Uri
  • +
  • NLog types: Layout, SimpleLayout & ConditionExpression
  • +
  • Types which has an implicit conversion from string
  • +
  • Types which are using TypeDescriptor from string
  • +
  • Collections, introduced in NLog 4.4. See section Collection types
  • +
+

Collection types

+

Introduced in NLog 4.4, collection types could be used.

+

Usage in XML: comma separated string. If the value contains a comma, single quote the whole value.

+

Examples: +- value="one arg" +- value="1,2" +- value="value1,'value2, with comma'"

+

Supported types: + - IList<T> / IList + - IEnumerable<T> / IEnumerable + - ISet<T> / HashSet<T>

+

with the following types: + - .NET built in types (string, int, double, object) + - enums + - culture, encoding, Type + - not supported: Layout

+

Not supported: +- Arrays +- Non-generic List +- Non-gereric IList +- Custom class implementing/inheriting types listed above (because of performance)

+

PS: .NET 3.5 hasn't ISet<T>, so use HashSet<T>

+

XML Elements

+

For targets and layout renderers there is also support for XML elements.

+

E.g. the JSON layout:

+
<target name="jsonFile" xsi:type="File" fileName="${logFileNamePrefix}.json">
+      <layout xsi:type="JsonLayout">
+              <attribute name="time" layout="${longdate}" />
+              <attribute name="level" layout="${level:upperCase=true}"/>
+              <attribute name="message" layout="${message}" />
+       </layout>
+</target>
+
+

Usage in C#

+

+[ArrayParameter(typeof(JsonAttribute), "attribute")]
+public IList<JsonAttribute> Attributes { get; private set; }
+
+[NLogConfigurationItem]
+public class JsonAttribute {} //needs default ctor
+
+
+

Another example is the Database target

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/QPC-Layout-Renderer/index.html b/wiki/QPC-Layout-Renderer/index.html new file mode 100644 index 000000000..812c01559 --- /dev/null +++ b/wiki/QPC-Layout-Renderer/index.html @@ -0,0 +1,1325 @@ + + + + + + + + QPC Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

High precision timer, based on the value returned from QueryPerformanceCounter() optionally converted to seconds.

+
+

Platforms Supported: Limited (Only for .NetFramework and deprecated with NLog 5.0)

+
+

Configuration Syntax

+
${qpc:normalize=Boolean:difference=Boolean:alignDecimalPoint=Boolean
+     :precision=Integer:seconds=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • normalize - Indicates whether to normalize the result by subtracting it from the result of the first call (so that it's effectively zero-based). Boolean Default: True
  • +
  • difference - Indicates whether to output the difference between the result of QueryPerformanceCounter and the previous one. Boolean Default: False
  • +
  • alignDecimalPoint - Indicates whether to align decimal point (emit non-significant zeros). Boolean Default: True
  • +
  • precision - Number of decimal digits to be included in output. Integer Default: 4
  • +
  • seconds - Indicates whether to convert the result to seconds by dividing by the result of QueryPerformanceFrequency(). Boolean Default: True
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/RandomizeGroup-target/index.html b/wiki/RandomizeGroup-target/index.html new file mode 100644 index 000000000..00e86c7c1 --- /dev/null +++ b/wiki/RandomizeGroup-target/index.html @@ -0,0 +1,1327 @@ + + + + + + + + RandomizeGroup target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to a randomly selected target.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="RandomizeGroup" name="String">
+    <target xsi:type="wrappedTargetType" ... />
+    <target xsi:type="wrappedTargetType" ... />
+    ...
+    <target xsi:type="wrappedTargetType" ... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/RegEx-Replace-Layout-Renderer/index.html b/wiki/RegEx-Replace-Layout-Renderer/index.html new file mode 100644 index 000000000..d9eb17a4a --- /dev/null +++ b/wiki/RegEx-Replace-Layout-Renderer/index.html @@ -0,0 +1,1341 @@ + + + + + + + + RegEx Replace Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

RegEx for replacing a string in the output of another layout with another string.

+
+

Platforms Supported: All - Requires nuget-package NLog.RegEx

+
+

There is also ${replace} if not needing RegEx-support.

+

Configuration Syntax

+
${regex-replace:searchFor=String:wholeWords=Boolean:replaceWith=String
+         :ignoreCase=Boolean:inner=Layout}
+
+

Parameters

+

Search/Replace Options

+
    +
  • searchFor - Text to search for. String
  • +
  • replaceWith - Replacement string.
  • +
  • ignoreCase - Indicates whether to ignore case when searching. Boolean Default: False
  • +
  • wholeWords - Indicates whether to search for whole words. Boolean Default: False
  • +
  • replaceGroupName - Specifies group name for Matched Subexpressions, where it will perform replace of all matches with that group name. Ex. (?<groupname>subexpression)
  • +
  • compileRegex - Compiles the Regex. Setting this to true can improve regex performance, but costs memory. Boolean Default: False
  • +
+

Examples

+

Replace sensitive data, that starts with password= or password:

+
<variable name="replacePasswords"
+  value="${regex-replace:inner=${message}:searchFor=(?i)(?&lt;=password[=\:])(.*?)(?=(\;|$| )):replaceWith=******}" />
+
+

Truncate after token, search for , and replace everything after with empty string:

+
<variable name="truncateAfterComma"
+  value="${regex-replace:inner=${aspnet-request-ip}:searchFor=,.*:replaceWith=}" />
+
+

With Regular Expressions keep in mind the content escaping rules to escape special characters in Regex. Specifically } and \. So for example the regular expression (\d{3})+ would need to be escaped like so in your configuration

+
<variable name="messageNoDigits" 
+  value="${regex-replace:inner=${message}:searchFor=(\\d{3\})+:replaceWith=}" />
+
+

There is a dedicated layout ${replace-newlines} for replacing / removing newlines (handles both Unix and Windows newlines)

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Register-your-custom-component/index.html b/wiki/Register-your-custom-component/index.html new file mode 100644 index 000000000..5c3d12f8a --- /dev/null +++ b/wiki/Register-your-custom-component/index.html @@ -0,0 +1,1372 @@ + + + + + + + + Register your custom component - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog extensions must be registered before they can be used in NLog configuration. This can be done in different ways:

+

Register the NLog extensions from code

+

NLog 5.2 encourage registration from code of the NLog-extension-types, when you know up-front what will be needed.

+
NLog.LogManager.Setup().SetupExtensions(ext => {
+    ext.RegisterTarget<MyCustomTarget>();
+    ext.RegisterLayout<MyCustomLayout>();
+    ext.RegisterLayoutRenderer<MyCustomLayoutRenderer>();
+});
+
+

This will improve application startup-time, as one can skip assembly-loading and assembly-scanning for NLog-extension-types. It also ensures that build-trimming for the application will work (linker-tree-shake).

+

Note registrations must be performed before LogManager.Configuration is loaded, which happens automatically on calling LogManager.GetLogger("..") or LogManager.GetCurrentClassLogger()

+

Include assembly-name in type for NLog extensions

+

NLog 5.0 introduces the ability to use fully qualified name when specifying the type for a config-item.

+
<nlog> 
+  <targets> 
+    <target name="mytarget" type="CustomTarget, MyAssemblyName" />
+  </targets> 
+
+

Register NLog extensions from assembly in NLog config

+

Include your assembly with the <extensions> syntax. Use the assembly name (not the filename)

+
<nlog> 
+  <extensions> 
+    <add assembly="MyAssemblyName"/> 
+  </extensions> 
+
+

Register NLog extensions from assembly at runtime

+

Provide the name of the assembly, which contains the NLog extension types:

+
NLog.LogManager.Setup().SetupExtensions(s => s.RegisterAssembly("MyAssemblyName"));
+
+

Since NLog v5.2 this is no longer recommended. Instead one should explicit register the NLog-extension-types from code.

+

Register NLog extension from code (Old style)

+

Introduced with NLog v4.4. Now marked as obsolete with NLog v5.2

+
//target
+Target.Register<MyNamespace.MyFirstTarget>("MyFirst"); //generic
+Target.Register("MyFirst", typeof(MyNamespace.MyFirstTarget)); //OR, dynamic
+
+//layout renderer
+LayoutRenderer.Register<MyNamespace.MyFirstLayoutRenderer>("MyFirst"); //generic
+LayoutRenderer.Register("MyFirst", typeof(MyNamespace.MyFirstLayoutRenderer)); //dynamic
+
+//layout
+Layout.Register<MyNamespace.CsvLayout>("csv"); //generic
+Layout.Register("csv", typeof(MyNamespace.CsvLayout)); //dynamic
+
+

Register NLog extension from code (Older style)

+

Now marked as obsolete with NLog v5.2

+
//target
+ConfigurationItemFactory.Default.Targets
+                            .RegisterDefinition("MyFirst", typeof(MyNamespace.MyFirstTarget));
+
+//layout renderer
+ConfigurationItemFactory.Default.LayoutRenderers
+                            .RegisterDefinition("hello-world", typeof(MyNamespace.HelloWorldLayoutRenderer));
+
+//layout 
+ConfigurationItemFactory.Default.Layouts
+                            .RegisterDefinition("csv", typeof(MyNamespace.CsvLayout));
+
+
+
+

Automatic loading NLog extensions from assemblies with NLog prefix

+

⚠️ NLog 5.0 no longer automatically scans all assemblies to register NLog extensions. This avoids an overhead during startup, and because it doesn't work with <packagereference>. To explicit enable the automatic scanning, then one can specify autoLoadAssemblies="true" in <nlog>.

+

Introduced in NLog 4.0, where it automatically scans all assemblies starting with "NLog", and attempt to register any available NLog extensions types.

+

Name your assembly "NLog*.dll", like “NLog.CustomTarget.dll”. When the assembly is in the same folder as nlog.dll, it will be autoloaded when the configuration changes.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Registry-Layout-Renderer/index.html b/wiki/Registry-Layout-Renderer/index.html new file mode 100644 index 000000000..f2d5c27bc --- /dev/null +++ b/wiki/Registry-Layout-Renderer/index.html @@ -0,0 +1,1331 @@ + + + + + + + + Registry Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A value from the Registry.

+
+

Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsRegistry since NLog 5.0

+
+

Configuration Syntax

+
${registry:value=Layout:key=Layout:defaultValue=Layout:view=enum:requireEscapingSlashesInDefaultValue=boolean}
+
+

Parameters

+

Registry Options

+
    +
  • value - Registry value name. Since NLog 4.3 a Layout. Before String.
  • +
  • +

    key - Registry key. Required. Since NLog 4.3 a Layout. Before String. + Must have the form: hive/key/subkey/name + Possible hives: HKLM/HKEY_LOCAL_MACHINE/HKCU/HKEY_CURRENT_USER + Also possible since NLog 4.3: HKEY_CLASSES_ROOT/HKEY_USERS/HKEY_CURRENT_CONFIG/HKEY_DYN_DATA/HKEY_PERFORMANCE_DATA

    +
  • +
  • +

    defaultValue - Value to be output when the specified registry key or value is not found. Since NLog 4.3 a Layout. Before String.

    +
  • +
  • RequireEscapingSlashesInDefaultValue - Introduced in NLog 4.3 boolean. Require escaping backward slashes in DefaultValue. Need to be backwardscompatible. Default true. Will be removed in the future.
  • +
  • View - Introduced in NLog 4.3 . Registry32, Registry64, Default
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Reinitialize-NLog-configuration/index.html b/wiki/Reinitialize-NLog-configuration/index.html new file mode 100644 index 000000000..1ea8498fc --- /dev/null +++ b/wiki/Reinitialize-NLog-configuration/index.html @@ -0,0 +1,1337 @@ + + + + + + + + Reinitialize NLog configuration - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The combination of dynamic logging configuration and NLog-targets that only applies configuration during initialization can give a catch22. You want to have logging up and running early, but this will fail if NLog-targets initialization depends on configuration settings being available. This can lead to NLog-targets failing to initialize so NLog suddenly is disabled, or NLog-targets never using the configured destination.

+

GDC and whenEmpty

+

The recommended solution to this problem is to make use of GDC and whenEmpty:

+
<target xsi:type="ElasticSearch" uri="${gdc:item=targetUri:whenEmpty=http\://localhost}">
+
+

Then one can apply the dynamic configuration change like this:

+
NLog.GlobalDiagnosticsContext.Set("targetUri", "http://127.0.0.1:9200");
+NLog.LogManager.Configuration = NLog.LogManager.Configuration?.Reload();
+
+

Please note that Configuration.Reload() will cause all NLog-variables to be reset. This is why GDC is being used to store the dynamic configuration.

+

Re-initialize single target

+

The standard NLog targets supports reinitialization, but it is not always supported by 3rdParty NLog targets. This can happen if closing NLog-target performs dispose of members, that are only initialized in the constructor of the NLog-target.

+
var target = NLog.LogManager.Configuration?.FindTargetByName<BlobStorageTarget>("blob");
+target?.Dispose();   // Closes the target so it is uninitialized
+NLog.LogManager.ReconfigExistingLoggers(); // Ensures all targets are initialized
+
+

Knowing the name of the NLog-target can sometimes be a challenge, especially if the NLog-target is wrapped using AsyncWrapper or BufferingWrapper. One can also do this:

+
NLog.LogManager.Configuration?.AllTargets.OfType<BlobStorageTarget>().ToList().ForEach(t => t.Dispose());
+NLog.LogManager.ReconfigExistingLoggers(); // Ensures all targets are initialized
+
+

Re-initialize all targets

+

This is the big hammer, and might not be supported by all NLog-targets. This can happen if closing NLog-target performs dispose of members, that are only initialized in the constructor of the NLog-target.

+

NLog v5 has introduced this command:

+
NLog.LogManager.Setup().ReloadConfiguration();
+
+

If using NLog v4 then this will also work:

+
NLog.LogManager.Configuration = NLog.LogManager.Configuration;
+
+

Notice that LogEvents produced by the application can become lost, in the period where closing and initializing all NLog targets.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/RepeatingWrapper-target/index.html b/wiki/RepeatingWrapper-target/index.html new file mode 100644 index 000000000..6b6bf44ff --- /dev/null +++ b/wiki/RepeatingWrapper-target/index.html @@ -0,0 +1,1328 @@ + + + + + + + + RepeatingWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Repeats each log event the specified number of times.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="RepeatingWrapper" name="String" repeatCount="Integer">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Repeating Options

+
    +
  • repeatCount - Number of times to repeat each log message. Integer Default: 3
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Replace-Layout-Renderer/index.html b/wiki/Replace-Layout-Renderer/index.html new file mode 100644 index 000000000..52ded1eaf --- /dev/null +++ b/wiki/Replace-Layout-Renderer/index.html @@ -0,0 +1,1356 @@ + + + + + + + + Replace Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Replaces a string in the output of another layout with another string.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${replace:searchFor=String:wholeWords=Boolean:replaceWith=String
+         :ignoreCase=Boolean:inner=Layout}
+
+

Parameters

+

Search/Replace Options

+
    +
  • searchFor - Text to search for. String
  • +
  • replaceWith - Replacement string.
  • +
  • ignoreCase - Indicates whether to ignore case when searching. Boolean Default: False
  • +
  • wholeWords - Indicates whether to search for whole words. Boolean Default: False
  • +
+

Transformation Options

+
    +
  • inner - Wrapped layout. Layout
  • +
+

RegEx not supported

+

NLog v6 does not support Regular Expressions (RegEx), and have removed these options:

+
    +
  • regex - Indicates whether regular expressions should be used when searching. Boolean Default: False
  • +
  • replaceGroupName - Specifies group name for Matched Subexpressions, where it will perform replace of all matches with that group name. Ex. (?<groupname>subexpression)
    +

    Introduced with NLog 3.1

    +
    +
  • +
  • compileRegex - Compiles the Regex. Setting this to true can improve regex performance, but costs memory. Boolean Default: False
    +

    Introduced with NLog 4.7

    +
    +
  • +
+

If needing Regular Expressions, then one can use ${regex-replace} from NLog.RegEx-nuget-package.

+

RegEx Examples

+

Replace sensitive data, that starts with password= or password:

+
<variable name="replacePasswords"
+  value="${replace:inner=${message}:searchFor=(?i)(?&lt;=password[=\:])(.*?)(?=(\;|$| )):replaceWith=******:regex=true}" />
+
+

Truncate after token, search for , and replace everything after with empty string:

+
<variable name="truncateAfterComma"
+  value="${replace:inner=${aspnet-request-ip}:searchFor=,.*:replaceWith=:regex=true}" />
+
+

With Regular Expressions keep in mind the content escaping rules to escape special characters in Regex. Specifically } and \. So for example the regular expression (\d{3})+ would need to be escaped like so in your configuration

+
<variable name="messageNoDigits" 
+  value="${replace:inner=${message}:searchFor=(\\d{3\})+:replaceWith=:regex=true}" />
+
+

There is a dedicated layout ${replace-newlines} for replacing / removing newlines (handles both Unix and Windows newlines)

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Replace-NewLines-Layout-Renderer/index.html b/wiki/Replace-NewLines-Layout-Renderer/index.html new file mode 100644 index 000000000..b084079b0 --- /dev/null +++ b/wiki/Replace-NewLines-Layout-Renderer/index.html @@ -0,0 +1,1341 @@ + + + + + + + + Replace NewLines Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Replaces a new lines in the output of another layout with a string.

+
+

Platforms Supported: All

+

Introduced in NLog 4.1

+

For general purpose search and replace there is also ${replace}

+
+

Configuration Syntax

+

${replace-newlines:inner=Layout:replacement=String}

+

Parameters

+
    +
  • replacement - Text to replace newlines with. Default is " " (space)
  • +
+

Examples

+
logger.Info("foo {0}",  "bar" + System.Environment.NewLine + "123");
+
+

To space

+
${replace-newlines:${message}}
+
+

Will result in "foo bar 123"

+

To other char

+
${replace-newlines:replacement=|:${message}}
+
+

Will result in "foo bar|123"

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/RetryingWrapper-target/index.html b/wiki/RetryingWrapper-target/index.html new file mode 100644 index 000000000..63e171b8c --- /dev/null +++ b/wiki/RetryingWrapper-target/index.html @@ -0,0 +1,1344 @@ + + + + + + + + RetryingWrapper target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Retries in case of write error.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="RetryingWrapper" name="String" retryDelayMilliseconds="Integer" retryCount="Integer">
+    <target xsi:type="wrappedTargetType" ...target properties... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Retrying Options

+
    +
  • +

    retryDelayMilliseconds - Time to wait between retries in milliseconds. Integer Default: 100

    +
  • +
  • +

    retryCount - Number of retries that should be attempted on the wrapped target in case of a failure. Integer Default: 3

    +
  • +
  • +

    enableBatchWrite - Allow batch writes, and only introduced retry delay once before retrying the batch items one at a time.

    +
    +

    Introduced with NLog 5.0

    +
    +
  • +
+

Notes

+

When failure occurs, then the retry will perform a synchronous delay. To avoid blocking the application-thread in the retry-sleep, then consider using AsyncWrapper like this:

+
    +
  • AsyncWrapper -> RetryWrapper -> Actual Target
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/RichTextBox-target/index.html b/wiki/RichTextBox-target/index.html new file mode 100644 index 000000000..0b872598b --- /dev/null +++ b/wiki/RichTextBox-target/index.html @@ -0,0 +1,1307 @@ + + + + + + + + RichTextBox target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+ +
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Right-layout-renderer/index.html b/wiki/Right-layout-renderer/index.html new file mode 100644 index 000000000..e76ce9416 --- /dev/null +++ b/wiki/Right-layout-renderer/index.html @@ -0,0 +1,1332 @@ + + + + + + + + Right layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Right part of a text

+
+

Platforms Supported: All

+

Introduced in NLog 4.6

+
+

Related:

+ +

Configuration Syntax

+
${right:inner=Layout:length=Integer}
+
+

Read more about using the Configuration File.

+

Parameters

+

Transformation Options

+
    +
  • +

    inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout

    +
  • +
  • +

    length - Length in characters. Integer Required.

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Rot13-Layout-Renderer/index.html b/wiki/Rot13-Layout-Renderer/index.html new file mode 100644 index 000000000..3ed2e22a4 --- /dev/null +++ b/wiki/Rot13-Layout-Renderer/index.html @@ -0,0 +1,1328 @@ + + + + + + + + Rot13 Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Decodes text "encrypted" with ROT-13.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${rot13:inner=Layout:text=Layout}
+
+

Parameters

+

Transformation Options

+
    +
  • +

    inner - Wrapped layout. Layout

    +
  • +
  • +

    text - Layout to be wrapped. Layout
    +This variable is for backwards compatibility

    +
  • +
+

Remarks

+

See https://en.wikipedia.org/wiki/ROT13.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/RoundRobinGroup-target/index.html b/wiki/RoundRobinGroup-target/index.html new file mode 100644 index 000000000..d69e0a52b --- /dev/null +++ b/wiki/RoundRobinGroup-target/index.html @@ -0,0 +1,1327 @@ + + + + + + + + RoundRobinGroup target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Distributes log events to targets in a round-robin fashion.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="RoundRobinGroup" name="String">
+    <target xsi:type="wrappedTargetType" ... />
+    <target xsi:type="wrappedTargetType" ... />
+    ...
+    <target xsi:type="wrappedTargetType" ... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/SL-AppInfo-Layout-Renderer/index.html b/wiki/SL-AppInfo-Layout-Renderer/index.html new file mode 100644 index 000000000..03660cc80 --- /dev/null +++ b/wiki/SL-AppInfo-Layout-Renderer/index.html @@ -0,0 +1,1344 @@ + + + + + + + + SL AppInfo Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Information about Silverlight application.

+

Supported in Silverlight (Deprecated with NLog 5.0)

+

Configuration Syntax

+
${sl-appinfo:option=Enum}
+
+

Parameters

+

Rendering Options

+
    +
  • option - Specific information to display. Default: 0
    + Possible values:
  • +
  • +

    HasElevatedPermissions - Whether application is running with elevated permissions.

    +
    +

    This parameter is not supported in: +* NLog v2.0 for Silverlight 2.0 +* NLog v2.0 for Silverlight 3.0

    +
    +
  • +
  • +

    InstallState - Installed state of an application.

    +
    +

    This parameter is not supported in: +* NLog v2.0 for Silverlight 2.0

    +
    +
  • +
  • +

    IsOutOfBrowser - Whether application is running out-of-browser.

    +
    +

    This parameter is not supported in: +* NLog v2.0 for Silverlight 2.0

    +
    +
  • +
  • +

    XapUri - URI of the current application XAP file.

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ScopeIndent-Layout-Renderer/index.html b/wiki/ScopeIndent-Layout-Renderer/index.html new file mode 100644 index 000000000..157f19fdc --- /dev/null +++ b/wiki/ScopeIndent-Layout-Renderer/index.html @@ -0,0 +1,1339 @@ + + + + + + + + ScopeIndent Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ScopeContext Nested States are stored in the thread execution context. Similar to "Nested Diagnostic Context" (NDC) in Log4j.

+
+

Platforms Supported: All (AsyncLocal is used for NetStandard and Net46, but older platforms uses Remoting.Messaging.CallContext)

+

Introduced with NLog 5.0.5

+
+

Inserts indent-delimiter for every nested state in the ScopeContext.

+

Configuration Syntax

+
${scopeindent:indent=Layout}
+
+

Parameters

+
    +
  • indent - Delimiter to insert for every nested state level in ScopeContext. Layout. Default (double space)
  • +
+

Examples

+
Logger.Info("Hello No Scope");              // Will not be indented
+
+using (NLog.ScopeContext.PushNestedState("First Scope"))
+{
+   Logger.Info("Hello First Scope");        // Will be indented once
+   await InnerOperationAsync();
+}
+
+static async Task InnerOperationAsync()
+{
+    using (NLog.ScopeContext.PushNestedState("Second Scope"))
+    {
+        Logger.Info("Hello Second Scope");   // Will be indented twice
+        await Task.Yield();
+    }
+}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ScopeNested-Layout-Renderer/index.html b/wiki/ScopeNested-Layout-Renderer/index.html new file mode 100644 index 000000000..c15b5ca7f --- /dev/null +++ b/wiki/ScopeNested-Layout-Renderer/index.html @@ -0,0 +1,1359 @@ + + + + + + + + ScopeNested Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ScopeContext Nested States are stored in the thread execution context. Similar to "Nested Diagnostic Context" (NDC) in Log4j.

+
+

Platforms Supported: All (AsyncLocal is used for NetStandard and Net46, but older platforms uses Remoting.Messaging.CallContext)

+

Introduced with NLog 5.0 that merges ${MDC} + ${MDLC} + ${NDC} + ${NDLC} into an unified ScopeContext.

+
+

It enables one to assign a scope-name to the active scope (Ex. a request method-name). Then all logger-events created within the scoped logical context, can automatically capture the scope-name without needing to specify it with each LogEvent. The specified scope states will automatically flow together with async Tasks.

+

See also NLog Context and ${scopeproperty} and ${scopetiming} and ${scopeindent}

+

Configuration Syntax

+
${scopenested:bottomFrames=Integer:topFrames=Integer:separator=String}
+
+

Parameters

+
    +
  • bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer. Default -1.
  • +
  • topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer. Default -1
  • +
  • separator - Separator to be used for concatenating nested diagnostics context output. string. Default (space)
  • +
  • format - Format string for conversion into string. Possible to use @ for Json-Array.
  • +
  • culture - Format provider for conversion into string.
  • +
+

Examples

+
using (NLog.ScopeContext.PushNestedState("Outer Scope"))
+{
+   Logger.Info("Hello Outer");
+   await InnerOperationAsync();
+}
+
+static async Task InnerOperationAsync()
+{
+    using (NLog.ScopeContext.PushNestedState("Inner Scope"))
+    {
+        Logger.Info("Hello Inner");
+        await Task.Yield();
+    }
+}
+
+

The NLog Logger can also be used to update ScopeContext:

+
var logger = NLog.LogManager.GetCurrentClassLogger();
+using (logger.PushScopeNested("Outer Scope"))
+{
+}
+
+

.NET Core logging

+

When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options:

+
using (_logger.BeginScope("Outer Scope"))
+{
+   _logger.LogDebug("Start process {ProccessName}, "Main");
+}
+
+

Indenting Log Messages

+

Indent log-messages based on how many nested levels in ScopeContext using ${scopeindent}

+
${scopeindent}${message}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ScopeProperty-Layout-Renderer/index.html b/wiki/ScopeProperty-Layout-Renderer/index.html new file mode 100644 index 000000000..a673be226 --- /dev/null +++ b/wiki/ScopeProperty-Layout-Renderer/index.html @@ -0,0 +1,1355 @@ + + + + + + + + ScopeProperty Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ScopeContext Properties are stored in the thread execution context. Similar to "Mapped Diagnostic Context" (MDC) in Log4j.

+
+

Platforms Supported: All (AsyncLocal is used for NetStandard and Net46, but older platforms uses Remoting.Messaging.CallContext)

+

Introduced with NLog 5.0 that merges ${MDC} + ${MDLC} + ${NDC} + ${NDLC} into an unified ScopeContext.

+
+

It enables one to assign one or more named properties to the active scope (Ex. a request CorrelationId). Then all logger-events created within the scoped logical context, can automatically include the scope-properties in the ouput without specifying with each LogEvent. The specified scope properties will automatically flow together with async Tasks.

+

See also NLog Context and ${scopenested} and ${scopetiming} and ${all-event-properties:includeScopeProperties=true}

+

Configuration Syntax

+
${scopeproperty:item=String}
+
+

Parameters

+
    +
  • item - Name of the item. Lookup is case-insensitive. Required.
  • +
  • format - Format string for conversion into string. Possible to use @ for Json.
  • +
  • culture - Format provider for conversion into string.
  • +
+

Example

+
using (NLog.ScopeContext.PushProperty("PropertyName", "PropertyValue")) 
+{
+    Logger.Info("Hello World"); // LogEvent can use ${scopeproperty:PropertyName} in target output
+}
+// "PropertyName" items has been removed from current context
+
+

The NLog Logger can also be used for updating the ScopeContext:

+
var logger = NLog.LogManager.GetCurrentClassLogger();
+using (logger.PushScopeProperty("PropertyName", "PropertyValue")) 
+{
+    logger.Info("Hello World"); // LogEvent can use ${scopeproperty:PropertyName} in target output
+}
+
+

.NET Core logging

+

When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options:

+
using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("userid", request.UserId) }))
+{
+   _logger.LogDebug("Hello {World}", "Earth"); // Render userId via ${scopeproperty:userid} in target output
+}
+
+

NLog.Extensions.Logging v5.3.7 adds support for using ValueTuple for single scope-property (better performance):

+
using (_logger.BeginScope(("userid", request.UserId)))
+{
+   _logger.LogDebug("Hello {World}", "Earth"); // Render userId via ${scopeproperty:userid} in target output
+}
+
+

Fallback to default value

+

When ScopeContext Property cannot be found (or has blank value), then one use whenEmpty to specify fallback value:

+
${scope-property:UserId:whenEmpty=42}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ScopeTiming-Layout-Renderer/index.html b/wiki/ScopeTiming-Layout-Renderer/index.html new file mode 100644 index 000000000..f3a978164 --- /dev/null +++ b/wiki/ScopeTiming-Layout-Renderer/index.html @@ -0,0 +1,1324 @@ + + + + + + + + ScopeTiming Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

ScopeContext allows one to give a scope name for an operation that can be async. When the scope begins then it automatically captures a timestamp. This can be used to show duration of the active scope.

+
+

Platforms Supported: All

+

Introduced in NLog 5.0 and replaces ${ndlctiming}

+
+

See also NLog Context and ${scopeproperty} and ${scopenested}

+

Configuration Syntax

+
${scopetiming:currentScope=Boolean:StartTime=Boolean:format=String}
+
+

Parameters

+

Rendering Options

+
    +
  • currentScope - Whether to only include the duration of the last scope created. Boolean. Default False.
  • +
  • StartTime - Whether to just display the scope creation time, and not the duration. Boolean. Default False
  • +
  • format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format). string. Default null
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/SequenceId-layout-renderer/index.html b/wiki/SequenceId-layout-renderer/index.html new file mode 100644 index 000000000..6757f76bd --- /dev/null +++ b/wiki/SequenceId-layout-renderer/index.html @@ -0,0 +1,1317 @@ + + + + + + + + SequenceId layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The log sequence id (Reset to zero on application restart)

+
+

Platforms Supported: All

+

Introduced in NLog v4.5

+
+

Alternative use ${counter:sequence=global} or ${guid:GeneratedFromLogEvent=true}

+

Configuration syntax

+
${sequenceid}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ShortDate-Layout-Renderer/index.html b/wiki/ShortDate-Layout-Renderer/index.html new file mode 100644 index 000000000..39add95a6 --- /dev/null +++ b/wiki/ShortDate-Layout-Renderer/index.html @@ -0,0 +1,1321 @@ + + + + + + + + ShortDate Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The short date in a sortable format yyyy-MM-dd.

+
+

Platforms Supported: All

+

Alternative ${date:format=yyyy_MM_dd} can be used to customize the DateTime-format.

+
+

Configuration Syntax

+
${shortdate:universalTime=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • universalTime - Indicates whether to output UTC time instead of local time. Boolean Default: False
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/SimpleLayout/index.html b/wiki/SimpleLayout/index.html new file mode 100644 index 000000000..7fd43ee5f --- /dev/null +++ b/wiki/SimpleLayout/index.html @@ -0,0 +1,1339 @@ + + + + + + + + SimpleLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Represents a string with embedded placeholders that can render contextual information from the LogEvent.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+

SimpleLayout is used by default when nothing specified, so one can just write:

+
<targets>
+  <target layout="Hello ${message}" />
+</targets>
+
+

But one can explictly specify the SimpleLayout-type like this:

+
<targets>
+  <target>
+    <layout xsi:type="SimpleLayout" text="Hello ${message}" />
+  </target>
+</targets>
+
+

Parameters

+

Layout Options

+
    +
  • text - Layout text
  • +
+

Remarks

+

The layout is not meant to be built explicitly from code, instead assign a string, e.g. Layout l = "${longdate}|${level}|${logger}|${message}"

+

The layout can be literal text like "Hello", but can also contain Layout-Renderers like ${message}. See also: List of Layout-Renderers

+

Many NLog Targets has their Layout-option configured to this default-value:

+
+

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

+
+

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}

+

There also exists Layout-types for more structured output-formats like JSON, XML, CSV, etc. See also: List of Layouts

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Special-Folder-Layout-Renderer/index.html b/wiki/Special-Folder-Layout-Renderer/index.html new file mode 100644 index 000000000..98c987bac --- /dev/null +++ b/wiki/Special-Folder-Layout-Renderer/index.html @@ -0,0 +1,1431 @@ + + + + + + + + Special Folder Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

System special folder path (includes My Documents, My Music, Program Files, Desktop, and more).

+
+

Platforms Supported: All

+

See also ${processdir} , ${basedir} , ${currentdir} , ${tempdir}

+
+

Configuration Syntax

+
${specialfolder:dir=String:file=String:folder=Enum}
+
+

Example using CommonApplicationData which is good when running as Windows Service:

+
    +
  • fileName="${specialfolder:folder=CommonApplicationData:cached=true}/AppName/logfile.txt"
  • +
  • Windows-Path - C:/ProgramData/AppName/logfile.txt
  • +
+

Parameters

+

Advanced Options

+
    +
  • dir - Name of the directory to be Path.Combine()'d with the directory name.
  • +
  • file - Name of the file to be Path.Combine()'d with the directory name.
  • +
+

Rendering Options

+
    +
  • +

    folder - System special folder to use. Full list of options is available at MSDN. The most common ones are:

    +
  • +
  • +

    ApplicationData - Roaming application data for current user

    +
      +
    • Windows Path = C:\Users\%USERNAME%\AppData\Roaming
    • +
    • Xamarin Mono = $HOME/.config (or $XDG_CONFIG_HOME if set)
    • +
    • Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/.config
    • +
    • Xamarin Android = /data/data/@PACKAGE_NAME@/files/.config
    • +
    +
  • +
  • LocalApplicationData - Non roaming application data for current user
      +
    • Windows Path = C:\Users\%USERNAME%\AppData\Local
    • +
    • Xamarin Mono = $HOME/.local/share (or $XDG_DATA_HOME if set)
    • +
    • Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents
    • +
    • Xamarin Android = /data/data/@PACKAGE_NAME@/files/.local/share
    • +
    +
  • +
  • CommonApplicationData - Application data for all users (Good when running as Windows Service)
      +
    • Windows Path = C:\ProgramData
    • +
    • Xamarin Mono = /usr/share
    • +
    • Xamarin iOS = /usr/share
    • +
    • Xamarin Android = /usr/share
    • +
    +
  • +
  • MyDocuments - My Documents
      +
    • Windows Path = C:\Users\%USERNAME%\Documents
    • +
    • Xamarin Mono = $HOME
    • +
    • Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents
    • +
    • Xamarin Android = /data/data/@PACKAGE_NAME@/files
    • +
    +
  • +
  • Desktop - My Desktop
      +
    • Windows Path = C:\Users\%USERNAME%\Desktop
    • +
    • Xamarin Mono = $HOME/Desktop (or $XDG_DESKTOP_DIR if set)
    • +
    • Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/Desktop
    • +
    • Xamarin Android = /data/data/@PACKAGE_NAME@/files/Desktop
    • +
    +
  • +
  • UserProfile
      +
    • Windows Path = C:\Users\%USERNAME%
    • +
    • Xamarin Mono = $HOME
    • +
    • Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@
    • +
    • Xamarin Android = /data/data/@PACKAGE_NAME@/files
    • +
    +
  • +
  • Templates
      +
    • Windows Path = C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Templates
    • +
    • Xamarin Mono = $HOME/Templates (or $XDG_TEMPLATES_DIR if set)
    • +
    • Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/Templates
    • +
    • Xamarin Android = /data/data/@PACKAGE_NAME@/files/Templates
    • +
    +
  • +
  • CommonTemplates
      +
    • Windows Path = C:\ProgramData\Microsoft\Windows\Templates
    • +
    • Xamarin Mono = /usr/share/templates
    • +
    • Xamarin iOS = /usr/share/templates
    • +
    • Xamarin Android = /usr/share/templates
    • +
    +
  • +
  • Resources
      +
    • Windows Path = C:\WINDOWS\resources
    • +
    • Xamarin iOS = /Library
    • +
    +
  • +
  • AdminTools
  • +
  • CommonAdminTools
  • +
  • CommonDesktopDirectory
  • +
  • CommonDocuments
  • +
  • CommonMusic
  • +
  • CommonPictures
  • +
  • CommonProgramFiles
  • +
  • CommonProgramFilesX86
  • +
  • CommonPrograms
  • +
  • CommonStartMenu
  • +
  • CommonStartup
  • +
  • CommonVideos
  • +
  • Cookies
  • +
  • DesktopDirectory (Same as Desktop)
  • +
  • Favorites
  • +
  • Fonts
  • +
  • History
  • +
  • LocalizedResources
  • +
  • MyComputer
  • +
  • MyMusic
  • +
  • MyPictures
  • +
  • MyVideos
  • +
  • NetworkShortcuts
  • +
  • Personal (Same as MyDocuments)
  • +
  • PrinterShortcuts
  • +
  • ProgramFiles
  • +
  • ProgramFilesX86
  • +
  • Programs
  • +
  • Recent
  • +
  • SendTo
  • +
  • StartMenu
  • +
  • Startup
  • +
  • System
  • +
  • SystemX86
  • +
  • Windows
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/SplitGroup-target/index.html b/wiki/SplitGroup-target/index.html new file mode 100644 index 000000000..5b4ab3ec0 --- /dev/null +++ b/wiki/SplitGroup-target/index.html @@ -0,0 +1,1328 @@ + + + + + + + + SplitGroup target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Writes log events to all wrapped targets.

+
+

Platforms Supported: All

+
+

ℹ️ For better performance, specify targets directly on the logging rule, optionally using NLog variables.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="SplitGroup" name="String">
+    <target xsi:type="wrappedTargetType" ... />
+    <target xsi:type="wrappedTargetType" ... />
+    ...
+    <target xsi:type="wrappedTargetType" ... />
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Splunk-Target/index.html b/wiki/Splunk-Target/index.html new file mode 100644 index 000000000..8e9cf1cb3 --- /dev/null +++ b/wiki/Splunk-Target/index.html @@ -0,0 +1,1487 @@ + + + + + + + + Splunk Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to the remote instance of Splunk Server using Splunk JSON-format using TCP / UDP.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network

+
+

This target inherits from the Network Target, and so it has also all the properties of the Network Target available. Using the SplunkLayout to produce Splunk JSON-format.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Splunk"
+          name="String"
+          address="Layout">
+    <splunkField name="String" layout="Layout" /><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Payload Options

+
    +
  • +

    layout - Instance of GelfLayout that is used to format log messages. Layout Default: GelfLayout

    +
  • +
  • +

    SplunkHostName - Splunk Message Host-field. Default = ${hostname}

    +
  • +
  • +

    SplunkSourceName - Splunk Message Source-field. Default = ${processname}

    +
  • +
  • +

    SplunkSourceType - Splunk Message SourceType-field. Default = null

    +
  • +
  • +

    SplunkIndex - Splunk Message Index-field. Default = null

    +
  • +
  • +

    IncludeEventProperties - Include all properties from the log events. Default = true.

    +
  • +
  • +

    IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false.

    +
  • +
  • +

    ExcludeEmptyProperties - Exclude null/empty properties. Default = false.

    +
  • +
  • +

    ExcludeProperties - Comma separated string with names which properties to exclude.

    +
  • +
  • +

    SplunkField

    +
  • +
  • name - Required. The name of the JSON-key
  • +
  • +

    layout - The layout for the JSON-value (Can be a nested JsonLayout)

    +
  • +
  • +

    encoding - Encoding to be used. Encoding Default: utf-8

    +
  • +
  • +

    newLine - Indicates whether to append newline at the end of log message. Boolean Default: False

    +
  • +
  • +

    lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF. Not used if newLine is false. +Possible values:

    +
  • +
  • CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default)
  • +
  • CR - Carriage Return (ASCII 13).
  • +
  • LF - Line Feed (ASCII 10).
  • +
  • NULL - Null terminator (ASCII 0)
  • +
  • +

    None - No end of line characters.

    +
  • +
  • +

    maxMessageSize - Maximum message size in bytes. Integer Default: 65000

    +
  • +
  • +

    onOverflow - Action that should be taken if the message-size is larger than maxMessageSize. +Possible values:

    +
  • +
  • Discard - Discard the entire message.
  • +
  • Error - Report an error.
  • +
  • Split - Split the message into smaller pieces (Default)
  • +
+

Connection Options

+
    +
  • address - Network address. Layout +The network address can be:
  • +
  • tcp://host:port - TCP (auto select IPv4/IPv6)
  • +
  • tcp4://host:port - force TCP/IPv4
  • +
  • tcp6://host:port - force TCP/IPv6
  • +
  • udp://host:port - UDP (auto select IPv4/IPv6)
  • +
  • udp4://host:port - force UDP/IPv4
  • +
  • udp6://host:port - force UDP/IPv6
  • +
  • http://host:port/pageName - HTTP using POST verb
  • +
  • +

    https://host:port/pageName - HTTPS using POST verb

    +
  • +
  • +

    keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True

    +
  • +
  • +

    connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5

    +
  • +
  • +

    maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16. Not used if keepConnection is true.

    +
  • +
  • +

    onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections.

    +
  • +
+

Possible enum values: + * Discard - Discard new messages when reaching limit (Default) + * Grow - Send message and ignore limit + * Block - Block until pending connections has been freed.

+
    +
  • +

    maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer. Default: 10000

    +
  • +
  • +

    onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize.

    +
  • +
  • Discard - Discard the entire message (Default)
  • +
  • Grow - Ignore limit and grow the queue.
  • +
  • +

    Block - Block until queue is below limit.

    +
  • +
  • +

    KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true.

    +
  • +
  • +

    sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. + Possible values (combination allowed, comma separated):

    +
  • +
  • None - No SSL/TLS is used
  • +
  • Default - Accepts Tls or Ssl3
  • +
  • Ssl2 - really not recommended
  • +
  • Ssl3 - not recommended
  • +
  • Tls - TLS 1.0
  • +
  • Tls11 - TLS 1.1
  • +
  • +

    Tls12 - TLS 1.2

    +
  • +
  • +

    SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation)

    +
  • +
  • +

    SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile

    +
  • +
  • +

    SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine)

    +
    +

    Introduced in NLog.Targets.Network v6.1.6

    +
    +
  • +
+

Example

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <extensions>
+    <add assembly="NLog.Targets.Network"/>
+  </extensions>
+
+  <targets>
+    <target name="splunk" xsi:type="splunk" address="http://localhost:12201/gelf" />
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="splunk" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/SplunkLayout/index.html b/wiki/SplunkLayout/index.html new file mode 100644 index 000000000..a80bbcdb8 --- /dev/null +++ b/wiki/SplunkLayout/index.html @@ -0,0 +1,1355 @@ + + + + + + + + SplunkLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders each log event as the Splunk JSON format expected by the Splunk HTTP Event Collector (HEC).

+

SplunkLayout renders the complete HEC event, including the outer time, host, source, sourcetype, index, and nested event fields.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network

+
+
<target name="jsonFile" xsi:type="File" fileName="splunk-file.json" >
+      <layout xsi:type="SplunkLayout" includeEventProperties="Boolean" excludeProperties="Comma-separated list (string)">
+            <SplunkField name="threadid" layout="${threadid}" />
+            <SplunkField name="messagetemplate" layout="${message:raw=true}" />  
+       </layout>
+</target>
+
+

Layout Options

+
    +
  • +

    SplunkHostName - Splunk Message Host-field. Default = ${hostname}

    +
  • +
  • +

    SplunkSourceName - Splunk Message Source-field. Default = ${processname}

    +
  • +
  • +

    SplunkSourceType - Splunk Message SourceType-field. Use _json to enable automatic extraction of fields from the JSON event object. Default = _json

    +
  • +
  • +

    SplunkIndex - Splunk Message Index-field. The HEC token must have write-access to this index. No value means using HEC token's default index. Default = null

    +
  • +
  • +

    IncludeEventProperties - Include all properties from the log events. Default = true.

    +
  • +
  • +

    IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false.

    +
  • +
  • +

    ExcludeEmptyProperties - Exclude null/empty properties. Default = false.

    +
  • +
  • +

    ExcludeProperties - Comma separated string with names which properties to exclude.

    +
  • +
  • +

    SplunkField

    +
  • +
  • name - Required. The name of the JSON-key
  • +
  • layout - The layout for the JSON-value (Can be a nested JsonLayout)
  • +
+

Splunk HTTP Event Collector (HEC)

+

SplunkLayout can be used with an HTTP target to send events to the Splunk HEC /services/collector/event endpoint using newline-delimited JSON (NDJSON).

+

The HTTP target must provide the following HTTP header: Authorization: Splunk <hec-token>

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Stack-Trace-Layout-Renderer/index.html b/wiki/Stack-Trace-Layout-Renderer/index.html new file mode 100644 index 000000000..703c1787f --- /dev/null +++ b/wiki/Stack-Trace-Layout-Renderer/index.html @@ -0,0 +1,1353 @@ + + + + + + + + Stack Trace Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render Stack trace of a log event.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${stacktrace:format=Enum:topFrames=Integer:skipFrames=Integer:separator=String}
+
+

Parameters

+

Rendering Options

+
    +
  • format - Output format of the stack trace. Default: Flat
    + Possible values:
  • +
  • DetailedFlat - Detailed flat format (method signatures displayed in a single line).
  • +
  • Flat - Flat format (class and method names displayed in a single line).
  • +
  • Raw - Raw format (multiline - as returned by StackFrame.ToString() method).
  • +
  • topFrames - Number of top stack frames to be rendered. Integer Default: 3
  • +
  • skipFrames - Numberof frames to skip. Integer Default: 0
  • +
  • separator - Stack frame separator string. Default: =>. To set new line use &#13;&#10;
  • +
  • captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true
    +

    Introduced with NLog 4.7.1

    +
    +
  • +
  • reverse - Whether to output the stacktrace in reverse order. Default: false
    +

    Introduced with NLog 5.0

    +
    +
  • +
+

Examples

+

Raw

+

Note: To get the filenames and line numbers, include the PDB files.

+

Note: Prior NLog 4.4.7, the result was always <filename unknown>:0:0

+
Main at offset 638 in file:line:column file1.cs:100:10  
+TestLogging at offset 590 in file:line:column testlogger.cs:30:10  
+WriteToLog at offset 112 in file:line:column testlogger.cs:10:20
+
+

Flat

+
Program.Main  
+Program.TestLogging  
+NLogLoggerHelper.LogEvent
+
+

DetailedFlat

+
[Int32 Main()]  
+[Void TestLogging()]  
+[Void WriteToLog(NLog.Logger, NLog.LogLevel, System.String)]
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Substring-layout-renderer/index.html b/wiki/Substring-layout-renderer/index.html new file mode 100644 index 000000000..301bee8d4 --- /dev/null +++ b/wiki/Substring-layout-renderer/index.html @@ -0,0 +1,1335 @@ + + + + + + + + Substring layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Substring the result

+
+

Platforms Supported: All

+

Introduced in NLog 4.6

+
+

Related:

+ +

Configuration Syntax

+
${substring:inner=Layout:length=Integer:start=Integer}
+
+

Read more about using the Configuration File.

+

Parameters

+

Transformation Options

+
    +
  • +

    inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout

    +
  • +
  • +

    length - Length in characters. If null, then the whole string Integer. Default: null

    +
  • +
  • +

    start - Start index. Integer Default: 0

    +
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Syslog-Target/index.html b/wiki/Syslog-Target/index.html new file mode 100644 index 000000000..bf0c6ee19 --- /dev/null +++ b/wiki/Syslog-Target/index.html @@ -0,0 +1,1514 @@ + + + + + + + + Syslog Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages to the remote instance of Syslog Server.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network

+
+

This target inherits from the Network Target, and so it has also all the properties of the Network Target available. Using the SyslogLayout to produce Syslog output.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="Syslog"
+          name="String"
+          address="Layout">
+            <Rfc5424>true</Rfc5424>
+            <Rfc3164>false</Rfc3164>
+            <StructuredDataParam name="String" layout="Layout" /><!-- repeated -->
+  </target>
+</targets>
+
+

Read more about using the Configuration File.

+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Payload Options

+
    +
  • +

    layout - Instance of SyslogLayout that is used to format log messages. Layout Default: SyslogLayout

    +
  • +
  • +

    Rfc5424 - Rfc5424 as Syslog Format. Default = true.

    +
  • +
  • +

    Rfc3164 - Rfc3164 as Syslog Format. Default = false.

    +
  • +
  • +

    SyslogHostName - Hostname of the sender machine. Default = ${hostname}

    +
  • +
  • +

    SyslogAppName - Name of the device / application / process sending the Syslog-message. Default = ${processname}

    +
  • +
  • +

    SyslogProcessId - Process Id or Process Name or Logger Name. Default = ${processid}

    +
  • +
  • +

    SyslogMessage - Syslog Message Payload. Default = ${message}${onexception:|}${exception:format=shortType,message}.

    +
  • +
  • +

    SyslogMessageId - EventId to recognize the Syslog Message Type.

    +
  • +
  • +

    SyslogLevel - Syslog Level Mapping. Default automatically converts from NLog LogLevel.

    +
  • +
  • +

    SyslogFacility - Syslog Device Facility. Default = User

    +
  • +
  • +

    SyslogTimestamp - Syslog DateTime Format when Rfc5424. Default = ${date:format=o}

    +
  • +
  • +

    IncludeEventProperties - Include all properties from the log events when Rfc5424. Default = true.

    +
  • +
  • +

    ExcludeEmptyProperties - Exclude event properties with value null or empty when Rfc5424. Default = false.

    +
    +

    Introduced with NLog.Targets.Network v6.1.6

    +
    +
  • +
  • +

    ExcludeProperties - Comma separated string with names which properties to exclude when Rfc5424. Case insensitive. Default empty.

    +
    +

    Introduced with NLog.Targets.Network v6.1.6

    +
    +
  • +
  • +

    StructuredDataId - Prefix for StructuredData when Rfc5424. Default = meta

    +
  • +
  • +

    StructuredDataParam

    +
  • +
  • name - Structured property-name when Rfc5424
  • +
  • +

    layout - Structured property-value layout

    +
  • +
  • +

    newLine - Indicates whether to append newline at the end of log message. Boolean Default: False

    +
  • +
  • +

    lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF. Not used if newLine is false. +Possible values:

    +
  • +
  • CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default)
  • +
  • CR - Carriage Return (ASCII 13).
  • +
  • LF - Line Feed (ASCII 10).
  • +
  • NULL - Null terminator (ASCII 0)
  • +
  • +

    None - No end of line characters.

    +
  • +
  • +

    maxMessageSize - Maximum message size in bytes. Integer Default: 65000

    +
  • +
  • +

    onOverflow - Action that should be taken if the message-size is larger than maxMessageSize. +Possible values:

    +
  • +
  • Discard - Discard the entire message.
  • +
  • Error - Report an error.
  • +
  • Split - Split the message into smaller pieces (Default)
  • +
+

Connection Options

+
    +
  • address - Network address. Layout +The network address can be:
  • +
  • tcp://host:port - TCP (auto select IPv4/IPv6)
  • +
  • tcp4://host:port - force TCP/IPv4
  • +
  • tcp6://host:port - force TCP/IPv6
  • +
  • udp://host:port - UDP (auto select IPv4/IPv6)
  • +
  • udp4://host:port - force UDP/IPv4
  • +
  • udp6://host:port - force UDP/IPv6
  • +
  • http://host:port/pageName - HTTP using POST verb
  • +
  • +

    https://host:port/pageName - HTTPS using POST verb

    +
  • +
  • +

    keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True

    +
  • +
  • +

    connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5

    +
  • +
  • +

    maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16. Not used if keepConnection is true.

    +
  • +
  • +

    onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections.

    +
  • +
+

Possible enum values: + * Discard - Discard new messages when reaching limit (Default) + * Grow - Send message and ignore limit + * Block - Block until pending connections has been freed.

+
    +
  • +

    maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer. Default: 10000

    +
  • +
  • +

    onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize.

    +
  • +
  • Discard - Discard the entire message (Default)
  • +
  • Grow - Ignore limit and grow the queue.
  • +
  • +

    Block - Block until queue is below limit.

    +
  • +
  • +

    KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer. Default: 0 (Disabled)

    +
  • +
  • +

    NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true.

    +
  • +
  • +

    sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. + Possible values (combination allowed, comma separated):

    +
  • +
  • None - No SSL/TLS is used
  • +
  • Default - Accepts Tls or Ssl3
  • +
  • Ssl2 - really not recommended
  • +
  • Ssl3 - not recommended
  • +
  • Tls - TLS 1.0
  • +
  • Tls11 - TLS 1.1
  • +
  • +

    Tls12 - TLS 1.2

    +
  • +
  • +

    SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation)

    +
  • +
  • +

    SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile

    +
  • +
  • +

    SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine)

    +
    +

    Introduced in NLog.Targets.Network v6.1.6

    +
    +
  • +
+

Example

+
<?xml version="1.0" encoding="utf-8"?>
+<nlog throwConfigExceptions="true">
+
+  <extensions>
+    <add assembly="NLog.Targets.Network"/>
+  </extensions>
+
+  <targets>
+    <target xsi:type="SysLog" name="SyslogTcp" address="tcp://localhost:514">
+      <Rfc5424>true</Rfc5424>
+      <Rfc3164>false</Rfc3164>
+      <StructuredDataParam name="ThreadId" layout="${ThreadId}" />
+    </target>
+  </targets>
+
+  <rules>
+    <logger name="*" minlevel="Trace" writeTo="SyslogTcp" />
+  </rules>
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/SyslogLayout/index.html b/wiki/SyslogLayout/index.html new file mode 100644 index 000000000..0d9483d44 --- /dev/null +++ b/wiki/SyslogLayout/index.html @@ -0,0 +1,1376 @@ + + + + + + + + SyslogLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders to Syslog Server Format.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Network

+
+
<target name="syslogFile" xsi:type="File" fileName="syslog-file.txt" >
+      <layout xsi:type="SyslogLayout" includeEventProperties="Boolean" excludeProperties="Comma-separated list (string)">
+            <Rfc3164>false</Rfc3164>
+            <Rfc5424>true</Rfc5424>
+            <StructuredDataParam name="String" layout="Layout" /><!-- repeated -->
+       </layout>
+</target>
+
+

Layout Options

+
    +
  • +

    Rfc5424 - Rfc5424 as Syslog Format. Default = true.

    +
  • +
  • +

    Rfc3164 - Rfc3164 as Syslog Format. Default = false.

    +
  • +
  • +

    SyslogHostName - Hostname of the sender machine. Default = ${hostname}

    +
  • +
  • +

    SyslogAppName - Name of the device / application / process sending the Syslog-message. Default = ${processname}

    +
  • +
  • +

    SyslogProcessId - Process Id or Process Name or Logger Name. Default = ${processid}

    +
  • +
  • +

    SyslogMessage - Syslog Message Payload. Default = ${message}${onexception:|}${exception:format=shortType,message}.

    +
  • +
  • +

    SyslogMessageId - EventId to recognize the Syslog Message Type.

    +
  • +
  • +

    SyslogLevel - Syslog Level Mapping.

    +
  • +
  • +

    SyslogFacility - Syslog Device Facility. Default = User

    +
  • +
  • +

    SyslogTimestamp - Syslog DateTime Format when Rfc5424. Default = ${date:format=o}

    +
  • +
  • +

    IncludeEventProperties - Include all properties from the log events when Rfc5424. Default = true.

    +
  • +
  • +

    ExcludeEmptyProperties - Exclude event properties with value null or empty when Rfc5424. Default = false.

    +
    +

    Introduced with NLog.Targets.Network v6.1.6

    +
    +
  • +
  • +

    ExcludeProperties - Comma separated string with names which properties to exclude when Rfc5424. Case insensitive. Default empty.

    +
    +

    Introduced with NLog.Targets.Network v6.1.6

    +
    +
  • +
  • +

    StructuredDataId - Prefix for StructuredData when Rfc5424. Default = meta

    +
  • +
  • +

    StructuredDataParam

    +
  • +
  • name - Structured property-name when Rfc5424
  • +
  • layout - Structured property-value layout
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Targets-and-Wrappers/index.html b/wiki/Targets-and-Wrappers/index.html new file mode 100644 index 000000000..98cfa79e0 --- /dev/null +++ b/wiki/Targets-and-Wrappers/index.html @@ -0,0 +1,1307 @@ + + + + + + + + Targets and Wrappers - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Moved to Targets

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Targets/index.html b/wiki/Targets/index.html new file mode 100644 index 000000000..0150cfd1f --- /dev/null +++ b/wiki/Targets/index.html @@ -0,0 +1,1317 @@ + + + + + + + + Targets - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Use

+

Targets are used to display, store, or pass log messages to another destination. There are two kinds of target: + 1. Targets that writes the LogEvents + 2. 'Wrapper' Targets that apply additional logic when writing to wrapped Target. Logic can be filtering / batching / retry-on-error / etc.

+

Available Targets

+

List of NLog targets can found here: https://nlog-project.org/config/?tab=targets

+

Nuget Packages from NLog

+

Writing your own target

+

NLog can be extended with custom new targets. For more information, see: Extending-NLog

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/TempDir-Layout-Renderer/index.html b/wiki/TempDir-Layout-Renderer/index.html new file mode 100644 index 000000000..4f3719b5b --- /dev/null +++ b/wiki/TempDir-Layout-Renderer/index.html @@ -0,0 +1,1322 @@ + + + + + + + + TempDir Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The temporary directory on the local machine.

+
+

Platforms Supported: All

+

See also ${basedir}, ${processdir}, ${specialfolder}, ${currentdir}

+
+

Configuration Syntax

+
${tempdir:dir=String:file=String}
+
+

Parameters

+

Advanced Options

+
    +
  • dir - Name of the directory to be Path.Combine()'d with the directory name.
  • +
  • file - Name of the file to be Path.Combine()'d with the directory name.
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/TextLayout/index.html b/wiki/TextLayout/index.html new file mode 100644 index 000000000..ca586d326 --- /dev/null +++ b/wiki/TextLayout/index.html @@ -0,0 +1,1307 @@ + + + + + + + + TextLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Page moved here: https://github.com/NLog/NLog/wiki/SimpleLayout

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ThreadId-Layout-Renderer/index.html b/wiki/ThreadId-Layout-Renderer/index.html new file mode 100644 index 000000000..70644d92f --- /dev/null +++ b/wiki/ThreadId-Layout-Renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + ThreadId Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The identifier of the current thread.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${threadid}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/ThreadName-Layout-Renderer/index.html b/wiki/ThreadName-Layout-Renderer/index.html new file mode 100644 index 000000000..d1b254f1b --- /dev/null +++ b/wiki/ThreadName-Layout-Renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + ThreadName Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The name of the current thread.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${threadname}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Ticks-Layout-Renderer/index.html b/wiki/Ticks-Layout-Renderer/index.html new file mode 100644 index 000000000..09886b5f9 --- /dev/null +++ b/wiki/Ticks-Layout-Renderer/index.html @@ -0,0 +1,1315 @@ + + + + + + + + Ticks Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The Ticks value of current date and time.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${ticks}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Time-Layout-Renderer/index.html b/wiki/Time-Layout-Renderer/index.html new file mode 100644 index 000000000..846bb7ce9 --- /dev/null +++ b/wiki/Time-Layout-Renderer/index.html @@ -0,0 +1,1331 @@ + + + + + + + + Time Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

The time in a 24-hour, sortable format HH:mm:ss.ffff.

+
+

Platforms Supported: All

+

See also ${processtime}, ${date}, ${longdate}, ${shortdate}

+
+

Configuration Syntax

+
${time:universalTime=Boolean:invariant=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • universalTime - Indicates whether to output UTC time instead of local time. Boolean Default: False
  • +
  • invariant - Indicates whether to output in invariant time format, and not lookup of current cultureinfo. Boolean Default: true (Before NLog 5.0 the default was false)
    +

    Introduced with NLog 4.5.2

    +
    +
  • +
  • culture - Culture used for time format. Default: InvariantCulture
    +

    Introduced with NLog 5.0

    +
    +
  • +
+

Time Source Precision

+

NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount. For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Time-Source/index.html b/wiki/Time-Source/index.html new file mode 100644 index 000000000..1d25f5d0b --- /dev/null +++ b/wiki/Time-Source/index.html @@ -0,0 +1,1491 @@ + + + + + + + + Time Source - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog outputs its timestamps in local time by default, as this is expected by most first time users. +The conversion from machine time to regional local time has an overhead, so NLog uses a cached time-source (FastLocal) by default, which only refreshes every 15 msec (Follows Environment.TickCount)

+

NLog has the ability to change the time source, that provides timestamping of LogEvents. This can be done from code, and also via XML-file.

+

The following sections were based and/or provided by Robert Važan’s +blog:

+ +

Configure Via XML

+

The time source can be configured via XML by setting the time element with the +XML name. The provided time sources don’t include “TimeSource” in their XML +names.

+
<nlog>
+    <time type="AccurateUtc" />
+    <!-- Rest of Configuration -->
+</nlog>
+
+

Configure Via Runtime Configuration

+

The time source can be configured by inserting the following before any log +messages are printed:

+
NLog.Time.TimeSource.Current = new NLog.Time.AccurateUtcTimeSource();
+
+

Provided Time Sources

+

The time source implementations that are included with NLog, either provides local-time or UTC-time. Where NLog uses FastLocal by default with low accuracy, but high performance. For almost monotonic timestamp then consider using AccurateUTC:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XML ConfigurationIs Default?Runtime ConfigurationTimeAccuracySpeed
FastLocalYesFastLocalTimeSourcelocal16msvery fast
FastUTCNoFastUtcTimeSourceUTC16msvery fast
AccurateLocalNoAccurateLocalTimeSourcelocal1msslow
AccurateUTCNoAccurateUtcTimeSourceUTC1msfast
+

Performance benchmarks for time source implementations (used BenchmarkDotNet):

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Method32-bit Mean64-bit Mean
FastLocal5.205 ns3.546 ns
FastUtc5.202 ns3.541 ns
AccurateLocal190.481 ns85.927 ns
AccurateUtc137.258 ns66.451 ns
+

The accuracy relates directly to Windows and how it balances accuracy, speed, +and efficiency (i.e. battery life). By default, Windows is set to 16ms of +accuracy, but can be changed via the API calls of +timeBeginPeriod +and +timeEndPeriod.

+

Custom Time Source

+

Before implementing your own time source, see the provided time sources first. +If none of those fit your needs, this section will guide you through the +process.

+

Create a class that inherits from TimeSource and implement the inherited +property getter Time and method FromSystemTime.

+
    +
  • +

    The property getter Time provides the current time instance.

    +
  • +
  • +

    The method FromSystemTime converts the system time to the same form as if + the time source provided it.

    +
  • +
+
[TimeSource("CustomTimeZone")]
+public class CustomTimeZoneTimeSource : TimeSource
+{
+    string ZoneName;
+    TimeZoneInfo ZoneInfo;
+
+    [Required]
+    public string Zone
+    {
+        get { return ZoneName; }
+        set
+        {
+            ZoneName = value;
+            ZoneInfo
+                = TimeZoneInfo.FindSystemTimeZoneById(value);
+        }
+    }
+
+    public override DateTime Time
+    {
+        get
+        {
+            return TimeZoneInfo.ConvertTimeFromUtc(
+                DateTime.UtcNow, ZoneInfo);
+        }
+    }
+
+    public override DateTime FromSystemTime(DateTime systemTime)
+    {
+        return TimeZoneInfo.ConvertTimeFromUtc(systemTime, ZoneInfo);
+    }
+}
+
+

In addition, add an attribute to the top that provides the name when specifying +the type via XML.

+

Your custom time source can be loaded by NLog just like any other NLog +extension. See how to use the custom target / layout +renderer.

+

The Runtime Configuration would look like this:

+
TimeSource.Current = new CustomTimeZoneTimeSource()
+{
+    Zone = "Central Standard Time"
+}
+
+

The XML Configuration would look like this:

+
<nlog>
+    <time type="CustomTimeZone" zone="Central Standard Time" />
+</nlog>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Tip.png b/wiki/Tip.png new file mode 100644 index 000000000..faa569c2d Binary files /dev/null and b/wiki/Tip.png differ diff --git a/wiki/ToolStripItem-Target/index.html b/wiki/ToolStripItem-Target/index.html new file mode 100644 index 000000000..2447baf1c --- /dev/null +++ b/wiki/ToolStripItem-Target/index.html @@ -0,0 +1,1307 @@ + + + + + + + + ToolStripItem Target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+ +
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Tools/index.html b/wiki/Tools/index.html new file mode 100644 index 000000000..898e77b9e --- /dev/null +++ b/wiki/Tools/index.html @@ -0,0 +1,1334 @@ + + + + + + + + Tools - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Log Viewers/Analyzers

+

Logs produced by NLog can be analyzed using a number of GUI tools:

+

NLog-specific viewers

+
    +
  • Gibraltar (using Gibraltar Adapter for NLog) - https://nlog-project.org/2009/11/01/gibraltar-adapter-for-nlog-released.html
  • +
  • Sentinel - https://github.com/yarseyah/sentinel
  • +
  • NLogViewer - http://github.com/jkowalski/NLogViewer (functional, but no longer in development, not recommended)
  • +
  • LogEntries - http://www.logentries.com (service for cloud logging, has .net NLog target)
  • +
  • Legit Log Viewer - http://www.legitlog.com/ (Although their website is down, it is Free and powerful log viewer.)
  • +
  • ReflectInsight Viewer (using the ReflectInsight Extension for NLog) - http://insightextensions.codeplex.com/
  • +
+

Log4x-compatible viewers

+

In general, any viewer supporting Log4J or Log4Net should work fine with NLog - see Chainsaw Target for information on configuring NLog for use with those viewers. +* LogWizard - https://github.com/jtorjo/logwizard +* Apache Chainsaw v2 - https://logging.apache.org/chainsaw/ +* ~~DevIntelligence Log4Net Viewer - http://devintelligence.com/log4netviewer/~~ (questionable status) +* C# WPF Log4Net Viewer - https://www.codeproject.com/KB/cs/logviewer.aspx +* ~~Log4Net Dashboard - http://www.l4ndash.com/~~ (questionable status) +* Log4View - http://www.log4view.com/ +* Log2Console - https://github.com/Statyk7/log2console +* ~~Legit Log Viewer - http://www.legitlog.com/~~ (questionable status) +* ReflectInsight Viewer (using the ReflectInsight Extension for Log4net) - http://insightextensions.codeplex.com/ +* Free Log File Viewer: Log4Net Log4J NLog - https://sourceforge.net/projects/gamutlogviewer/ +* Lilith +* OtrosLogViewer +* LogViewer

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Trace-Activity-Id-Layout-Renderer/index.html b/wiki/Trace-Activity-Id-Layout-Renderer/index.html new file mode 100644 index 000000000..58fde383d --- /dev/null +++ b/wiki/Trace-Activity-Id-Layout-Renderer/index.html @@ -0,0 +1,1333 @@ + + + + + + + + Trace Activity Id Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Outputs the Trace.CorrelationManager.ActivityId as trace correlation id.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6

+

Introduced in NLog v4.1.

+
+

Configuration Syntax

+
${activityid}
+
+

Remarks

+
+

⚠️ Trace.CorrelationManager.ActivityId is now considered legacy and instead replaced by System.Diagnostics.Activity. See also: ${activity}

+
+

If the Trace.CorrelationManager.ActivityId is equal to Guid.Empty, then appends String.Empty, otherwise appends Trace.CorrelationManager.ActivityId as separated by hyphens according to the CultureInfo.InvariantCulture.

+

Example

+

For an ASP.NET IIS application, initialize the Trace.CorrelationManager.ActivityId in the Global.asax.cs, Application_BeginRequest event:

+
    protected void Application_BeginRequest(object sender, EventArgs e)
+    {
+        ...
+        if (Trace.CorrelationManager.ActivityId == Guid.Empty)
+        {
+            Trace.CorrelationManager.ActivityId = Guid.NewGuid();
+        }
+    }
+
+

Notice IIS Express might automatically setup ActivityId without needing the above code.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Trace-target/index.html b/wiki/Trace-target/index.html new file mode 100644 index 000000000..e352deb91 --- /dev/null +++ b/wiki/Trace-target/index.html @@ -0,0 +1,1347 @@ + + + + + + + + Trace target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Sends log messages through System.Diagnostics.Trace.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6

+
+

Configuration Syntax

+
<targets>
+  <target xsi:type="Trace" name="String" layout="Layout" />
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

Output Options

+
    +
  • layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
  • +
  • rawWrite - Always use Trace.WriteLine independent of LogLevel. Default: False
    +

    Introduced with NLog 4.5, fixes the issue with output being prefixed with exe-filename.

    +
    +
  • +
  • EnableTraceFail - Use Trace.Fail for LogLevel.Fatal, instead of Trace.Error. Default: False
    +

    Introduced with NLog 4.7, avoids Enviroment.FailFast that can happen for default trace listener.

    +
    +
  • +
  • header - Layout used to format header-output when initializing. Layout
    +

    Introduced with NLog 5.0

    +
    +
  • +
  • footer - Layout used to format footer-output when closing. Layout
    +

    Introduced with NLog 5.0

    +
    +
  • +
+

Notes

+

Alternative targets for diagnostic output: +- DebugSystem-target for output to System.Diagnostics.Debug +- Debugger-target for output to System.Diagnostics.Debugger.Log +- OutputDebugString-target for output to OutputDebugString Win32 API

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Trim-Whitespace-Layout-Renderer/index.html b/wiki/Trim-Whitespace-Layout-Renderer/index.html new file mode 100644 index 000000000..43546d410 --- /dev/null +++ b/wiki/Trim-Whitespace-Layout-Renderer/index.html @@ -0,0 +1,1324 @@ + + + + + + + + Trim Whitespace Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Trims the whitespace from the result of another layout renderer.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${trim-whitespace:trimWhiteSpace=Boolean:inner=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:trimWhiteSpace=Boolean}
+
+

Parameters

+

Transformation Options

+
    +
  • trimWhiteSpace - Indicates whether trim should be applied. Boolean Default: True
  • +
  • inner - Wrapped layout. Layout
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Tutorial/index.html b/wiki/Tutorial/index.html new file mode 100644 index 000000000..9b1bc26bd --- /dev/null +++ b/wiki/Tutorial/index.html @@ -0,0 +1,1534 @@ + + + + + + + + Tutorial - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog can be setup with the following steps:

+
    +
  1. Install NLog nuget package
  2. +
  3. Configure NLog Targets for output
  4. +
  5. Writing log messages
  6. +
+

After having setup NLog, then make sure to explore:

+ +

If something is not working as expected then check the Troubleshooting section.

+

If wanting to use Microsoft Extension Logging (MEL) then check .NET Core and ASP.NET Core tutorials.

+

Configure NLog Targets for output

+

NLog will only produce output if having configured one (or more) NLog targets.

+

NLog can be configured using XML by adding a NLog.config file to your application project (File Properties: Copy If newer). NLog will automatically load the NLog.config by searching multiple file locations. This is a simple example of the content for NLog.config:

+
<?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="logfile" xsi:type="File" fileName="logfile.txt" />
+        <target name="logconsole" xsi:type="Console" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Info" writeTo="logconsole" />
+        <logger name="*" minlevel="Debug" writeTo="logfile" />
+    </rules>
+</nlog>
+
+

Alternative one can configure programmatically by doing this in code:

+
var config = new NLog.Config.LoggingConfiguration();
+
+// Targets where to log to: File and Console
+var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "logfile.txt" };
+var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
+
+// Rules for mapping loggers to targets            
+config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
+config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
+
+// Apply config           
+NLog.LogManager.Configuration = config;
+
+

NLog 5.0 introduces a Fluent-Configuration-API so you can do this instead:

+
NLog.LogManager.Setup().LoadConfiguration(builder => {
+   builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole();
+   builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: "logfile.txt");
+});
+
+

The rules redirects logger output to the wanted output targets. The rules also provides filtering options to output only relevant logevents. Usually based on logger-name and loglevel (Ex. name="*" minlevel="Trace" means everything).

+

See also Configuration File or Configure from code

+

See also Available NLog Targets for output.

+

+

Writing log messages

+
public static class Program
+{
+    private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
+
+    public static void Main()
+    {
+        try
+        {
+           Logger.Info("Hello world");
+           System.Console.ReadKey();
+        }
+        catch (Exception ex)
+        {
+           Logger.Error(ex, "Goodbye cruel world");
+        }
+    }
+}  
+
+

The Logger can write messages with different LogLevels, which is used by the logging-rules (See minLevel in configuration example above) so only relevant messages are redirected to the wanted targets. The LogLevel identifies how important/detailed the message is. NLog can route log messages based primarily on their logger name and log level.

+

The log levels ordered by severity:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
LogLevelSeverityTypical Use
TraceMost verbose level. Used for development and seldom enabled in production.Ex. Request-payload, Response-payload, Begin-method-X or End-method-X
DebugDebugging the application behavior from internal events of interest.Ex. Executed query, User authenticated, Session expired
InfoInformation about application lifetime events like starting/stopping and configuration changes.
WarnWarnings about validation issues or temporary failures that can be recovered.
ErrorErrors where functionality has failed or Exception have been caught.
FatalMost critical level. Application is about to abort.
+

The logger is not tied to a specific target. The messages written to one logger can reach multiple targets based on the Configuration-file#rules. Maintaining this separation lets you keep logging statements in your code and easily change how and where the logs are written, just by updating the configuration in one place. See also Filtering log messages.

+

Instead of using NLog Logger directly, then NLog also supports logging abstractions like Microsoft Extension Logging or LibLog.

+

Layouts and LayoutRenderers

+

NLog allows you to customize how log messages are written to a NLog target. This shows the default SimpleLayout used by most NLog targets:

+
<target name="logfile" xsi:type="File" fileName="file.txt" layout="`${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}`" />
+
+

This can be configured to include extra context information (Ex ${threadid}):

+
<target name="logfile" xsi:type="File" fileName="file.txt" layout="${longdate}|${level:uppercase=true}|${logger}|${threadid}|${message}|${exception:format=tostring}" />
+
+

See full list here: Layout Renderers

+

One can also use a more complex Layout instead of SimpleLayout: +* CsvLayout +* JsonLayout +* XmlLayout

+

See full list here: Layouts

+

Target Wrappers

+

NLog supports special kinds of targets which do not do any logging by themselves, but extends the behavior of destination target. Those targets are called wrappers. The most commonly used ones are: +* AsyncWrapper - Improves Performance by providing asynchronous, buffered execution of target writes. +* BufferingWrapper - Simple batching of log messages. Maybe only send batch when certain log event occurs (Ex. Exception). +* FallbackGroup - Provides fallback-on-error. +* RetryingWrapper - Provides retry-on-error.

+

See full list here: Target Wrappers

+

There is a shortcut for enabling the AsyncWrapper for all targets, by adding async="true":

+
<?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 async="true">
+        <target name="logfile" xsi:type="File" fileName="file.txt" />
+    </targets>
+
+    <rules>
+        <logger name="*" minlevel="Info" writeTo="logfile" />
+    </rules>
+</nlog>
+
+

This will make all writes to the file be asynchronous, which will improve responsiveness of the calling thread.

+

Best practices for using NLog

+

1. Logger should be a static variable in each class

+

When using LogManager.GetCurrentClassLogger:

+

Creating a new Logger has a small overhead, as it has to acquire locks and allocate objects.

+

Therefore it is recommended to create the logger like this:

+
namespace MyNamespace
+{
+  public class MyClass
+  {
+    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
+  }
+}
+
+

2. Logger should handle string formatting

+

Avoid performing string allocation or string concatenation upfront, but instead let the Logger do the formatting. This will allow NLog to defer the formatting and improve performance.

+

Either using Structured logging that captures parameters as named properties:

+
logger.Info("Hello {World}", "Earth");
+
+

Or using string-format syntax:

+
logger.Info("Hello {0}", "Earth");
+
+

3. Logger should be given the Exception

+

Avoid giving the Exception as formatting parameter, but instead provide it explicitly as first parameter. This will help the NLog targets to provide better logging.

+
try
+{
+}
+catch (Exception ex)
+{
+    logger.Error(ex, "Something bad happened");
+}
+
+

4. Validate XML configuration from NLog.config

+

NLog swallows by default all exceptions, so problems with logging will not cause the application to break. But for many application the logging is very critical, so if the initial NLog configuration fails, then it is fatal.

+

Adding throwConfigExceptions="true" will make NLog complain when something is wrong with the configuration:

+
<?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"
+      throwConfigExceptions="true">
+</nlog>
+
+

There is also a setting called throwExceptions="true", which should never be used in production as it can cause havoc for your application. It is intended for unit testing and local troubleshooting. See also Troubleshooting Configuration

+

It is also a good idea to check output from NLog InternalLogger, as it can give alerts when detecting problems with the NLog configuration.

+

5. Remember to Flush

+

NLog will by default attempt to flush automatically at application shutdown. Microsoft Windows give .NET applications a limited amount of time to perform shutdown (usually 2 sec) before being terminated. If having a NLog configuration with NLog Targets that requires network-traffic (Http, Mail, Tcp), then it is a really good idea to perform a manual Flush/Shutdown independent on running on Linux/Windows.

+
NLog.LogManager.Shutdown(); // Flush and close down internal threads and timers
+
+

NET Application running on Mono/Linux are required to stop threads/timers before entering application shutdown phase. Failing to do this will cause unhandled exceptions and segmentation faults, and other unpredictable behavior.

+

NET 10.0 (and newer) no longer signals AppDomain.ProcessExit or AssemblyLoadContext.Unloading independent on running on Windows/Linux. So just like using LogManager.AutoShutdown = false.

+

6. Unhandled exeptions

+

When non-background threads dies because of unhandled Exception, then the entire application will die. For better diagnostics, then one can listen for unhandled exceptions and forward to NLog at application startup:

+
AppDomain.CurrentAppDomain.UnhandledException += (s, e) => {
+   NLog.LogManager.GetLogger("Application").Error(e.ExceptionObject as Exception, "Unhandled Application Exception");
+   NLog.LogManager.Flush();  // Ensure logs are written before application dies
+};
+
+

When async Tasks dies because of unobserved Exception and finalized, then the application will continue without making any noise. For better diagnostics, then one can listen for unobserved exceptions and forward to NLog at application startup:

+
System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (s, e) => {
+   if (e.Exception is System.OperationCanceledException)
+      NLog.LogManager.GetLogger("Application").Info(e.Exception, "Unobserved Task Cancellation");
+   else
+      NLog.LogManager.GetLogger("Application").Warn(e.Exception, "Unobserved Task Exception");
+};
+
+

Notice that TaskScheduler.UnobservedTaskException cannot be used with partial-trust .NET Framework applications, where registration will throw MethodAccessException.

+

Notice there is also AppDomain.CurrentDomain.FirstChanceException but one should avoid doing logging in this event-handler, since it will result in recursive-loop when NLog Target experience any Exception.

+

7. Environment specific target options

+

Most NLog-Target options supports NLog Layout, which means the NLog-Target options can be assigned from environment-variables, configuration-files or global diagnotic context (GDC).

+

Thus one only have to maintain a single NLog-configuration, and all environment-specific options can be extracted to a dedicated location. See also Environment specific NLog Logging Configuration

+

If wanting different output levels/targets depending on environment, then one can also use NLog Layout in the Logger-rules, thus having different minLevel="${configsetting:DefaultLevel:whenEmpty=Warn}" depending on environment (Where LogLevel Off can disable output).

+

If having multiple targets, and the targets are using the same NLog Layout for output, then one can use NLog config variables to define the NLog Layout. Instead of maintaining the NLog Layout for each target, then assign target layout to the config-variable. NLog v5 adds support for using more advanced Layouts like the JsonLayout, XmlLayout, CsvLayout or other.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Uppercase-Layout-Renderer/index.html b/wiki/Uppercase-Layout-Renderer/index.html new file mode 100644 index 000000000..468e22931 --- /dev/null +++ b/wiki/Uppercase-Layout-Renderer/index.html @@ -0,0 +1,1330 @@ + + + + + + + + Uppercase Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Converts the result of another layout output to upper case.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${uppercase:uppercase=Boolean:inner=Layout:culture=Culture}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:uppercase=Boolean}
+
+

Parameters

+

Transformation Options

+
    +
  • inner - Wrapped layout. Layout. Default attribute.
  • +
  • uppercase - Indicates whether upper case conversion should be applied. Default true with Inner, required when using as ambient.
  • +
  • culture - Culture used for rendering. Culture
  • +
+

Examples

+
${uppercase:${level}}
+${uppercase:Inner=${level}}
+${level:uppercase=true}
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Url-Encode-Layout-Renderer/index.html b/wiki/Url-Encode-Layout-Renderer/index.html new file mode 100644 index 000000000..ed8308c3c --- /dev/null +++ b/wiki/Url-Encode-Layout-Renderer/index.html @@ -0,0 +1,1323 @@ + + + + + + + + Url Encode Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Encodes the result of another layout output for use with URLs.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${url-encode:spaceAsPlus=Boolean:inner=Layout}
+
+

Parameters

+

Transformation Options

+
    +
  • spaceAsPlus - Indicates whether spaces should be translated to '+' or '%20'. Boolean
  • +
  • inner - Wrapped layout. Layout
  • +
  • escapeDataRfc3986 - NLog will by default encode as UTF8 and escape special characters according to Rfc2396. To escape data according to standard Rc3986, set this option to 'true' (Available from NLog 4.4)
  • +
  • escapeDataNLogLegacy - NLog will by default encode as UTF8 and escape special characters according to Rfc2396. To escape data according to the old non-standard NLog style, set this option to 'true' (Available from NLog 4.4)
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Var-Layout-Renderer/index.html b/wiki/Var-Layout-Renderer/index.html new file mode 100644 index 000000000..30630823a --- /dev/null +++ b/wiki/Var-Layout-Renderer/index.html @@ -0,0 +1,1353 @@ + + + + + + + + Var Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

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 as optimized 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)
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Visual-Studio-Support/index.html b/wiki/Visual-Studio-Support/index.html new file mode 100644 index 000000000..0874efe0e --- /dev/null +++ b/wiki/Visual-Studio-Support/index.html @@ -0,0 +1,1342 @@ + + + + + + + + Visual Studio Support - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog integrates with Visual Studio®

+

Intellisense

+

NLog supports Intellisense when editing XML configuration files. Install the NLog.Schema-nuget-package and update the NLog.config-file:

+
<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">
+  <!-- configuration goes here --> 
+</nlog>
+
+

Alternative enable "Automatically download DTDs and schemas" (Visual Studio Options), then Intellisense works with using direct URL:

+
<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 http://www.nlog-project.org/schemas/NLog.xsd">
+  <!-- configuration goes here --> 
+</nlog>
+
+

Notice Intellisense will only work in Visual Studio when using xsi:type="...":

+
<target xsi:type="TypeName"/>
+
+

And not:

+
<target type="TypeName"/>
+
+

Legacy

+

Integration with Add/Reference dialog

+

NLog Setup registers the appropriate AssemblyFolders entry in registry so that Visual Studio is able to locate the *.dll files and present them in Add Reference dialog. This is supported in all Visual Studio versions.

+

New Item Templates

+

NLog comes with 3 sample configuration files that can be quickly added to you project through Add New Item dialog. They are: +* configuration file that defines one File Target (typical) +* configuration file that defines one Console Target +* empty configuration file

+

Please note that you need to change “Copy To Output Directory” option of properties of NLog.config to “Copy Always”

+

Note that “New Item” templates are supported on Visual Studio 2005 and higher (including Express Editions).

+

Code Snippets

+

NLog installs a Visual Studio 2005 Code Snippet called “nlogger” that can be used to quickly declare a logger instance. It inserts the following piece of text:

+
private static Logger logger = LogManager.GetCurrentClassLogger();
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/W3CExtendedLogLayout/index.html b/wiki/W3CExtendedLogLayout/index.html new file mode 100644 index 000000000..fdaeef192 --- /dev/null +++ b/wiki/W3CExtendedLogLayout/index.html @@ -0,0 +1,1342 @@ + + + + + + + + W3CExtendedLogLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders to W3C Extended Log Format (ELF)

+
+

Platforms Supported: All

+

Introduced with NLog.Web 5.0

+
+
<target name="w3cFile" xsi:type="File" fileName="log-file.json" >
+      <layout xsi:type="W3CExtendedLogLayout">
+              <directive name="Software" layout="My Web Server" />         <!-- Optional - Can be repeated -->
+              <field name="cs-method" layout="${aspnet-request-method}" /> <!-- Optional - Can be repeated -->
+       </layout>
+</target>
+
+

Note default fields will be printed, when no fields has been specified. Same behavior for directives.

+

Parameters

+
    +
  • field
  • +
  • name - Required. The name of the W3C Extended Field
  • +
  • +

    layout - The layout value of the W3C Extended Field

    +
  • +
  • +

    directive

    +
  • +
  • name - Required. The name of the W3C Extended Directive Header
  • +
  • layout - The layout value of the W3C Extended Directive Header
  • +
+

Notes

+

Available W3C log-parsers:

+
    +
  • https://github.com/jibedoubleve/log-reader
  • +
  • https://support.microsoft.com/en-us/topic/log-parser-2-2-and-asp-net-37531636-1cf5-dc52-f12a-6a9252155631
  • +
  • https://techcommunity.microsoft.com/t5/exchange-team-blog/introducing-log-parser-studio/ba-p/601131
  • +
  • https://www.finalanalytics.com/products/httplogbrowser
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Web-resources/index.html b/wiki/Web-resources/index.html new file mode 100644 index 000000000..dd9823829 --- /dev/null +++ b/wiki/Web-resources/index.html @@ -0,0 +1,1358 @@ + + + + + + + + Web resources - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Articles and tutorials about NLog

+ +

Logging Facades

+ +

NLog Extensions

+ +

See also: Extending-NLog

+

See also: Who Is Using NLog

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WebService-target---Workaround-for-url-variables/index.html b/wiki/WebService-target---Workaround-for-url-variables/index.html new file mode 100644 index 000000000..5aca01c65 --- /dev/null +++ b/wiki/WebService-target---Workaround-for-url-variables/index.html @@ -0,0 +1,1373 @@ + + + + + + + + WebService target Workaround for url variables - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • + +
  • + Edit on GitHub +
  • +
+
+
+
+
+ +
+

⚠️ NLog 5.0 now supports Layout for the Url-parameter, so this work-around is no longer needed.

+
+

Given config

+

*a target configured as in: https://github.com/NLog/NLog/wiki/Webservice-Target-for-Splunk

+

Workaround

+

Tool driven

+
    +
  • Create a transformation from nlog.config using the slow-cheetah plugin: +https://github.com/microsoft/slow-cheetah/blob/master/doc/transforming_files.md
  • +
+

Manual

+
    +
  • Create a Nlog.Release.config (XML-File) to override the hard coded url
  • +
  • The name must be same as the name from your original target!
  • +
  • Install Package "Microsoft.VisualStudio.SlowCheetah"
  • +
  • Update your csproj file:
  • +
+
<ItemGroup>
+       <Content Update="Nlog.config">
+           <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+           <TransformOnBuild>true</TransformOnBuild>
+       </Content>
+       <None Include="Nlog.Release.config">
+           <IsTransformFile>true</IsTransformFile>
+           <DependentUpon>Nlog.config</DependentUpon>
+       </None>
+   </ItemGroup>
+
+

Content of nlog.Release.config

+
<?xml version="1.0" encoding="utf-8"?>
+<!--For more information on using transformations see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
+<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 async="true">
+        <target xsi:type="WebService"
+         name="Splunk"
+         url="NEWURL"
+         protocol="JsonPost"
+         encoding="utf-8"
+         preAuthenticate="true"
+                xdt:Transform="SetAttributes(url)" xdt:Locator="Match(name)">
+        </target>
+    </targets>
+</nlog>
+
+

If NEWURL is a variable

+
    +
  • In program.cs modify nlog.config before configuring Nlog
  • +
+
var token = Environment.GetEnvironmentVariable("YOURURL");
+     if (!string.IsNullOrWhiteSpace(token))
+     {
+       var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
+       var nlogFolder = $"{currentFolder}/nlog.config";
+
+       var configText = File.ReadAllText(nlogFolder);
+       var updatedConfig = configText
+         .Replace("NEWURL", token);
+
+       File.WriteAllText(nlogFolder, updatedConfig);
+     }
+var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
+//...
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WebService-target/index.html b/wiki/WebService-target/index.html new file mode 100644 index 000000000..cc5d92c62 --- /dev/null +++ b/wiki/WebService-target/index.html @@ -0,0 +1,1477 @@ + + + + + + + + WebService target - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Calls the specified REST web service using HTTP/HTTPS-request for each log message.

+
+

Platforms Supported: All - Requires nuget-package NLog.Targets.WebService since NLog v6

+
+

Checkout NLog.Targets.HttpClient if needing batching of multiple LogEvents in a single HTTP payload.

+

Configuration Syntax

+
<targets>
+  <target xsi:type="WebService"
+          name="String"
+          url="System.Uri"
+          protocol="Enum"
+          namespace="String"
+          methodName="String">
+    <parameter name="String" layout="Layout" parametertype="System.Type"/><!-- repeated -->
+    <header name="String" layout="Layout"/><!-- repeated -->
+  </target>
+</targets>
+
+

Parameters

+

General Options

+
    +
  • name - Name of the target.
  • +
+

HttpRequest Parameters Options

+

<parameter> defines a single parameter to be passed in the Http Request: + * name - Name of the parameter. + * layout - Layout that should be use to calculate the value for the parameter. Layout Required. + * parametertype - Type of the parameter. System.Type

+

HttpRequest Headers Options

+

<header> defines a single Http-header to be included in Http Request:

+
    +
  • name - Name of the header parameter.
  • +
  • layout - Layout that should be use to calculate the value for the parameter. Layout Required.
  • +
+
+

NLog 4.6 allows override of Http-header SoapAction for Protocol Soap11

+
+

Web Service Options

+
    +
  • +

    url - Web service URI. Layout Required.

    +
    +

    NLog 5.0 changed property-type from string to NLog Layout.

    +
    +
  • +
  • +

    Protocol - Protocol to be used when calling web service. Default: Soap11
    +Possible values:

    +
  • +
  • JsonPost - JSON POST - introduced in NLog 4.4 - ContentType "application/json"
  • +
  • XmlPost - XML POST - introduced in NLog 4.4 - ContentType "application/xml"
  • +
  • HttpGet - Use HTTP GET Protocol.
  • +
  • HttpPost - Use HTTP POST Protocol. ContentType "application/x-www-form-urlencoded"
  • +
  • Soap11 - Use SOAP 1.1 Protocol. Remember to configure Namespace + MethodName
  • +
  • +

    Soap12 - Use SOAP 1.2 Protocol. Remember to configure Namespace + MethodName

    +
  • +
  • +

    Namespace - Web service namespace for soap:Envelope (Soap11 + Soap12)

    +
  • +
  • +

    MethodName - Web service method name for soap:Envelope (Soap11 + Soap12)

    +
  • +
  • +

    encoding - Encoding. Encoding name like "utf-8", "ascii" or "utf-16". See Encoding class on MSDN. Default: Utf-8

    +
  • +
  • +

    includeBOM - Skip or add Byte-order-mark (BOM) for UTF-8. Only used if encoding is set to UTF-8, because a BOM is optional in UTF-8. default: false. For more info on BOM, check Wikipedia. +Possible options:

    +
  • +
  • null: doesn’t change BOM.
  • +
  • true: always include UTF-8 BOM UTF-8 encodings.
  • +
  • +

    false: default, always skip BOM on UTF-8 encodings.

    +
  • +
  • +

    escapeDataRfc3986 - NLog will by default encode parameters as UTF8 and escape special characters according to Rfc2396. To escape data according to standard Rc3986, set this option to 'true' (Available from NLog 4.4)

    +
  • +
  • +

    escapeDataNLogLegacy - NLog will by default encode parameters as UTF8 and escape special characters according to Rfc2396. To escape data according to the old non-standard NLog style, set this option to 'true' (Available from NLog 4.4)

    +
    +

    NLog v6 no longer supports this encoding, and marked option obsolete.

    +
    +
  • +
  • +

    Expect100Continue - Indicates whether to use http 100-Continue behavior, where the client sends headers and expects a 100-Continue response from the server before sending the request body. This feature is enabled by default for .NET Framework and can cause delays especially when http-server does not support the protocol. Setting this to false can improve performance in such cases.

    +
    +

    Introduced with NLog.Targets.WebService ver. 6.1.1

    +
    +
  • +
  • +

    PreAuthenticate - Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in Headers parameters)

    +
  • +
  • +

    ProxyType - Configuration of HttpWebRequest.Proxy. Default: DefaultWebProxy (Introduced with NLog 4.5)
    +Possible values:

    +
  • +
  • DefaultWebProxy - Default proxy configuration from WebRequest.DefaultWebProxy (defaultProxy in app.config)
  • +
  • AutoProxy - WebRequest.GetSystemWebProxy() with default network credentials (Not supported on NetCore)
  • +
  • ProxyAddress - User defined proxy address retrieved from the ProxyAddress parameter.
  • +
  • +

    NoProxy - Disables use of proxy (fast)

    +
  • +
  • +

    ProxyAddress - User defined proxy address, include port separated by a colon (Introduced with NLog 4.5)

    +
  • +
  • +

    UserAgent - User defined Http-Header 'User-Agent' for the web-request (Introduced with NLog 4.7.11)

    +
  • +
+

Remarks

+

The web service must implement a method that accepts a number of string parameters.

+

Example

+

Example config:

+
<nlog>
+    <targets>
+        <target type='WebService'
+                name='ws'
+                url='http://localhost:1234/logme/post'
+                protocol='HttpPost'
+                encoding='UTF-8'>
+            <parameter name='param1' type='System.String' layout='${message}'/> 
+            <parameter name='param2' type='System.String' layout='${level}'/>
+        </target>
+    </targets>
+    <rules>
+      <logger name='*'writeTo='ws'></logger>
+    </rules>
+</nlog>
+
+

Example API controller

+

+public class LogMeController : ApiController
+{
+    /// <summary>
+    /// We need a complex type for modelbinding because 
+    /// of content-type: "application/x-www-form-urlencoded" 
+    /// in <see cref="WebServiceTarget"/>
+    /// </summary>
+    public class ComplexType
+    {
+        public string Param1 { get; set; }
+        public string Param2 { get; set; }
+    }
+
+    /// <summary>
+    /// Post
+    /// </summary>
+    public void Post([FromBody] ComplexType complexType)
+    {
+        //do something
+    }
+}
+
+

Example with JSON document

+

NLog v4.5 supports sending custom JSON document using a single nameless parameter, instead individual named parameters:

+
<target type="WebService"
+   name="ws"
+   url="http://localhost:1234/logme/jsonpost"
+   protocol="JsonPost">
+   <parameter name="">
+      <layout xsi:type="JsonLayout">
+         <attribute name='logger' layout='${logger}' />
+         <attribute name='level' layout='${level}' />
+         <attribute name="message" layout="${message}" />
+      </layout>
+   </parameter>
+</target>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Webservice-Target-for-Splunk/index.html b/wiki/Webservice-Target-for-Splunk/index.html new file mode 100644 index 000000000..17df1b253 --- /dev/null +++ b/wiki/Webservice-Target-for-Splunk/index.html @@ -0,0 +1,1352 @@ + + + + + + + + Webservice Target for Splunk - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Example config for Splunk:

+
    +
  • You have to authorize against splunk see header attribute
  • +
  • Your content must be wrapped in <parameter name="event">
  • +
+
<target xsi:type="WebService"
+         name="Splunk"
+         url="http(s)://SPLUNKSERVER/services/collector/event"
+         protocol="JsonPost"
+         encoding="utf-8"
+         preAuthenticate="true">
+      <header name='Authorization' layout='Splunk YOURTOKEN' />
+<!-- 
+OR from config
+<header name='Authorization' layout='Splunk ${configsetting:name=Splunk.Token}' />
+-->
+      <parameter name='sourcetype' layout='_json'/> 
+      <parameter name="event">
+        <layout xsi:type="JsonLayout">        
+          <attribute name="Exception" encode="false" layout="${exception:format=@}" />       
+          <attribute name="Logger" layout="${logger}" />
+          <attribute name="Level" layout="${level}"/>
+          <attribute name="Date" layout="${longdate}"/>
+        </layout>
+      </parameter>    
+    </target>
+
+

Alternative TCP/UDP config for Splunk

+

Setup Splunk Input: +- From the Splunk Settings, select Data Inputs +- Click Add new for TCP (or UDP) +- Configure the TCP (or UDP) port to use +- On the page Input Settings you can (optionally) specify various things about the data you are going to be sending. There are two particularly useful settings here, the sourcetype and index +- Click Review and then Submit

+

Setup NLog Network Target:

+
<target xsi:type="Network"
+         name="Splunk"
+         address="tcp://<splunk-address>:<splunk-port>"
+         newLine="true"
+         layout="${level}|${logger}|${message}|{exception:format=tostring}">
+</target>
+
+

Splunk supports SYSLOG format for TCP/UDP, so maybe try out Syslog Target

+

Notice that UDP-protocol has restrictions for log-message size, so they can become discarded.

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/When-Filter/index.html b/wiki/When-Filter/index.html new file mode 100644 index 000000000..67b0e4e9d --- /dev/null +++ b/wiki/When-Filter/index.html @@ -0,0 +1,1436 @@ + + + + + + + + When Filter - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Filter events in the config.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<rules>
+  <logger ... >
+    <filters defaultAction="Neutral | Ignore | Log | LogFinal | IgnoreFinal">
+      <when condition="Condition" action="Enum"/>
+    </filters>
+  </logger>
+</rules>
+
+

Parameters

+
    +
  • +

    defaultAction - default filter action when no match. Default Ignore.

    +
    +

    Introduced with NLog 4.6. Before NLog 5.0 the default was Neutral.

    +
    +
  • +
  • +

    Ignore - The message should not be logged.

    +
  • +
  • IgnoreFinal - The message should not be logged and ignore any following logging-rules.
  • +
  • Log - The message should be logged.
  • +
  • LogFinal - The message should be logged and ignore any following logging-rules.
  • +
  • +

    Neutral - No decision

    +
  • +
  • +

    filterdefaultaction - Alternative name for defaultAction to match actual API.

    +
    +

    Introduced with NLog 5.0

    +
    +
  • +
+

Filtering Options

+
    +
  • condition - Condition expression. Condition Required. See section Conditions below.
  • +
  • action - Action to be taken when filter matches. Required.
    +Possible values:
  • +
  • Ignore - The message should not be logged.
  • +
  • IgnoreFinal - The message should not be logged and ignore any following logging-rules.
  • +
  • Log - The message should be logged.
  • +
  • LogFinal - The message should be logged and ignore any following logging-rules.
  • +
  • Neutral - The filter doesn't want to decide whether to log or discard the message.
  • +
+

Conditions

+

Conditions are expressions used with the <when> filter. They consist of one or more tests. They are used in the filter to determine if an action will be taken.

+

Predefined Tokens

+
    +
  • message - LogEvent formatted message
  • +
  • logger - Logger name
  • +
  • level - LogLevel object
  • +
  • exception - Exception object (Introduced with NLog 5.0)
  • +
  • ${layout} - All available layout-options (except stacktrace).
  • +
+

Condition Language

+

The filter expressions are written in a special mini-language. The language consists of: +* relational operators: ==, !=, <, <=, >= and > +
Note: Some predefined XML characters may need to be escaped. For example, if you try to use the '<' character, the XML parser will interpret it as an opening tag which results in an error in the configuration file. Instead, use the escaped version of '<' (&lt;) in this context. +* boolean operators: and, or, not +* string literals which are always evaluated as layouts - ${somerenderer} +* boolean literals - true and false +* numeric literals - e.g. 12345 (integer literal) and 12345.678 (floating point literal) +* log level literals - LogLevel.Trace, LogLevel.Debug, ... LogLevel.Fatal +* predefined keywords to access the most common log event properties - level, message and logger +* braces - to override default priorities and group expressions together +* condition functions - to perform string and object tests +* Single quotes should be escaped with another single quote.

+

Condition Functions

+

The following condition functions are available: +* contains(s1,s2) Determines whether the second string is a substring of the first one. Returns: true when the second string is a substring of the first string, false otherwise. +* ends-with(s1,s2) Determines whether the second string is a suffix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise. +* equals(o1,o2) Compares two objects for equality. Returns: true when two objects are equal, false otherwise.

+
+

Notice that 'o1' == 'o2' or 'o1' != 'o2' will be faster and reduces memory allocations. +* length(s) Returns the length of a string. +Notice that 's' != '' is faster than length('s') > 0, and reduces memory allocation. +* starts-with(s1,s2) Determines whether the second string is a prefix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise. +* regex-matches(input, pattern, options) Introduced in NLog 4.5. Indicates whether the regular expression pattern finds a match in the specified input string. options is an optional comma separated list of values from the RegexOptions enumeration.
+Returns : true when a match is found in the input string, false otherwise.
+Example : regex-matches('${message}', '^foo$', 'ignorecase,singleline')

+
+

Quotes

+

Single quotes should be escaped with another single quote. +Example:

+
contains('${message}', 'Cannot insert the value NULL into column ''Col1')
+
+

Extensibility

+

New custom condition functions methods can also be added.

+

NLog 4.7 allows you to register your own condition methods using LogFactory.Setup(). Where a lambda can be registered like this:

+
LogManager.Setup().SetupExtensions(s => 
+   s.RegisterConditionMethod("hasParameters", evt => evt.Parameters?.Length > 0)
+);
+
+

And a static method like this:

+
LogManager.Setup().SetupExtensions(s =>
+   s.RegisterConditionMethod("hasPriority", typeof(NLogConditionMethods).GetMethod("HasPriority", BindingFlags.Static))
+);
+
+

Alternative way of adding custom condition methods is creating a public static class with a static function and mark the class and method with the attributes [ConditionMethods] and [ConditionMethod] respectively.

+

You can find a sample implementation of a custom filter here

+

Then you have to tell NLog where to find your assembly (Ex. NLog.ConditionMethodsAssembly.dll)

+
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.netfx35.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
+    <extensions>
+        <add assembly="NLog.ConditionMethodsAssembly" />
+    </extensions>
+   ...
+<nlog>
+
+

Examples

+

Here are several examples with conditions:

+
<rules>
+    <logger name="*" minLevel="Debug" writeTo="file">
+        <filters defaultAction="Log">
+            <when condition="exception != null" action="Log" />
+            <when condition="length(message) > 100" action="Ignore" />
+            <when condition="'${OnHasProperties:1}' != ''" action="Ignore" />
+            <when condition="logger == 'MyApps.SomeClass'" action="Ignore" />
+            <when condition="(level >= LogLevel.Debug and contains(message, 'PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" />
+            <when condition="not starts-with(message, 'PleaseLogThis')" action="Ignore" />
+            <when condition="contains(message, '&quot;Bob&quot;')" action="Ignore" />  <!-- "Bob" -->
+        </filters>
+    </logger>
+</rules>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/When-Layout-Renderer/index.html b/wiki/When-Layout-Renderer/index.html new file mode 100644 index 000000000..130a3d99e --- /dev/null +++ b/wiki/When-Layout-Renderer/index.html @@ -0,0 +1,1398 @@ + + + + + + + + When Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Only outputs the inner layout when the specified condition has been met. See Conditions.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${when:when=Condition:inner=Layout:else=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:when=Condition}
+
+

Parameters

+

Transformation Options

+
    +
  • when - Condition that must be met for the inner layout to be printed. Condition Required.
  • +
  • inner - Wrapped layout. Layout
  • +
  • else - Layout if the condition is not true (introduced in NLog 4.3.5)
  • +
+

Examples

+

print the message when the logger name is equal to "logger": + ``` +${message:when=logger=='logger'}

+

+convert a layout string result to a bit (1 or 0) that can be inserted into a SQL bit field.:
+
+
+

${when:when='${aspnet-request:serverVariable=HTTPS}' == 'on':inner=1:else=0}

+

+Write "Good" if the loglevel is trace/debug/info and otherwise "Bad":
+
+
+

${when:when=level<=LogLevel.Info:inner=Good:else=Bad}

+

+Write suffix to property-value when available:
+
+
+

${when:when='${event-properties:item=PropName}'=='':else= ${event-properties:item=PropName} Secs}

+

+Only write the message if it does not start with `Published` using a [condition function](https://github.com/NLog/NLog/wiki/When-Filter#condition-functions):
+
+
+

${when:when=not starts-with(message, 'Published'):inner=${message}} +```

+

Escaping

+

Since NLog 4.2

+

When using : and } in a internal layout those characters need to be escaped (there is no need to escape \).

+
    +
  • : because it's an option-separator.
  • +
  • } because it's the end of the layout
  • +
+

Working examples:

+
    +
  • ${when:when=1 == 1:Inner=Test\: Hello}
  • +
  • ${when:when=1 == 1:Inner=Test\\Hello}
  • +
  • ${when:when=1 == 1:Inner=Test\Hello}
  • +
  • ${when:when=1 == 1:Inner=Test{Hello\}}
  • +
+

Before NLog 4.2

+

The colon (:) character should be wrapped within {literal:text=\:} instead of placed directly within the inner layout.

+

Working Example

+ + + + + + + + + + + + + +
Configurationlayout="${when:when=1 == 1:inner=Test${literal:text=\:} Hello${literal:text=\:} World}"
OutputTest: Hello: World
+

Non-working Example

+ + + + + + + + + + + + + +
Configurationlayout="${when:when=1 == 1:inner=Test: Hello: World}"
OutputWorld
+

When the colon character is not wrapped only the last literal instance, in this case the word 'World', appears.

+

:star: Workaround identified by: @reedyrm

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WhenContains-filter/index.html b/wiki/WhenContains-filter/index.html new file mode 100644 index 000000000..8e1326b05 --- /dev/null +++ b/wiki/WhenContains-filter/index.html @@ -0,0 +1,1335 @@ + + + + + + + + WhenContains filter - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Matches when the calculated layout contains the specified substring. This filter is deprecated in favour of \ which is based on conditions.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<rules>
+  <logger ... >
+    <filters>
+      <whenContains layout="Layout" substring="String" action="Enum" ignoreCase="Boolean"/>
+    </filters>
+  </logger>
+</rules>
+
+

Parameters

+

Filtering Options

+
    +
  • layout - Layout to be used to filter log messages. Layout Required.
  • +
  • substring - Substring to be matched. Required.
  • +
  • action - Action to be taken when filter matches. Required.
    +Possible values:
  • +
  • Ignore - The message should not be logged.
  • +
  • IgnoreFinal - The message should not be logged and processing should be finished.
  • +
  • Log - The message should be logged.
  • +
  • LogFinal - The message should be logged and processing should be finished.
  • +
  • Neutral - The filter doesn't want to decide whether to log or discard the message.
  • +
  • ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WhenEmpty-Layout-Renderer/index.html b/wiki/WhenEmpty-Layout-Renderer/index.html new file mode 100644 index 000000000..f1f3d1d1c --- /dev/null +++ b/wiki/WhenEmpty-Layout-Renderer/index.html @@ -0,0 +1,1324 @@ + + + + + + + + WhenEmpty Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Outputs alternative layout when the inner layout produces empty result.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${whenEmpty:whenEmpty=Layout:inner=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:whenEmpty=Layout}
+
+

Parameters

+

Transformation Options

+
    +
  • whenEmpty - Layout to be rendered when original layout produced empty result. Layout Required.
  • +
  • inner - Wrapped layout. Layout
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WhenEqual-filter/index.html b/wiki/WhenEqual-filter/index.html new file mode 100644 index 000000000..2bb4bc66a --- /dev/null +++ b/wiki/WhenEqual-filter/index.html @@ -0,0 +1,1335 @@ + + + + + + + + WhenEqual filter - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Matches when the calculated layout is equal to the specified substring. This filter is deprecated in favour of \ which is based on contitions.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<rules>
+  <logger ... >
+    <filters>
+      <whenEqual ignoreCase="Boolean" layout="Layout" action="Enum" compareTo="String"/>
+    </filters>
+  </logger>
+</rules>
+
+

Parameters

+

Filtering Options

+
    +
  • layout - Layout to be used to filter log messages. Layout Required.
  • +
  • action - Action to be taken when filter matches. Required.
    +Possible values:
  • +
  • Ignore - The message should not be logged.
  • +
  • IgnoreFinal - The message should not be logged and processing should be finished.
  • +
  • Log - The message should be logged.
  • +
  • LogFinal - The message should be logged and processing should be finished.
  • +
  • Neutral - The filter doesn't want to decide whether to log or discard the message.
  • +
  • compareTo - String to compare the layout to. Required.
  • +
  • ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WhenNotContains-filter/index.html b/wiki/WhenNotContains-filter/index.html new file mode 100644 index 000000000..5c1d5dfad --- /dev/null +++ b/wiki/WhenNotContains-filter/index.html @@ -0,0 +1,1335 @@ + + + + + + + + WhenNotContains filter - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Matches when the calculated layout does NOT contain the specified substring. This filter is deprecated in favour of \ which is based on contitions.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<rules>
+  <logger ... >
+    <filters>
+      <whenNotContains layout="Layout" substring="String" action="Enum" ignoreCase="Boolean"/>
+    </filters>
+  </logger>
+</rules>
+
+

Parameters

+

Filtering Options

+
    +
  • layout - Layout to be used to filter log messages. Layout Required.
  • +
  • substring - Substring to be matched. Required.
  • +
  • action - Action to be taken when filter matches. Required.
    +Possible values:
  • +
  • Ignore - The message should not be logged.
  • +
  • IgnoreFinal - The message should not be logged and processing should be finished.
  • +
  • Log - The message should be logged.
  • +
  • LogFinal - The message should be logged and processing should be finished.
  • +
  • Neutral - The filter doesn't want to decide whether to log or discard the message.
  • +
  • ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WhenNotEqual-filter/index.html b/wiki/WhenNotEqual-filter/index.html new file mode 100644 index 000000000..abefa6f0a --- /dev/null +++ b/wiki/WhenNotEqual-filter/index.html @@ -0,0 +1,1335 @@ + + + + + + + + WhenNotEqual filter - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Matches when the calculated layout is NOT equal to the specified substring. This filter is deprecated in favour of \ which is based on contitions.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
<rules>
+  <logger ... >
+    <filters>
+      <whenNotEqual ignoreCase="Boolean" layout="Layout" action="Enum" compareTo="String"/>
+    </filters>
+  </logger>
+</rules>
+
+

Parameters

+

Filtering Options

+
    +
  • layout - Layout to be used to filter log messages. Layout Required.
  • +
  • action - Action to be taken when filter matches. Required.
    +Possible values:
  • +
  • Ignore - The message should not be logged.
  • +
  • IgnoreFinal - The message should not be logged and processing should be finished.
  • +
  • Log - The message should be logged.
  • +
  • LogFinal - The message should be logged and processing should be finished.
  • +
  • Neutral - The filter doesn't want to decide whether to log or discard the message.
  • +
  • compareTo - String to compare the layout to. Required.
  • +
  • ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WhenRepeated-Filter/index.html b/wiki/WhenRepeated-Filter/index.html new file mode 100644 index 000000000..79012c0cb --- /dev/null +++ b/wiki/WhenRepeated-Filter/index.html @@ -0,0 +1,1346 @@ + + + + + + + + WhenRepeated Filter - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Matches when the calculated layout has already been logged. Useful if having an aggressive logger, and wants to throttle the output.

+

Introduced with NLog ver. 4.5

+

Configuration Syntax

+
<rules>
+  <logger ... >
+    <filters defaultAction="Log">
+      <whenRepeated layout="Layout" timeoutSeconds="30" action="Ignore" />
+    </filters>
+  </logger>
+</rules>
+
+

Can also be combined with FilteringWrapper-target.

+

Parameters

+

Filtering Options

+
    +
  • layout - Layout to be used to filter log messages. Layout Required.
  • +
  • timeoutSeconds - How long to ignore identical messages before logging again (Default 10 secs)
  • +
  • action - Action to be taken when filter matches. Required.
    +Possible values:
  • +
  • Ignore - The message should not be logged.
  • +
  • IgnoreFinal - The message should not be logged and processing should be finished.
  • +
  • Log - The message should be logged.
  • +
  • LogFinal - The message should be logged and processing should be finished.
  • +
  • Neutral - The filter doesn't want to decide whether to log or discard the message.
  • +
  • includeFirst - Should action also be applied to the initial logevent? When enabled then it will only perform the first logging if the messages continues after the initial timeout. (Default: false)
  • +
+

Logging Options

+
    +
  • FilterCountPropertyName - Tell how many identical log messages has been ignored. By adding LogEvent-Property with this name to the next LogEvent after timeout expires.
  • +
  • FilterCountMessageAppendFormat - Tell how many identical log messages has been ignored. By appending to LogEVent-Message to the next LogEvent after timeout expires (Ex. " (Hits: {0}")
  • +
+

Advanced Parameters

+
    +
  • MaxLength - Max number of characters to include when checking for identical messages (Default 1000 characters)
  • +
  • MaxFilterCacheSize - Max number of unique log messages to keep in cache, before starting to prune (Default 50000)
  • +
  • DefaultFilterCacheSize - Initial start size of the cache for keep track of unique log messages (Default 1000)
  • +
  • OptimizeBufferDefaultLength - Initial allocated size of the reusable buffers (Default 1000)
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Who-Is-Using-NLog/index.html b/wiki/Who-Is-Using-NLog/index.html new file mode 100644 index 000000000..f44835583 --- /dev/null +++ b/wiki/Who-Is-Using-NLog/index.html @@ -0,0 +1,1341 @@ + + + + + + + + Who Is Using NLog - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

NLog is being used in a number of software projects, both commercial and open source. If you are using NLog in your product, feel free to expand this page by adding short information about your project and/or company (make sure you have permission to use your company name and/or logo).

+

Open source projects

+

The following open source software projects are using or supporting NLog: +* Logging - https://github.com/akovac35/Logging +* SimplePM (programming contests management system) - https://github.com/SirkadirovTeam/SimplePM_Server +* Castle Project/Windsor Container - https://github.com/castleproject/Core/blob/master/docs/logging.md +* Ninject - http://ninject.org/ +* Common Infrastructure Libraries for .NET - http://netcommon.sourceforge.net/ +* EasyLOB - http://www.easylob.com +* TeamCity Configuration Monitor - http://teamcityconfmonitor.codeplex.com/ +* MassTransit - http://masstransit-project.com/ +* Topshelf - http://topshelf-project.com/ +* ServiceStack - https://docs.servicestack.net/logging +* ReflectInsight Extensions - https://insightextensions.codeplex.com/ +* Fop2DD - https://github.com/KeenSystemsNL/Fop2DD +* Ember Media Manager - http://embermediamanager.org/ +* ArchiSteamFarm - https://github.com/JustArchiNET/ArchiSteamFarm +* Sonarr - https://github.com/Sonarr/Sonarr +* Radarr - https://github.com/Radarr/Radarr +* Jackett - https://github.com/Jackett/Jackett +* SCM Backup - https://scm-backup.org/

+

Commercial software

+
    +
  • Gibraltar - https://nlog-project.org/2009/11/01/gibraltar-adapter-for-nlog-released.html
  • +
  • TradeBullet - http://www.tradebullet.com
  • +
  • LiteStock - http://www.lightweightlabs.com
  • +
  • ReflectInsight by ReflectSoftware - http://www.reflectsoftware.com/
  • +
  • Nemo Documents - http://www.nemo-docs.com
  • +
  • Misk.com - https://www.misk.com/
  • +
  • VisioForge - http://www.visioforge.com
  • +
  • elmah.io - https://elmah.io
  • +
+

See also: Articles and tutorials about NLog

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Windows-Identity-Layout-Renderer/index.html b/wiki/Windows-Identity-Layout-Renderer/index.html new file mode 100644 index 000000000..80b5f62a5 --- /dev/null +++ b/wiki/Windows-Identity-Layout-Renderer/index.html @@ -0,0 +1,1333 @@ + + + + + + + + Windows Identity Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Render Windows identity information (username) from the current thread-context.

+
+

Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsIdentity since NLog 5.0

+
+

Configuration Syntax

+
${windows-identity:userName=Boolean:domain=Boolean}
+
+

Parameters

+

Rendering Options

+
    +
  • userName - Indicates whether username should be included. Boolean Default: True
  • +
  • domain - Indicates whether domain name should be included. Boolean Default: True
  • +
+

Notes

+ + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/WrapLine-layout-renderer/index.html b/wiki/WrapLine-layout-renderer/index.html new file mode 100644 index 000000000..1ae1b92f0 --- /dev/null +++ b/wiki/WrapLine-layout-renderer/index.html @@ -0,0 +1,1331 @@ + + + + + + + + WrapLine layout renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Wraps the result of another layout output at specified line length.

+
+

Platforms Supported: All

+

Introduced in NLog 4.3.4

+
+

Configuration Syntax

+
${wrapline=Integer:inner=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:wrapline=Integer}
+
+

Parameters

+

Transformation Options

+
    +
  • inner - Wrapped layout. Layout. Default attribute.
  • +
  • wrapline - Indicates wrapping position. Integer greater than 0. Default: 80
  • +
+

Examples

+
${wrapline:${message}}
+${wrapline:Inner=${message}:WrapLine=80}
+${message:wrapline=80}
+
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/XML-config-include-Example/index.html b/wiki/XML-config-include-Example/index.html new file mode 100644 index 000000000..625a5afbb --- /dev/null +++ b/wiki/XML-config-include-Example/index.html @@ -0,0 +1,1352 @@ + + + + + + + + XML config include Example - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Example with a <include /> and <variable /> in the XML config

+

base file: d:\nlog-file.config

+

File to be included. +Contains one target and needs ${productName}

+
<?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">
+  <!-- This file will be included. -->
+  <!--  Note: Attributes on the "nlog" element are ignored for this file, the ones of the main config will be used. -->
+
+  <!-- the variable ${productName} must be defined in the main nlog.config -->
+
+  <targets>
+      <target name="file1" xsi:type="File" fileName="D:\logs\${productName}\${shortdate}.log" 
+          layout="${time} [${level:uppercase=true}] |${logger}| ${message} ${exception}" />
+  </targets>
+
+</nlog>
+
+
+

nlog.config

+

The main file. +e.g. in the root folder of your application. Contains in this example no targets, only <include />,,`

+

+<?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">
+
+  <!-- override productName in includes, so it could be used in d:\nlog-file.config -->
+  <variable name="productName" value="myProduct"/> 
+
+  <include file="D:\nlog-file.config" ignoreErrors="true" />    
+
+  <!-- note: will be set after the include are loaded -->
+  <variable name="myVar" value="myValue"/> 
+
+  <rules>      
+    <logger name="*" minlevel="Info" writeTo="file1" enabled="false" />     
+    <logger name="PerformanceLogger" minlevel="Trace"  writeTo="file1" enabled="false" />   <!-- not enabled, only when tracing -->
+
+  </rules>
+</nlog>
+
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/Xml-Encode-Layout-Renderer/index.html b/wiki/Xml-Encode-Layout-Renderer/index.html new file mode 100644 index 000000000..7553de4e9 --- /dev/null +++ b/wiki/Xml-Encode-Layout-Renderer/index.html @@ -0,0 +1,1324 @@ + + + + + + + + Xml Encode Layout Renderer - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

Converts the result of another layout output to be XML-compliant.

+
+

Platforms Supported: All

+
+

Configuration Syntax

+
${xml-encode:xmlEncode=Boolean:inner=Layout}
+
+

or by using ambient property to modify output of other layout renderer:

+
${other:xmlEncode=Boolean}
+
+

Parameters

+

Transformation Options

+
    +
  • xmlEncode - Indicates whether to apply XML encoding. Boolean Default: True
  • +
  • inner - Wrapped layout. Layout
  • +
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/XmlLayout/index.html b/wiki/XmlLayout/index.html new file mode 100644 index 000000000..cd7cd9d04 --- /dev/null +++ b/wiki/XmlLayout/index.html @@ -0,0 +1,1483 @@ + + + + + + + + XmlLayout - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

A specialized layout that renders to XML.

+
+

Platforms Supported: All

+

Introduced in NLog 4.6

+
+
<target name="xmlFile" xsi:type="File" fileName="${logFileNamePrefix}.xml" >
+      <layout xsi:type="XmlLayout" includeEventProperties="false" elementName='logevent'>
+              <attribute name="time" layout="${longdate}" />
+              <attribute name="level" layout="${level:upperCase=true}"/>
+              <element name="message" value="${message}" />
+      </layout>
+</target>
+
+

This would write:

+
<logevent time="2010-01-01 12:34:56.0000" level="ERROR">
+   <message>hello, world</message>
+</logevent>
+
+

Parameters

+

Root

+
    +
  • ElementName - Name of the top level XML element Default: logevent
  • +
  • ElementValue - Value inside the top level XML element Layout
  • +
  • +

    ElementEncode - Xml Encode the value for the top level XML element Boolean Default: True + > Ensures always valid XML, but gives a performance hit

    +
  • +
  • +

    IndentXml - Insert newlines and simplistic indention of output. Boolean. Default: False

    +
  • +
  • +

    IncludeEmptyValue - Whether a ElementValue with empty value should be included in the output Boolean Default: False

    +
  • +
  • +

    MaxRecursionLimit - How far should the XML serializer follow object references before backing off. Integer. Default 1 (0 = No object reflection)

    +
  • +
  • +

    IncludeEventProperties - Include all events properties of a logevent? Default: false.

    +
    +

    Before NLog 5.0 option was named IncludeAllProperties

    +
    +
  • +
  • IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false.
    +

    Before NLog 5.0 option was named IncludeMdlc or IncludeMdc

    +
    +
  • +
  • +

    ExcludeProperties - Comma separated string with names which properties to exclude. Only used when IncludeEventProperties is true. Case sensitive. Default empty When a name contains a comma, single quote the value. E.g. 'value,withquote',value2.

    +
  • +
  • +

    PropertiesElementName - Element name to use when rendering properties. Support string-format where {0} means property-key-name. Skips closing element tag when having configured PropertiesElementValueAttribute

    +
  • +
  • +

    PropertiesElementKeyAttribute - Attribute name to use when rendering property-key. When null (or empty) then key-attribute is not included. Will replace newlines in attribute-value with &#13;&#10;

    +
  • +
  • +

    PropertiesElementValueAttribute - Attribute name to use when rendering property-value. When null (or empty) then value-attribute is not included and value is formatted as XML-element-value. Skips closing element tag when using attribute for value Will replace newlines in attribute-value with &#13;&#10;

    +
  • +
  • PropertiesCollectionItemName - Element name to use for rendering IList-collections items
  • +
+

Elements

+

<element> defines childs elements to render:

+
    +
  • Name - Name of the element. Default 'item'
  • +
  • Value - Value inside the element Layout
  • +
  • Encode - Xml Encode the value Boolean Default: True
  • +
+
+

Configuration parameters for Root can also be used for each <element>-element.

+
+

Attributes

+

<attribute> defines the attributes to render:

+
    +
  • Name - Name of the attribute. Required.
  • +
  • Layout - Layout that will be rendered as the attribute's value. Layout Required.
  • +
  • Encode - Xml Encode the attribute value. Boolean Default: True
  • +
  • IncludeEmptyValue - - Whether an attribute with empty value should be included in the output Boolean
  • +
+

Examples

+

XML with attributes and elements

+

XmlLayout

+
<layout type='XmlLayout' >
+     <attribute name='logger' layout='${logger}' includeEmptyValue='true' />
+     <attribute name='level' layout='${uppercase:${level}}' includeEmptyValue='true' />
+     <element name='message' value='${message}' />
+     <element name='exception'>
+         <attribute name='tyoe' layout='${exception:format=type}' />
+         <attribute name='message' layout='${exception:format=message}' />
+         <attribute name='stacktrace' layout='${exception:format=tostring}' />
+     </element>
+</layout>
+
+

Xml Output

+
<logevent logger="logger1" level="INFO">
+  <message>My log message</message>
+  <exception>My exception message</exception>
+  <location class-name="MyNamespace.MyClass"></location>
+</logevent>
+
+

LogEventInfo Properties Default Output

+

XmlLayout

+
<layout xsi:type="XmlLayout" includeEventProperties="true">
+</layout>
+
+

Xml Output

+
<logevent>
+  <property key="PropertyName">PropertyValue</property>
+</logevent>
+
+

LogEventInfo Properties with element-name override

+

XmlLayout

+
<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesElementName="myparm">
+</layout>
+
+

Xml Output

+
<logevent>
+  <myparm key="PropertyName">PropertyValue</myparm>
+</logevent>
+
+

LogEventInfo Properties with element-name as property-name

+

XmlLayout

+
<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesElementKeyAttribute="" propertiesElementName="{0}">
+</layout>
+
+

Xml Output

+
<logevent>
+  <PropertyName>PropertyValue</PropertyName>
+</logevent>
+
+

LogEventInfo Properties Value as attribute:

+

XmlLayout

+
<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesElementValueAttribute="value">
+</layout>
+
+

Xml Output

+
<logevent>
+  <property key="PropertyName" value="PropertyValue"/>
+</logevent>
+
+

LogEventInfo Properties Dictionary-object Default Output

+

XmlLayout

+
<layout xsi:type="XmlLayout" includeEventProperties="true">
+</layout>
+
+

Xml Output

+
<logevent>
+  <property key="PropertyName"><property key="DictionaryKey">DictionaryValue</property></property>
+</logevent>
+
+

LogEventInfo Properties List-object Default Output

+

XmlLayout

+
<layout xsi:type="XmlLayout" includeEventProperties="true">
+</layout>
+
+

Xml Output

+
<logevent>
+  <property key="PropertyName"><item>ListValue1</item><item>ListValue2</item></property>
+</logevent>
+
+

LogEventInfo Properties List-object with element-name override

+

XmlLayout

+
<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesCollectionItemName="element">
+</layout>
+
+

Xml Output

+
<logevent>
+  <property key="PropertyName"><element>ListValue1</element><element>ListValue2</element></property>
+</logevent>
+
+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/_Footer.creole b/wiki/_Footer.creole new file mode 100644 index 000000000..f4df88b3a --- /dev/null +++ b/wiki/_Footer.creole @@ -0,0 +1,2 @@ +- [[Troubleshooting Guide|Logging-troubleshooting]] +- See available NLog Targets and Layouts: https://nlog-project.org/config \ No newline at end of file diff --git a/wiki/_Sidebar/index.html b/wiki/_Sidebar/index.html new file mode 100644 index 000000000..b2c28f3c6 --- /dev/null +++ b/wiki/_Sidebar/index.html @@ -0,0 +1,1357 @@ + + + + + + + + Sidebar - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ + + +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + Next » + + +
+ + + + + + + + + diff --git a/wiki/css/fonts/Roboto-Slab-Bold.woff b/wiki/css/fonts/Roboto-Slab-Bold.woff new file mode 100644 index 000000000..6cb600001 Binary files /dev/null and b/wiki/css/fonts/Roboto-Slab-Bold.woff differ diff --git a/wiki/css/fonts/Roboto-Slab-Bold.woff2 b/wiki/css/fonts/Roboto-Slab-Bold.woff2 new file mode 100644 index 000000000..7059e2314 Binary files /dev/null and b/wiki/css/fonts/Roboto-Slab-Bold.woff2 differ diff --git a/wiki/css/fonts/Roboto-Slab-Regular.woff b/wiki/css/fonts/Roboto-Slab-Regular.woff new file mode 100644 index 000000000..f815f63f9 Binary files /dev/null and b/wiki/css/fonts/Roboto-Slab-Regular.woff differ diff --git a/wiki/css/fonts/Roboto-Slab-Regular.woff2 b/wiki/css/fonts/Roboto-Slab-Regular.woff2 new file mode 100644 index 000000000..f2c76e5bd Binary files /dev/null and b/wiki/css/fonts/Roboto-Slab-Regular.woff2 differ diff --git a/wiki/css/fonts/fontawesome-webfont.eot b/wiki/css/fonts/fontawesome-webfont.eot new file mode 100644 index 000000000..e9f60ca95 Binary files /dev/null and b/wiki/css/fonts/fontawesome-webfont.eot differ diff --git a/wiki/css/fonts/fontawesome-webfont.svg b/wiki/css/fonts/fontawesome-webfont.svg new file mode 100644 index 000000000..855c845e5 --- /dev/null +++ b/wiki/css/fonts/fontawesome-webfont.svg @@ -0,0 +1,2671 @@ + + + + +Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016 + By ,,, +Copyright Dave Gandy 2016. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/wiki/css/fonts/fontawesome-webfont.ttf b/wiki/css/fonts/fontawesome-webfont.ttf new file mode 100644 index 000000000..35acda2fa Binary files /dev/null and b/wiki/css/fonts/fontawesome-webfont.ttf differ diff --git a/wiki/css/fonts/fontawesome-webfont.woff b/wiki/css/fonts/fontawesome-webfont.woff new file mode 100644 index 000000000..400014a4b Binary files /dev/null and b/wiki/css/fonts/fontawesome-webfont.woff differ diff --git a/wiki/css/fonts/fontawesome-webfont.woff2 b/wiki/css/fonts/fontawesome-webfont.woff2 new file mode 100644 index 000000000..4d13fc604 Binary files /dev/null and b/wiki/css/fonts/fontawesome-webfont.woff2 differ diff --git a/wiki/css/fonts/lato-bold-italic.woff b/wiki/css/fonts/lato-bold-italic.woff new file mode 100644 index 000000000..88ad05b9f Binary files /dev/null and b/wiki/css/fonts/lato-bold-italic.woff differ diff --git a/wiki/css/fonts/lato-bold-italic.woff2 b/wiki/css/fonts/lato-bold-italic.woff2 new file mode 100644 index 000000000..c4e3d804b Binary files /dev/null and b/wiki/css/fonts/lato-bold-italic.woff2 differ diff --git a/wiki/css/fonts/lato-bold.woff b/wiki/css/fonts/lato-bold.woff new file mode 100644 index 000000000..c6dff51f0 Binary files /dev/null and b/wiki/css/fonts/lato-bold.woff differ diff --git a/wiki/css/fonts/lato-bold.woff2 b/wiki/css/fonts/lato-bold.woff2 new file mode 100644 index 000000000..bb195043c Binary files /dev/null and b/wiki/css/fonts/lato-bold.woff2 differ diff --git a/wiki/css/fonts/lato-normal-italic.woff b/wiki/css/fonts/lato-normal-italic.woff new file mode 100644 index 000000000..76114bc03 Binary files /dev/null and b/wiki/css/fonts/lato-normal-italic.woff differ diff --git a/wiki/css/fonts/lato-normal-italic.woff2 b/wiki/css/fonts/lato-normal-italic.woff2 new file mode 100644 index 000000000..3404f37e2 Binary files /dev/null and b/wiki/css/fonts/lato-normal-italic.woff2 differ diff --git a/wiki/css/fonts/lato-normal.woff b/wiki/css/fonts/lato-normal.woff new file mode 100644 index 000000000..ae1307ff5 Binary files /dev/null and b/wiki/css/fonts/lato-normal.woff differ diff --git a/wiki/css/fonts/lato-normal.woff2 b/wiki/css/fonts/lato-normal.woff2 new file mode 100644 index 000000000..3bf984332 Binary files /dev/null and b/wiki/css/fonts/lato-normal.woff2 differ diff --git a/wiki/css/theme.css b/wiki/css/theme.css new file mode 100644 index 000000000..ad773009b --- /dev/null +++ b/wiki/css/theme.css @@ -0,0 +1,13 @@ +/* + * This file is copied from the upstream ReadTheDocs Sphinx + * theme. To aid upgradability this file should *not* be edited. + * modifications we need should be included in theme_extra.css. + * + * https://github.com/readthedocs/sphinx_rtd_theme + */ + + /* sphinx_rtd_theme version 1.2.0 | MIT license */ +html{box-sizing:border-box}*,:after,:before{box-sizing:inherit}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden],audio:not([controls]){display:none}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}blockquote{margin:0}dfn{font-style:italic}ins{background:#ff9;text-decoration:none}ins,mark{color:#000}mark{background:#ff0;font-style:italic;font-weight:700}.rst-content code,.rst-content tt,code,kbd,pre,samp{font-family:monospace,serif;_font-family:courier new,monospace;font-size:1em}pre{white-space:pre}q{quotes:none}q:after,q:before{content:"";content:none}small{font-size:85%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}dl,ol,ul{margin:0;padding:0;list-style:none;list-style-image:none}li{list-style:none}dd{margin:0}img{border:0;-ms-interpolation-mode:bicubic;vertical-align:middle;max-width:100%}svg:not(:root){overflow:hidden}figure,form{margin:0}label{cursor:pointer}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,input[type=button],input[type=reset],input[type=submit]{cursor:pointer;-webkit-appearance:button;*overflow:visible}button[disabled],input[disabled]{cursor:default}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}textarea{resize:vertical}table{border-collapse:collapse;border-spacing:0}td{vertical-align:top}.chromeframe{margin:.2em 0;background:#ccc;color:#000;padding:.2em 0}.ir{display:block;border:0;text-indent:-999em;overflow:hidden;background-color:transparent;background-repeat:no-repeat;text-align:left;direction:ltr;*line-height:0}.ir br{display:none}.hidden{display:none!important;visibility:hidden}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.relative{position:relative}big,small{font-size:100%}@media print{body,html,section{background:none!important}*{box-shadow:none!important;text-shadow:none!important;filter:none!important;-ms-filter:none!important}a,a:visited{text-decoration:underline}.ir a:after,a[href^="#"]:after,a[href^="javascript:"]:after{content:""}blockquote,pre{page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}.rst-content .toctree-wrapper>p.caption,h2,h3,p{orphans:3;widows:3}.rst-content .toctree-wrapper>p.caption,h2,h3{page-break-after:avoid}}.btn,.fa:before,.icon:before,.rst-content .admonition,.rst-content .admonition-title:before,.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .code-block-caption .headerlink:before,.rst-content .danger,.rst-content .eqno .headerlink:before,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .note,.rst-content .seealso,.rst-content .tip,.rst-content .warning,.rst-content code.download span:first-child:before,.rst-content dl dt .headerlink:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content p .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content tt.download span:first-child:before,.wy-alert,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-menu-vertical li.current>a button.toctree-expand:before,.wy-menu-vertical li.on a button.toctree-expand:before,.wy-menu-vertical li button.toctree-expand:before,input[type=color],input[type=date],input[type=datetime-local],input[type=datetime],input[type=email],input[type=month],input[type=number],input[type=password],input[type=search],input[type=tel],input[type=text],input[type=time],input[type=url],input[type=week],select,textarea{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:after,.clearfix:before{display:table;content:""}.clearfix:after{clear:both}/*! + * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:FontAwesome;src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713);src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713?#iefix&v=4.7.0) format("embedded-opentype"),url(fonts/fontawesome-webfont.woff2?af7ae505a9eed503f8b8e6982036873e) format("woff2"),url(fonts/fontawesome-webfont.woff?fee66e712a8a08eef5805a46892932ad) format("woff"),url(fonts/fontawesome-webfont.ttf?b06871f281fee6b241d60582ae9369b9) format("truetype"),url(fonts/fontawesome-webfont.svg?912ec66d7572ff821749319396470bde#fontawesomeregular) format("svg");font-weight:400;font-style:normal}.fa,.icon,.rst-content .admonition-title,.rst-content .code-block-caption .headerlink,.rst-content .eqno .headerlink,.rst-content code.download span:first-child,.rst-content dl dt .headerlink,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content p.caption .headerlink,.rst-content p .headerlink,.rst-content table>caption .headerlink,.rst-content tt.download span:first-child,.wy-menu-vertical li.current>a button.toctree-expand,.wy-menu-vertical li.on a button.toctree-expand,.wy-menu-vertical li button.toctree-expand{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14286em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14286em;width:2.14286em;top:.14286em;text-align:center}.fa-li.fa-lg{left:-1.85714em}.fa-border{padding:.2em .25em .15em;border:.08em solid #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa-pull-left.icon,.fa.fa-pull-left,.rst-content .code-block-caption .fa-pull-left.headerlink,.rst-content .eqno .fa-pull-left.headerlink,.rst-content .fa-pull-left.admonition-title,.rst-content code.download span.fa-pull-left:first-child,.rst-content dl dt .fa-pull-left.headerlink,.rst-content h1 .fa-pull-left.headerlink,.rst-content h2 .fa-pull-left.headerlink,.rst-content h3 .fa-pull-left.headerlink,.rst-content h4 .fa-pull-left.headerlink,.rst-content h5 .fa-pull-left.headerlink,.rst-content h6 .fa-pull-left.headerlink,.rst-content p .fa-pull-left.headerlink,.rst-content table>caption .fa-pull-left.headerlink,.rst-content tt.download span.fa-pull-left:first-child,.wy-menu-vertical li.current>a button.fa-pull-left.toctree-expand,.wy-menu-vertical li.on a button.fa-pull-left.toctree-expand,.wy-menu-vertical li button.fa-pull-left.toctree-expand{margin-right:.3em}.fa-pull-right.icon,.fa.fa-pull-right,.rst-content .code-block-caption .fa-pull-right.headerlink,.rst-content .eqno .fa-pull-right.headerlink,.rst-content .fa-pull-right.admonition-title,.rst-content code.download span.fa-pull-right:first-child,.rst-content dl dt .fa-pull-right.headerlink,.rst-content h1 .fa-pull-right.headerlink,.rst-content h2 .fa-pull-right.headerlink,.rst-content h3 .fa-pull-right.headerlink,.rst-content h4 .fa-pull-right.headerlink,.rst-content h5 .fa-pull-right.headerlink,.rst-content h6 .fa-pull-right.headerlink,.rst-content p .fa-pull-right.headerlink,.rst-content table>caption .fa-pull-right.headerlink,.rst-content tt.download span.fa-pull-right:first-child,.wy-menu-vertical li.current>a button.fa-pull-right.toctree-expand,.wy-menu-vertical li.on a button.fa-pull-right.toctree-expand,.wy-menu-vertical li button.fa-pull-right.toctree-expand{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left,.pull-left.icon,.rst-content .code-block-caption .pull-left.headerlink,.rst-content .eqno .pull-left.headerlink,.rst-content .pull-left.admonition-title,.rst-content code.download span.pull-left:first-child,.rst-content dl dt .pull-left.headerlink,.rst-content h1 .pull-left.headerlink,.rst-content h2 .pull-left.headerlink,.rst-content h3 .pull-left.headerlink,.rst-content h4 .pull-left.headerlink,.rst-content h5 .pull-left.headerlink,.rst-content h6 .pull-left.headerlink,.rst-content p .pull-left.headerlink,.rst-content table>caption .pull-left.headerlink,.rst-content tt.download span.pull-left:first-child,.wy-menu-vertical li.current>a button.pull-left.toctree-expand,.wy-menu-vertical li.on a button.pull-left.toctree-expand,.wy-menu-vertical li button.pull-left.toctree-expand{margin-right:.3em}.fa.pull-right,.pull-right.icon,.rst-content .code-block-caption .pull-right.headerlink,.rst-content .eqno .pull-right.headerlink,.rst-content .pull-right.admonition-title,.rst-content code.download span.pull-right:first-child,.rst-content dl dt .pull-right.headerlink,.rst-content h1 .pull-right.headerlink,.rst-content h2 .pull-right.headerlink,.rst-content h3 .pull-right.headerlink,.rst-content h4 .pull-right.headerlink,.rst-content h5 .pull-right.headerlink,.rst-content h6 .pull-right.headerlink,.rst-content p .pull-right.headerlink,.rst-content table>caption .pull-right.headerlink,.rst-content tt.download span.pull-right:first-child,.wy-menu-vertical li.current>a button.pull-right.toctree-expand,.wy-menu-vertical li.on a button.pull-right.toctree-expand,.wy-menu-vertical li button.pull-right.toctree-expand{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s linear infinite;animation:fa-spin 2s linear infinite}.fa-pulse{-webkit-animation:fa-spin 1s steps(8) infinite;animation:fa-spin 1s steps(8) infinite}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scaleX(-1);-ms-transform:scaleX(-1);transform:scaleX(-1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scaleY(-1);-ms-transform:scaleY(-1);transform:scaleY(-1)}:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:""}.fa-music:before{content:""}.fa-search:before,.icon-search:before{content:""}.fa-envelope-o:before{content:""}.fa-heart:before{content:""}.fa-star:before{content:""}.fa-star-o:before{content:""}.fa-user:before{content:""}.fa-film:before{content:""}.fa-th-large:before{content:""}.fa-th:before{content:""}.fa-th-list:before{content:""}.fa-check:before{content:""}.fa-close:before,.fa-remove:before,.fa-times:before{content:""}.fa-search-plus:before{content:""}.fa-search-minus:before{content:""}.fa-power-off:before{content:""}.fa-signal:before{content:""}.fa-cog:before,.fa-gear:before{content:""}.fa-trash-o:before{content:""}.fa-home:before,.icon-home:before{content:""}.fa-file-o:before{content:""}.fa-clock-o:before{content:""}.fa-road:before{content:""}.fa-download:before,.rst-content code.download span:first-child:before,.rst-content tt.download span:first-child:before{content:""}.fa-arrow-circle-o-down:before{content:""}.fa-arrow-circle-o-up:before{content:""}.fa-inbox:before{content:""}.fa-play-circle-o:before{content:""}.fa-repeat:before,.fa-rotate-right:before{content:""}.fa-refresh:before{content:""}.fa-list-alt:before{content:""}.fa-lock:before{content:""}.fa-flag:before{content:""}.fa-headphones:before{content:""}.fa-volume-off:before{content:""}.fa-volume-down:before{content:""}.fa-volume-up:before{content:""}.fa-qrcode:before{content:""}.fa-barcode:before{content:""}.fa-tag:before{content:""}.fa-tags:before{content:""}.fa-book:before,.icon-book:before{content:""}.fa-bookmark:before{content:""}.fa-print:before{content:""}.fa-camera:before{content:""}.fa-font:before{content:""}.fa-bold:before{content:""}.fa-italic:before{content:""}.fa-text-height:before{content:""}.fa-text-width:before{content:""}.fa-align-left:before{content:""}.fa-align-center:before{content:""}.fa-align-right:before{content:""}.fa-align-justify:before{content:""}.fa-list:before{content:""}.fa-dedent:before,.fa-outdent:before{content:""}.fa-indent:before{content:""}.fa-video-camera:before{content:""}.fa-image:before,.fa-photo:before,.fa-picture-o:before{content:""}.fa-pencil:before{content:""}.fa-map-marker:before{content:""}.fa-adjust:before{content:""}.fa-tint:before{content:""}.fa-edit:before,.fa-pencil-square-o:before{content:""}.fa-share-square-o:before{content:""}.fa-check-square-o:before{content:""}.fa-arrows:before{content:""}.fa-step-backward:before{content:""}.fa-fast-backward:before{content:""}.fa-backward:before{content:""}.fa-play:before{content:""}.fa-pause:before{content:""}.fa-stop:before{content:""}.fa-forward:before{content:""}.fa-fast-forward:before{content:""}.fa-step-forward:before{content:""}.fa-eject:before{content:""}.fa-chevron-left:before{content:""}.fa-chevron-right:before{content:""}.fa-plus-circle:before{content:""}.fa-minus-circle:before{content:""}.fa-times-circle:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before{content:""}.fa-check-circle:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before{content:""}.fa-question-circle:before{content:""}.fa-info-circle:before{content:""}.fa-crosshairs:before{content:""}.fa-times-circle-o:before{content:""}.fa-check-circle-o:before{content:""}.fa-ban:before{content:""}.fa-arrow-left:before{content:""}.fa-arrow-right:before{content:""}.fa-arrow-up:before{content:""}.fa-arrow-down:before{content:""}.fa-mail-forward:before,.fa-share:before{content:""}.fa-expand:before{content:""}.fa-compress:before{content:""}.fa-plus:before{content:""}.fa-minus:before{content:""}.fa-asterisk:before{content:""}.fa-exclamation-circle:before,.rst-content .admonition-title:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before{content:""}.fa-gift:before{content:""}.fa-leaf:before{content:""}.fa-fire:before,.icon-fire:before{content:""}.fa-eye:before{content:""}.fa-eye-slash:before{content:""}.fa-exclamation-triangle:before,.fa-warning:before{content:""}.fa-plane:before{content:""}.fa-calendar:before{content:""}.fa-random:before{content:""}.fa-comment:before{content:""}.fa-magnet:before{content:""}.fa-chevron-up:before{content:""}.fa-chevron-down:before{content:""}.fa-retweet:before{content:""}.fa-shopping-cart:before{content:""}.fa-folder:before{content:""}.fa-folder-open:before{content:""}.fa-arrows-v:before{content:""}.fa-arrows-h:before{content:""}.fa-bar-chart-o:before,.fa-bar-chart:before{content:""}.fa-twitter-square:before{content:""}.fa-facebook-square:before{content:""}.fa-camera-retro:before{content:""}.fa-key:before{content:""}.fa-cogs:before,.fa-gears:before{content:""}.fa-comments:before{content:""}.fa-thumbs-o-up:before{content:""}.fa-thumbs-o-down:before{content:""}.fa-star-half:before{content:""}.fa-heart-o:before{content:""}.fa-sign-out:before{content:""}.fa-linkedin-square:before{content:""}.fa-thumb-tack:before{content:""}.fa-external-link:before{content:""}.fa-sign-in:before{content:""}.fa-trophy:before{content:""}.fa-github-square:before{content:""}.fa-upload:before{content:""}.fa-lemon-o:before{content:""}.fa-phone:before{content:""}.fa-square-o:before{content:""}.fa-bookmark-o:before{content:""}.fa-phone-square:before{content:""}.fa-twitter:before{content:""}.fa-facebook-f:before,.fa-facebook:before{content:""}.fa-github:before,.icon-github:before{content:""}.fa-unlock:before{content:""}.fa-credit-card:before{content:""}.fa-feed:before,.fa-rss:before{content:""}.fa-hdd-o:before{content:""}.fa-bullhorn:before{content:""}.fa-bell:before{content:""}.fa-certificate:before{content:""}.fa-hand-o-right:before{content:""}.fa-hand-o-left:before{content:""}.fa-hand-o-up:before{content:""}.fa-hand-o-down:before{content:""}.fa-arrow-circle-left:before,.icon-circle-arrow-left:before{content:""}.fa-arrow-circle-right:before,.icon-circle-arrow-right:before{content:""}.fa-arrow-circle-up:before{content:""}.fa-arrow-circle-down:before{content:""}.fa-globe:before{content:""}.fa-wrench:before{content:""}.fa-tasks:before{content:""}.fa-filter:before{content:""}.fa-briefcase:before{content:""}.fa-arrows-alt:before{content:""}.fa-group:before,.fa-users:before{content:""}.fa-chain:before,.fa-link:before,.icon-link:before{content:""}.fa-cloud:before{content:""}.fa-flask:before{content:""}.fa-cut:before,.fa-scissors:before{content:""}.fa-copy:before,.fa-files-o:before{content:""}.fa-paperclip:before{content:""}.fa-floppy-o:before,.fa-save:before{content:""}.fa-square:before{content:""}.fa-bars:before,.fa-navicon:before,.fa-reorder:before{content:""}.fa-list-ul:before{content:""}.fa-list-ol:before{content:""}.fa-strikethrough:before{content:""}.fa-underline:before{content:""}.fa-table:before{content:""}.fa-magic:before{content:""}.fa-truck:before{content:""}.fa-pinterest:before{content:""}.fa-pinterest-square:before{content:""}.fa-google-plus-square:before{content:""}.fa-google-plus:before{content:""}.fa-money:before{content:""}.fa-caret-down:before,.icon-caret-down:before,.wy-dropdown .caret:before{content:""}.fa-caret-up:before{content:""}.fa-caret-left:before{content:""}.fa-caret-right:before{content:""}.fa-columns:before{content:""}.fa-sort:before,.fa-unsorted:before{content:""}.fa-sort-desc:before,.fa-sort-down:before{content:""}.fa-sort-asc:before,.fa-sort-up:before{content:""}.fa-envelope:before{content:""}.fa-linkedin:before{content:""}.fa-rotate-left:before,.fa-undo:before{content:""}.fa-gavel:before,.fa-legal:before{content:""}.fa-dashboard:before,.fa-tachometer:before{content:""}.fa-comment-o:before{content:""}.fa-comments-o:before{content:""}.fa-bolt:before,.fa-flash:before{content:""}.fa-sitemap:before{content:""}.fa-umbrella:before{content:""}.fa-clipboard:before,.fa-paste:before{content:""}.fa-lightbulb-o:before{content:""}.fa-exchange:before{content:""}.fa-cloud-download:before{content:""}.fa-cloud-upload:before{content:""}.fa-user-md:before{content:""}.fa-stethoscope:before{content:""}.fa-suitcase:before{content:""}.fa-bell-o:before{content:""}.fa-coffee:before{content:""}.fa-cutlery:before{content:""}.fa-file-text-o:before{content:""}.fa-building-o:before{content:""}.fa-hospital-o:before{content:""}.fa-ambulance:before{content:""}.fa-medkit:before{content:""}.fa-fighter-jet:before{content:""}.fa-beer:before{content:""}.fa-h-square:before{content:""}.fa-plus-square:before{content:""}.fa-angle-double-left:before{content:""}.fa-angle-double-right:before{content:""}.fa-angle-double-up:before{content:""}.fa-angle-double-down:before{content:""}.fa-angle-left:before{content:""}.fa-angle-right:before{content:""}.fa-angle-up:before{content:""}.fa-angle-down:before{content:""}.fa-desktop:before{content:""}.fa-laptop:before{content:""}.fa-tablet:before{content:""}.fa-mobile-phone:before,.fa-mobile:before{content:""}.fa-circle-o:before{content:""}.fa-quote-left:before{content:""}.fa-quote-right:before{content:""}.fa-spinner:before{content:""}.fa-circle:before{content:""}.fa-mail-reply:before,.fa-reply:before{content:""}.fa-github-alt:before{content:""}.fa-folder-o:before{content:""}.fa-folder-open-o:before{content:""}.fa-smile-o:before{content:""}.fa-frown-o:before{content:""}.fa-meh-o:before{content:""}.fa-gamepad:before{content:""}.fa-keyboard-o:before{content:""}.fa-flag-o:before{content:""}.fa-flag-checkered:before{content:""}.fa-terminal:before{content:""}.fa-code:before{content:""}.fa-mail-reply-all:before,.fa-reply-all:before{content:""}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:""}.fa-location-arrow:before{content:""}.fa-crop:before{content:""}.fa-code-fork:before{content:""}.fa-chain-broken:before,.fa-unlink:before{content:""}.fa-question:before{content:""}.fa-info:before{content:""}.fa-exclamation:before{content:""}.fa-superscript:before{content:""}.fa-subscript:before{content:""}.fa-eraser:before{content:""}.fa-puzzle-piece:before{content:""}.fa-microphone:before{content:""}.fa-microphone-slash:before{content:""}.fa-shield:before{content:""}.fa-calendar-o:before{content:""}.fa-fire-extinguisher:before{content:""}.fa-rocket:before{content:""}.fa-maxcdn:before{content:""}.fa-chevron-circle-left:before{content:""}.fa-chevron-circle-right:before{content:""}.fa-chevron-circle-up:before{content:""}.fa-chevron-circle-down:before{content:""}.fa-html5:before{content:""}.fa-css3:before{content:""}.fa-anchor:before{content:""}.fa-unlock-alt:before{content:""}.fa-bullseye:before{content:""}.fa-ellipsis-h:before{content:""}.fa-ellipsis-v:before{content:""}.fa-rss-square:before{content:""}.fa-play-circle:before{content:""}.fa-ticket:before{content:""}.fa-minus-square:before{content:""}.fa-minus-square-o:before,.wy-menu-vertical li.current>a button.toctree-expand:before,.wy-menu-vertical li.on a button.toctree-expand:before{content:""}.fa-level-up:before{content:""}.fa-level-down:before{content:""}.fa-check-square:before{content:""}.fa-pencil-square:before{content:""}.fa-external-link-square:before{content:""}.fa-share-square:before{content:""}.fa-compass:before{content:""}.fa-caret-square-o-down:before,.fa-toggle-down:before{content:""}.fa-caret-square-o-up:before,.fa-toggle-up:before{content:""}.fa-caret-square-o-right:before,.fa-toggle-right:before{content:""}.fa-eur:before,.fa-euro:before{content:""}.fa-gbp:before{content:""}.fa-dollar:before,.fa-usd:before{content:""}.fa-inr:before,.fa-rupee:before{content:""}.fa-cny:before,.fa-jpy:before,.fa-rmb:before,.fa-yen:before{content:""}.fa-rouble:before,.fa-rub:before,.fa-ruble:before{content:""}.fa-krw:before,.fa-won:before{content:""}.fa-bitcoin:before,.fa-btc:before{content:""}.fa-file:before{content:""}.fa-file-text:before{content:""}.fa-sort-alpha-asc:before{content:""}.fa-sort-alpha-desc:before{content:""}.fa-sort-amount-asc:before{content:""}.fa-sort-amount-desc:before{content:""}.fa-sort-numeric-asc:before{content:""}.fa-sort-numeric-desc:before{content:""}.fa-thumbs-up:before{content:""}.fa-thumbs-down:before{content:""}.fa-youtube-square:before{content:""}.fa-youtube:before{content:""}.fa-xing:before{content:""}.fa-xing-square:before{content:""}.fa-youtube-play:before{content:""}.fa-dropbox:before{content:""}.fa-stack-overflow:before{content:""}.fa-instagram:before{content:""}.fa-flickr:before{content:""}.fa-adn:before{content:""}.fa-bitbucket:before,.icon-bitbucket:before{content:""}.fa-bitbucket-square:before{content:""}.fa-tumblr:before{content:""}.fa-tumblr-square:before{content:""}.fa-long-arrow-down:before{content:""}.fa-long-arrow-up:before{content:""}.fa-long-arrow-left:before{content:""}.fa-long-arrow-right:before{content:""}.fa-apple:before{content:""}.fa-windows:before{content:""}.fa-android:before{content:""}.fa-linux:before{content:""}.fa-dribbble:before{content:""}.fa-skype:before{content:""}.fa-foursquare:before{content:""}.fa-trello:before{content:""}.fa-female:before{content:""}.fa-male:before{content:""}.fa-gittip:before,.fa-gratipay:before{content:""}.fa-sun-o:before{content:""}.fa-moon-o:before{content:""}.fa-archive:before{content:""}.fa-bug:before{content:""}.fa-vk:before{content:""}.fa-weibo:before{content:""}.fa-renren:before{content:""}.fa-pagelines:before{content:""}.fa-stack-exchange:before{content:""}.fa-arrow-circle-o-right:before{content:""}.fa-arrow-circle-o-left:before{content:""}.fa-caret-square-o-left:before,.fa-toggle-left:before{content:""}.fa-dot-circle-o:before{content:""}.fa-wheelchair:before{content:""}.fa-vimeo-square:before{content:""}.fa-try:before,.fa-turkish-lira:before{content:""}.fa-plus-square-o:before,.wy-menu-vertical li button.toctree-expand:before{content:""}.fa-space-shuttle:before{content:""}.fa-slack:before{content:""}.fa-envelope-square:before{content:""}.fa-wordpress:before{content:""}.fa-openid:before{content:""}.fa-bank:before,.fa-institution:before,.fa-university:before{content:""}.fa-graduation-cap:before,.fa-mortar-board:before{content:""}.fa-yahoo:before{content:""}.fa-google:before{content:""}.fa-reddit:before{content:""}.fa-reddit-square:before{content:""}.fa-stumbleupon-circle:before{content:""}.fa-stumbleupon:before{content:""}.fa-delicious:before{content:""}.fa-digg:before{content:""}.fa-pied-piper-pp:before{content:""}.fa-pied-piper-alt:before{content:""}.fa-drupal:before{content:""}.fa-joomla:before{content:""}.fa-language:before{content:""}.fa-fax:before{content:""}.fa-building:before{content:""}.fa-child:before{content:""}.fa-paw:before{content:""}.fa-spoon:before{content:""}.fa-cube:before{content:""}.fa-cubes:before{content:""}.fa-behance:before{content:""}.fa-behance-square:before{content:""}.fa-steam:before{content:""}.fa-steam-square:before{content:""}.fa-recycle:before{content:""}.fa-automobile:before,.fa-car:before{content:""}.fa-cab:before,.fa-taxi:before{content:""}.fa-tree:before{content:""}.fa-spotify:before{content:""}.fa-deviantart:before{content:""}.fa-soundcloud:before{content:""}.fa-database:before{content:""}.fa-file-pdf-o:before{content:""}.fa-file-word-o:before{content:""}.fa-file-excel-o:before{content:""}.fa-file-powerpoint-o:before{content:""}.fa-file-image-o:before,.fa-file-photo-o:before,.fa-file-picture-o:before{content:""}.fa-file-archive-o:before,.fa-file-zip-o:before{content:""}.fa-file-audio-o:before,.fa-file-sound-o:before{content:""}.fa-file-movie-o:before,.fa-file-video-o:before{content:""}.fa-file-code-o:before{content:""}.fa-vine:before{content:""}.fa-codepen:before{content:""}.fa-jsfiddle:before{content:""}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-ring:before,.fa-life-saver:before,.fa-support:before{content:""}.fa-circle-o-notch:before{content:""}.fa-ra:before,.fa-rebel:before,.fa-resistance:before{content:""}.fa-empire:before,.fa-ge:before{content:""}.fa-git-square:before{content:""}.fa-git:before{content:""}.fa-hacker-news:before,.fa-y-combinator-square:before,.fa-yc-square:before{content:""}.fa-tencent-weibo:before{content:""}.fa-qq:before{content:""}.fa-wechat:before,.fa-weixin:before{content:""}.fa-paper-plane:before,.fa-send:before{content:""}.fa-paper-plane-o:before,.fa-send-o:before{content:""}.fa-history:before{content:""}.fa-circle-thin:before{content:""}.fa-header:before{content:""}.fa-paragraph:before{content:""}.fa-sliders:before{content:""}.fa-share-alt:before{content:""}.fa-share-alt-square:before{content:""}.fa-bomb:before{content:""}.fa-futbol-o:before,.fa-soccer-ball-o:before{content:""}.fa-tty:before{content:""}.fa-binoculars:before{content:""}.fa-plug:before{content:""}.fa-slideshare:before{content:""}.fa-twitch:before{content:""}.fa-yelp:before{content:""}.fa-newspaper-o:before{content:""}.fa-wifi:before{content:""}.fa-calculator:before{content:""}.fa-paypal:before{content:""}.fa-google-wallet:before{content:""}.fa-cc-visa:before{content:""}.fa-cc-mastercard:before{content:""}.fa-cc-discover:before{content:""}.fa-cc-amex:before{content:""}.fa-cc-paypal:before{content:""}.fa-cc-stripe:before{content:""}.fa-bell-slash:before{content:""}.fa-bell-slash-o:before{content:""}.fa-trash:before{content:""}.fa-copyright:before{content:""}.fa-at:before{content:""}.fa-eyedropper:before{content:""}.fa-paint-brush:before{content:""}.fa-birthday-cake:before{content:""}.fa-area-chart:before{content:""}.fa-pie-chart:before{content:""}.fa-line-chart:before{content:""}.fa-lastfm:before{content:""}.fa-lastfm-square:before{content:""}.fa-toggle-off:before{content:""}.fa-toggle-on:before{content:""}.fa-bicycle:before{content:""}.fa-bus:before{content:""}.fa-ioxhost:before{content:""}.fa-angellist:before{content:""}.fa-cc:before{content:""}.fa-ils:before,.fa-shekel:before,.fa-sheqel:before{content:""}.fa-meanpath:before{content:""}.fa-buysellads:before{content:""}.fa-connectdevelop:before{content:""}.fa-dashcube:before{content:""}.fa-forumbee:before{content:""}.fa-leanpub:before{content:""}.fa-sellsy:before{content:""}.fa-shirtsinbulk:before{content:""}.fa-simplybuilt:before{content:""}.fa-skyatlas:before{content:""}.fa-cart-plus:before{content:""}.fa-cart-arrow-down:before{content:""}.fa-diamond:before{content:""}.fa-ship:before{content:""}.fa-user-secret:before{content:""}.fa-motorcycle:before{content:""}.fa-street-view:before{content:""}.fa-heartbeat:before{content:""}.fa-venus:before{content:""}.fa-mars:before{content:""}.fa-mercury:before{content:""}.fa-intersex:before,.fa-transgender:before{content:""}.fa-transgender-alt:before{content:""}.fa-venus-double:before{content:""}.fa-mars-double:before{content:""}.fa-venus-mars:before{content:""}.fa-mars-stroke:before{content:""}.fa-mars-stroke-v:before{content:""}.fa-mars-stroke-h:before{content:""}.fa-neuter:before{content:""}.fa-genderless:before{content:""}.fa-facebook-official:before{content:""}.fa-pinterest-p:before{content:""}.fa-whatsapp:before{content:""}.fa-server:before{content:""}.fa-user-plus:before{content:""}.fa-user-times:before{content:""}.fa-bed:before,.fa-hotel:before{content:""}.fa-viacoin:before{content:""}.fa-train:before{content:""}.fa-subway:before{content:""}.fa-medium:before{content:""}.fa-y-combinator:before,.fa-yc:before{content:""}.fa-optin-monster:before{content:""}.fa-opencart:before{content:""}.fa-expeditedssl:before{content:""}.fa-battery-4:before,.fa-battery-full:before,.fa-battery:before{content:""}.fa-battery-3:before,.fa-battery-three-quarters:before{content:""}.fa-battery-2:before,.fa-battery-half:before{content:""}.fa-battery-1:before,.fa-battery-quarter:before{content:""}.fa-battery-0:before,.fa-battery-empty:before{content:""}.fa-mouse-pointer:before{content:""}.fa-i-cursor:before{content:""}.fa-object-group:before{content:""}.fa-object-ungroup:before{content:""}.fa-sticky-note:before{content:""}.fa-sticky-note-o:before{content:""}.fa-cc-jcb:before{content:""}.fa-cc-diners-club:before{content:""}.fa-clone:before{content:""}.fa-balance-scale:before{content:""}.fa-hourglass-o:before{content:""}.fa-hourglass-1:before,.fa-hourglass-start:before{content:""}.fa-hourglass-2:before,.fa-hourglass-half:before{content:""}.fa-hourglass-3:before,.fa-hourglass-end:before{content:""}.fa-hourglass:before{content:""}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:""}.fa-hand-paper-o:before,.fa-hand-stop-o:before{content:""}.fa-hand-scissors-o:before{content:""}.fa-hand-lizard-o:before{content:""}.fa-hand-spock-o:before{content:""}.fa-hand-pointer-o:before{content:""}.fa-hand-peace-o:before{content:""}.fa-trademark:before{content:""}.fa-registered:before{content:""}.fa-creative-commons:before{content:""}.fa-gg:before{content:""}.fa-gg-circle:before{content:""}.fa-tripadvisor:before{content:""}.fa-odnoklassniki:before{content:""}.fa-odnoklassniki-square:before{content:""}.fa-get-pocket:before{content:""}.fa-wikipedia-w:before{content:""}.fa-safari:before{content:""}.fa-chrome:before{content:""}.fa-firefox:before{content:""}.fa-opera:before{content:""}.fa-internet-explorer:before{content:""}.fa-television:before,.fa-tv:before{content:""}.fa-contao:before{content:""}.fa-500px:before{content:""}.fa-amazon:before{content:""}.fa-calendar-plus-o:before{content:""}.fa-calendar-minus-o:before{content:""}.fa-calendar-times-o:before{content:""}.fa-calendar-check-o:before{content:""}.fa-industry:before{content:""}.fa-map-pin:before{content:""}.fa-map-signs:before{content:""}.fa-map-o:before{content:""}.fa-map:before{content:""}.fa-commenting:before{content:""}.fa-commenting-o:before{content:""}.fa-houzz:before{content:""}.fa-vimeo:before{content:""}.fa-black-tie:before{content:""}.fa-fonticons:before{content:""}.fa-reddit-alien:before{content:""}.fa-edge:before{content:""}.fa-credit-card-alt:before{content:""}.fa-codiepie:before{content:""}.fa-modx:before{content:""}.fa-fort-awesome:before{content:""}.fa-usb:before{content:""}.fa-product-hunt:before{content:""}.fa-mixcloud:before{content:""}.fa-scribd:before{content:""}.fa-pause-circle:before{content:""}.fa-pause-circle-o:before{content:""}.fa-stop-circle:before{content:""}.fa-stop-circle-o:before{content:""}.fa-shopping-bag:before{content:""}.fa-shopping-basket:before{content:""}.fa-hashtag:before{content:""}.fa-bluetooth:before{content:""}.fa-bluetooth-b:before{content:""}.fa-percent:before{content:""}.fa-gitlab:before,.icon-gitlab:before{content:""}.fa-wpbeginner:before{content:""}.fa-wpforms:before{content:""}.fa-envira:before{content:""}.fa-universal-access:before{content:""}.fa-wheelchair-alt:before{content:""}.fa-question-circle-o:before{content:""}.fa-blind:before{content:""}.fa-audio-description:before{content:""}.fa-volume-control-phone:before{content:""}.fa-braille:before{content:""}.fa-assistive-listening-systems:before{content:""}.fa-american-sign-language-interpreting:before,.fa-asl-interpreting:before{content:""}.fa-deaf:before,.fa-deafness:before,.fa-hard-of-hearing:before{content:""}.fa-glide:before{content:""}.fa-glide-g:before{content:""}.fa-sign-language:before,.fa-signing:before{content:""}.fa-low-vision:before{content:""}.fa-viadeo:before{content:""}.fa-viadeo-square:before{content:""}.fa-snapchat:before{content:""}.fa-snapchat-ghost:before{content:""}.fa-snapchat-square:before{content:""}.fa-pied-piper:before{content:""}.fa-first-order:before{content:""}.fa-yoast:before{content:""}.fa-themeisle:before{content:""}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:""}.fa-fa:before,.fa-font-awesome:before{content:""}.fa-handshake-o:before{content:""}.fa-envelope-open:before{content:""}.fa-envelope-open-o:before{content:""}.fa-linode:before{content:""}.fa-address-book:before{content:""}.fa-address-book-o:before{content:""}.fa-address-card:before,.fa-vcard:before{content:""}.fa-address-card-o:before,.fa-vcard-o:before{content:""}.fa-user-circle:before{content:""}.fa-user-circle-o:before{content:""}.fa-user-o:before{content:""}.fa-id-badge:before{content:""}.fa-drivers-license:before,.fa-id-card:before{content:""}.fa-drivers-license-o:before,.fa-id-card-o:before{content:""}.fa-quora:before{content:""}.fa-free-code-camp:before{content:""}.fa-telegram:before{content:""}.fa-thermometer-4:before,.fa-thermometer-full:before,.fa-thermometer:before{content:""}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:""}.fa-thermometer-2:before,.fa-thermometer-half:before{content:""}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:""}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:""}.fa-shower:before{content:""}.fa-bath:before,.fa-bathtub:before,.fa-s15:before{content:""}.fa-podcast:before{content:""}.fa-window-maximize:before{content:""}.fa-window-minimize:before{content:""}.fa-window-restore:before{content:""}.fa-times-rectangle:before,.fa-window-close:before{content:""}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:""}.fa-bandcamp:before{content:""}.fa-grav:before{content:""}.fa-etsy:before{content:""}.fa-imdb:before{content:""}.fa-ravelry:before{content:""}.fa-eercast:before{content:""}.fa-microchip:before{content:""}.fa-snowflake-o:before{content:""}.fa-superpowers:before{content:""}.fa-wpexplorer:before{content:""}.fa-meetup:before{content:""}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}.fa,.icon,.rst-content .admonition-title,.rst-content .code-block-caption .headerlink,.rst-content .eqno .headerlink,.rst-content code.download span:first-child,.rst-content dl dt .headerlink,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content p.caption .headerlink,.rst-content p .headerlink,.rst-content table>caption .headerlink,.rst-content tt.download span:first-child,.wy-dropdown .caret,.wy-inline-validate.wy-inline-validate-danger .wy-input-context,.wy-inline-validate.wy-inline-validate-info .wy-input-context,.wy-inline-validate.wy-inline-validate-success .wy-input-context,.wy-inline-validate.wy-inline-validate-warning .wy-input-context,.wy-menu-vertical li.current>a button.toctree-expand,.wy-menu-vertical li.on a button.toctree-expand,.wy-menu-vertical li button.toctree-expand{font-family:inherit}.fa:before,.icon:before,.rst-content .admonition-title:before,.rst-content .code-block-caption .headerlink:before,.rst-content .eqno .headerlink:before,.rst-content code.download span:first-child:before,.rst-content dl dt .headerlink:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content p .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content tt.download span:first-child:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-menu-vertical li.current>a button.toctree-expand:before,.wy-menu-vertical li.on a button.toctree-expand:before,.wy-menu-vertical li button.toctree-expand:before{font-family:FontAwesome;display:inline-block;font-style:normal;font-weight:400;line-height:1;text-decoration:inherit}.rst-content .code-block-caption a .headerlink,.rst-content .eqno a .headerlink,.rst-content a .admonition-title,.rst-content code.download a span:first-child,.rst-content dl dt a .headerlink,.rst-content h1 a .headerlink,.rst-content h2 a .headerlink,.rst-content h3 a .headerlink,.rst-content h4 a .headerlink,.rst-content h5 a .headerlink,.rst-content h6 a .headerlink,.rst-content p.caption a .headerlink,.rst-content p a .headerlink,.rst-content table>caption a .headerlink,.rst-content tt.download a span:first-child,.wy-menu-vertical li.current>a button.toctree-expand,.wy-menu-vertical li.on a button.toctree-expand,.wy-menu-vertical li a button.toctree-expand,a .fa,a .icon,a .rst-content .admonition-title,a .rst-content .code-block-caption .headerlink,a .rst-content .eqno .headerlink,a .rst-content code.download span:first-child,a .rst-content dl dt .headerlink,a .rst-content h1 .headerlink,a .rst-content h2 .headerlink,a .rst-content h3 .headerlink,a .rst-content h4 .headerlink,a .rst-content h5 .headerlink,a .rst-content h6 .headerlink,a .rst-content p.caption .headerlink,a .rst-content p .headerlink,a .rst-content table>caption .headerlink,a .rst-content tt.download span:first-child,a .wy-menu-vertical li button.toctree-expand{display:inline-block;text-decoration:inherit}.btn .fa,.btn .icon,.btn .rst-content .admonition-title,.btn .rst-content .code-block-caption .headerlink,.btn .rst-content .eqno .headerlink,.btn .rst-content code.download span:first-child,.btn .rst-content dl dt .headerlink,.btn .rst-content h1 .headerlink,.btn .rst-content h2 .headerlink,.btn .rst-content h3 .headerlink,.btn .rst-content h4 .headerlink,.btn .rst-content h5 .headerlink,.btn .rst-content h6 .headerlink,.btn .rst-content p .headerlink,.btn .rst-content table>caption .headerlink,.btn .rst-content tt.download span:first-child,.btn .wy-menu-vertical li.current>a button.toctree-expand,.btn .wy-menu-vertical li.on a button.toctree-expand,.btn .wy-menu-vertical li button.toctree-expand,.nav .fa,.nav .icon,.nav .rst-content .admonition-title,.nav .rst-content .code-block-caption .headerlink,.nav .rst-content .eqno .headerlink,.nav .rst-content code.download span:first-child,.nav .rst-content dl dt .headerlink,.nav .rst-content h1 .headerlink,.nav .rst-content h2 .headerlink,.nav .rst-content h3 .headerlink,.nav .rst-content h4 .headerlink,.nav .rst-content h5 .headerlink,.nav .rst-content h6 .headerlink,.nav .rst-content p .headerlink,.nav .rst-content table>caption .headerlink,.nav .rst-content tt.download span:first-child,.nav .wy-menu-vertical li.current>a button.toctree-expand,.nav .wy-menu-vertical li.on a button.toctree-expand,.nav .wy-menu-vertical li button.toctree-expand,.rst-content .btn .admonition-title,.rst-content .code-block-caption .btn .headerlink,.rst-content .code-block-caption .nav .headerlink,.rst-content .eqno .btn .headerlink,.rst-content .eqno .nav .headerlink,.rst-content .nav .admonition-title,.rst-content code.download .btn span:first-child,.rst-content code.download .nav span:first-child,.rst-content dl dt .btn .headerlink,.rst-content dl dt .nav .headerlink,.rst-content h1 .btn .headerlink,.rst-content h1 .nav .headerlink,.rst-content h2 .btn .headerlink,.rst-content h2 .nav .headerlink,.rst-content h3 .btn .headerlink,.rst-content h3 .nav .headerlink,.rst-content h4 .btn .headerlink,.rst-content h4 .nav .headerlink,.rst-content h5 .btn .headerlink,.rst-content h5 .nav .headerlink,.rst-content h6 .btn .headerlink,.rst-content h6 .nav .headerlink,.rst-content p .btn .headerlink,.rst-content p .nav .headerlink,.rst-content table>caption .btn .headerlink,.rst-content table>caption .nav .headerlink,.rst-content tt.download .btn span:first-child,.rst-content tt.download .nav span:first-child,.wy-menu-vertical li .btn button.toctree-expand,.wy-menu-vertical li.current>a .btn button.toctree-expand,.wy-menu-vertical li.current>a .nav button.toctree-expand,.wy-menu-vertical li .nav button.toctree-expand,.wy-menu-vertical li.on a .btn button.toctree-expand,.wy-menu-vertical li.on a .nav button.toctree-expand{display:inline}.btn .fa-large.icon,.btn .fa.fa-large,.btn .rst-content .code-block-caption .fa-large.headerlink,.btn .rst-content .eqno .fa-large.headerlink,.btn .rst-content .fa-large.admonition-title,.btn .rst-content code.download span.fa-large:first-child,.btn .rst-content dl dt .fa-large.headerlink,.btn .rst-content h1 .fa-large.headerlink,.btn .rst-content h2 .fa-large.headerlink,.btn .rst-content h3 .fa-large.headerlink,.btn .rst-content h4 .fa-large.headerlink,.btn .rst-content h5 .fa-large.headerlink,.btn .rst-content h6 .fa-large.headerlink,.btn .rst-content p .fa-large.headerlink,.btn .rst-content table>caption .fa-large.headerlink,.btn .rst-content tt.download span.fa-large:first-child,.btn .wy-menu-vertical li button.fa-large.toctree-expand,.nav .fa-large.icon,.nav .fa.fa-large,.nav .rst-content .code-block-caption .fa-large.headerlink,.nav .rst-content .eqno .fa-large.headerlink,.nav .rst-content .fa-large.admonition-title,.nav .rst-content code.download span.fa-large:first-child,.nav .rst-content dl dt .fa-large.headerlink,.nav .rst-content h1 .fa-large.headerlink,.nav .rst-content h2 .fa-large.headerlink,.nav .rst-content h3 .fa-large.headerlink,.nav .rst-content h4 .fa-large.headerlink,.nav .rst-content h5 .fa-large.headerlink,.nav .rst-content h6 .fa-large.headerlink,.nav .rst-content p .fa-large.headerlink,.nav .rst-content table>caption .fa-large.headerlink,.nav .rst-content tt.download span.fa-large:first-child,.nav .wy-menu-vertical li button.fa-large.toctree-expand,.rst-content .btn .fa-large.admonition-title,.rst-content .code-block-caption .btn .fa-large.headerlink,.rst-content .code-block-caption .nav .fa-large.headerlink,.rst-content .eqno .btn .fa-large.headerlink,.rst-content .eqno .nav .fa-large.headerlink,.rst-content .nav .fa-large.admonition-title,.rst-content code.download .btn span.fa-large:first-child,.rst-content code.download .nav span.fa-large:first-child,.rst-content dl dt .btn .fa-large.headerlink,.rst-content dl dt .nav .fa-large.headerlink,.rst-content h1 .btn .fa-large.headerlink,.rst-content h1 .nav .fa-large.headerlink,.rst-content h2 .btn .fa-large.headerlink,.rst-content h2 .nav .fa-large.headerlink,.rst-content h3 .btn .fa-large.headerlink,.rst-content h3 .nav .fa-large.headerlink,.rst-content h4 .btn .fa-large.headerlink,.rst-content h4 .nav .fa-large.headerlink,.rst-content h5 .btn .fa-large.headerlink,.rst-content h5 .nav .fa-large.headerlink,.rst-content h6 .btn .fa-large.headerlink,.rst-content h6 .nav .fa-large.headerlink,.rst-content p .btn .fa-large.headerlink,.rst-content p .nav .fa-large.headerlink,.rst-content table>caption .btn .fa-large.headerlink,.rst-content table>caption .nav .fa-large.headerlink,.rst-content tt.download .btn span.fa-large:first-child,.rst-content tt.download .nav span.fa-large:first-child,.wy-menu-vertical li .btn button.fa-large.toctree-expand,.wy-menu-vertical li .nav button.fa-large.toctree-expand{line-height:.9em}.btn .fa-spin.icon,.btn .fa.fa-spin,.btn .rst-content .code-block-caption .fa-spin.headerlink,.btn .rst-content .eqno .fa-spin.headerlink,.btn .rst-content .fa-spin.admonition-title,.btn .rst-content code.download span.fa-spin:first-child,.btn .rst-content dl dt .fa-spin.headerlink,.btn .rst-content h1 .fa-spin.headerlink,.btn .rst-content h2 .fa-spin.headerlink,.btn .rst-content h3 .fa-spin.headerlink,.btn .rst-content h4 .fa-spin.headerlink,.btn .rst-content h5 .fa-spin.headerlink,.btn .rst-content h6 .fa-spin.headerlink,.btn .rst-content p .fa-spin.headerlink,.btn .rst-content table>caption .fa-spin.headerlink,.btn .rst-content tt.download span.fa-spin:first-child,.btn .wy-menu-vertical li button.fa-spin.toctree-expand,.nav .fa-spin.icon,.nav .fa.fa-spin,.nav .rst-content .code-block-caption .fa-spin.headerlink,.nav .rst-content .eqno .fa-spin.headerlink,.nav .rst-content .fa-spin.admonition-title,.nav .rst-content code.download span.fa-spin:first-child,.nav .rst-content dl dt .fa-spin.headerlink,.nav .rst-content h1 .fa-spin.headerlink,.nav .rst-content h2 .fa-spin.headerlink,.nav .rst-content h3 .fa-spin.headerlink,.nav .rst-content h4 .fa-spin.headerlink,.nav .rst-content h5 .fa-spin.headerlink,.nav .rst-content h6 .fa-spin.headerlink,.nav .rst-content p .fa-spin.headerlink,.nav .rst-content table>caption .fa-spin.headerlink,.nav .rst-content tt.download span.fa-spin:first-child,.nav .wy-menu-vertical li button.fa-spin.toctree-expand,.rst-content .btn .fa-spin.admonition-title,.rst-content .code-block-caption .btn .fa-spin.headerlink,.rst-content .code-block-caption .nav .fa-spin.headerlink,.rst-content .eqno .btn .fa-spin.headerlink,.rst-content .eqno .nav .fa-spin.headerlink,.rst-content .nav .fa-spin.admonition-title,.rst-content code.download .btn span.fa-spin:first-child,.rst-content code.download .nav span.fa-spin:first-child,.rst-content dl dt .btn .fa-spin.headerlink,.rst-content dl dt .nav .fa-spin.headerlink,.rst-content h1 .btn .fa-spin.headerlink,.rst-content h1 .nav .fa-spin.headerlink,.rst-content h2 .btn .fa-spin.headerlink,.rst-content h2 .nav .fa-spin.headerlink,.rst-content h3 .btn .fa-spin.headerlink,.rst-content h3 .nav .fa-spin.headerlink,.rst-content h4 .btn .fa-spin.headerlink,.rst-content h4 .nav .fa-spin.headerlink,.rst-content h5 .btn .fa-spin.headerlink,.rst-content h5 .nav .fa-spin.headerlink,.rst-content h6 .btn .fa-spin.headerlink,.rst-content h6 .nav .fa-spin.headerlink,.rst-content p .btn .fa-spin.headerlink,.rst-content p .nav .fa-spin.headerlink,.rst-content table>caption .btn .fa-spin.headerlink,.rst-content table>caption .nav .fa-spin.headerlink,.rst-content tt.download .btn span.fa-spin:first-child,.rst-content tt.download .nav span.fa-spin:first-child,.wy-menu-vertical li .btn button.fa-spin.toctree-expand,.wy-menu-vertical li .nav button.fa-spin.toctree-expand{display:inline-block}.btn.fa:before,.btn.icon:before,.rst-content .btn.admonition-title:before,.rst-content .code-block-caption .btn.headerlink:before,.rst-content .eqno .btn.headerlink:before,.rst-content code.download span.btn:first-child:before,.rst-content dl dt .btn.headerlink:before,.rst-content h1 .btn.headerlink:before,.rst-content h2 .btn.headerlink:before,.rst-content h3 .btn.headerlink:before,.rst-content h4 .btn.headerlink:before,.rst-content h5 .btn.headerlink:before,.rst-content h6 .btn.headerlink:before,.rst-content p .btn.headerlink:before,.rst-content table>caption .btn.headerlink:before,.rst-content tt.download span.btn:first-child:before,.wy-menu-vertical li button.btn.toctree-expand:before{opacity:.5;-webkit-transition:opacity .05s ease-in;-moz-transition:opacity .05s ease-in;transition:opacity .05s ease-in}.btn.fa:hover:before,.btn.icon:hover:before,.rst-content .btn.admonition-title:hover:before,.rst-content .code-block-caption .btn.headerlink:hover:before,.rst-content .eqno .btn.headerlink:hover:before,.rst-content code.download span.btn:first-child:hover:before,.rst-content dl dt .btn.headerlink:hover:before,.rst-content h1 .btn.headerlink:hover:before,.rst-content h2 .btn.headerlink:hover:before,.rst-content h3 .btn.headerlink:hover:before,.rst-content h4 .btn.headerlink:hover:before,.rst-content h5 .btn.headerlink:hover:before,.rst-content h6 .btn.headerlink:hover:before,.rst-content p .btn.headerlink:hover:before,.rst-content table>caption .btn.headerlink:hover:before,.rst-content tt.download span.btn:first-child:hover:before,.wy-menu-vertical li button.btn.toctree-expand:hover:before{opacity:1}.btn-mini .fa:before,.btn-mini .icon:before,.btn-mini .rst-content .admonition-title:before,.btn-mini .rst-content .code-block-caption .headerlink:before,.btn-mini .rst-content .eqno .headerlink:before,.btn-mini .rst-content code.download span:first-child:before,.btn-mini .rst-content dl dt .headerlink:before,.btn-mini .rst-content h1 .headerlink:before,.btn-mini .rst-content h2 .headerlink:before,.btn-mini .rst-content h3 .headerlink:before,.btn-mini .rst-content h4 .headerlink:before,.btn-mini .rst-content h5 .headerlink:before,.btn-mini .rst-content h6 .headerlink:before,.btn-mini .rst-content p .headerlink:before,.btn-mini .rst-content table>caption .headerlink:before,.btn-mini .rst-content tt.download span:first-child:before,.btn-mini .wy-menu-vertical li button.toctree-expand:before,.rst-content .btn-mini .admonition-title:before,.rst-content .code-block-caption .btn-mini .headerlink:before,.rst-content .eqno .btn-mini .headerlink:before,.rst-content code.download .btn-mini span:first-child:before,.rst-content dl dt .btn-mini .headerlink:before,.rst-content h1 .btn-mini .headerlink:before,.rst-content h2 .btn-mini .headerlink:before,.rst-content h3 .btn-mini .headerlink:before,.rst-content h4 .btn-mini .headerlink:before,.rst-content h5 .btn-mini .headerlink:before,.rst-content h6 .btn-mini .headerlink:before,.rst-content p .btn-mini .headerlink:before,.rst-content table>caption .btn-mini .headerlink:before,.rst-content tt.download .btn-mini span:first-child:before,.wy-menu-vertical li .btn-mini button.toctree-expand:before{font-size:14px;vertical-align:-15%}.rst-content .admonition,.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .note,.rst-content .seealso,.rst-content .tip,.rst-content .warning,.wy-alert{padding:12px;line-height:24px;margin-bottom:24px;background:#e7f2fa}.rst-content .admonition-title,.wy-alert-title{font-weight:700;display:block;color:#fff;background:#6ab0de;padding:6px 12px;margin:-12px -12px 12px}.rst-content .danger,.rst-content .error,.rst-content .wy-alert-danger.admonition,.rst-content .wy-alert-danger.admonition-todo,.rst-content .wy-alert-danger.attention,.rst-content .wy-alert-danger.caution,.rst-content .wy-alert-danger.hint,.rst-content .wy-alert-danger.important,.rst-content .wy-alert-danger.note,.rst-content .wy-alert-danger.seealso,.rst-content .wy-alert-danger.tip,.rst-content .wy-alert-danger.warning,.wy-alert.wy-alert-danger{background:#fdf3f2}.rst-content .danger .admonition-title,.rst-content .danger .wy-alert-title,.rst-content .error .admonition-title,.rst-content .error .wy-alert-title,.rst-content .wy-alert-danger.admonition-todo .admonition-title,.rst-content .wy-alert-danger.admonition-todo .wy-alert-title,.rst-content .wy-alert-danger.admonition .admonition-title,.rst-content .wy-alert-danger.admonition .wy-alert-title,.rst-content .wy-alert-danger.attention .admonition-title,.rst-content .wy-alert-danger.attention .wy-alert-title,.rst-content .wy-alert-danger.caution .admonition-title,.rst-content .wy-alert-danger.caution .wy-alert-title,.rst-content .wy-alert-danger.hint .admonition-title,.rst-content .wy-alert-danger.hint .wy-alert-title,.rst-content .wy-alert-danger.important .admonition-title,.rst-content .wy-alert-danger.important .wy-alert-title,.rst-content .wy-alert-danger.note .admonition-title,.rst-content .wy-alert-danger.note .wy-alert-title,.rst-content .wy-alert-danger.seealso .admonition-title,.rst-content .wy-alert-danger.seealso .wy-alert-title,.rst-content .wy-alert-danger.tip .admonition-title,.rst-content .wy-alert-danger.tip .wy-alert-title,.rst-content .wy-alert-danger.warning .admonition-title,.rst-content .wy-alert-danger.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-danger .admonition-title,.wy-alert.wy-alert-danger .rst-content .admonition-title,.wy-alert.wy-alert-danger .wy-alert-title{background:#f29f97}.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .warning,.rst-content .wy-alert-warning.admonition,.rst-content .wy-alert-warning.danger,.rst-content .wy-alert-warning.error,.rst-content .wy-alert-warning.hint,.rst-content .wy-alert-warning.important,.rst-content .wy-alert-warning.note,.rst-content .wy-alert-warning.seealso,.rst-content .wy-alert-warning.tip,.wy-alert.wy-alert-warning{background:#ffedcc}.rst-content .admonition-todo .admonition-title,.rst-content .admonition-todo .wy-alert-title,.rst-content .attention .admonition-title,.rst-content .attention .wy-alert-title,.rst-content .caution .admonition-title,.rst-content .caution .wy-alert-title,.rst-content .warning .admonition-title,.rst-content .warning .wy-alert-title,.rst-content .wy-alert-warning.admonition .admonition-title,.rst-content .wy-alert-warning.admonition .wy-alert-title,.rst-content .wy-alert-warning.danger .admonition-title,.rst-content .wy-alert-warning.danger .wy-alert-title,.rst-content .wy-alert-warning.error .admonition-title,.rst-content .wy-alert-warning.error .wy-alert-title,.rst-content .wy-alert-warning.hint .admonition-title,.rst-content .wy-alert-warning.hint .wy-alert-title,.rst-content .wy-alert-warning.important .admonition-title,.rst-content .wy-alert-warning.important .wy-alert-title,.rst-content .wy-alert-warning.note .admonition-title,.rst-content .wy-alert-warning.note .wy-alert-title,.rst-content .wy-alert-warning.seealso .admonition-title,.rst-content .wy-alert-warning.seealso .wy-alert-title,.rst-content .wy-alert-warning.tip .admonition-title,.rst-content .wy-alert-warning.tip .wy-alert-title,.rst-content .wy-alert.wy-alert-warning .admonition-title,.wy-alert.wy-alert-warning .rst-content .admonition-title,.wy-alert.wy-alert-warning .wy-alert-title{background:#f0b37e}.rst-content .note,.rst-content .seealso,.rst-content .wy-alert-info.admonition,.rst-content .wy-alert-info.admonition-todo,.rst-content .wy-alert-info.attention,.rst-content .wy-alert-info.caution,.rst-content .wy-alert-info.danger,.rst-content .wy-alert-info.error,.rst-content .wy-alert-info.hint,.rst-content .wy-alert-info.important,.rst-content .wy-alert-info.tip,.rst-content .wy-alert-info.warning,.wy-alert.wy-alert-info{background:#e7f2fa}.rst-content .note .admonition-title,.rst-content .note .wy-alert-title,.rst-content .seealso .admonition-title,.rst-content .seealso .wy-alert-title,.rst-content .wy-alert-info.admonition-todo .admonition-title,.rst-content .wy-alert-info.admonition-todo .wy-alert-title,.rst-content .wy-alert-info.admonition .admonition-title,.rst-content .wy-alert-info.admonition .wy-alert-title,.rst-content .wy-alert-info.attention .admonition-title,.rst-content .wy-alert-info.attention .wy-alert-title,.rst-content .wy-alert-info.caution .admonition-title,.rst-content .wy-alert-info.caution .wy-alert-title,.rst-content .wy-alert-info.danger .admonition-title,.rst-content .wy-alert-info.danger .wy-alert-title,.rst-content .wy-alert-info.error .admonition-title,.rst-content .wy-alert-info.error .wy-alert-title,.rst-content .wy-alert-info.hint .admonition-title,.rst-content .wy-alert-info.hint .wy-alert-title,.rst-content .wy-alert-info.important .admonition-title,.rst-content .wy-alert-info.important .wy-alert-title,.rst-content .wy-alert-info.tip .admonition-title,.rst-content .wy-alert-info.tip .wy-alert-title,.rst-content .wy-alert-info.warning .admonition-title,.rst-content .wy-alert-info.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-info .admonition-title,.wy-alert.wy-alert-info .rst-content .admonition-title,.wy-alert.wy-alert-info .wy-alert-title{background:#6ab0de}.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .wy-alert-success.admonition,.rst-content .wy-alert-success.admonition-todo,.rst-content .wy-alert-success.attention,.rst-content .wy-alert-success.caution,.rst-content .wy-alert-success.danger,.rst-content .wy-alert-success.error,.rst-content .wy-alert-success.note,.rst-content .wy-alert-success.seealso,.rst-content .wy-alert-success.warning,.wy-alert.wy-alert-success{background:#dbfaf4}.rst-content .hint .admonition-title,.rst-content .hint .wy-alert-title,.rst-content .important .admonition-title,.rst-content .important .wy-alert-title,.rst-content .tip .admonition-title,.rst-content .tip .wy-alert-title,.rst-content .wy-alert-success.admonition-todo .admonition-title,.rst-content .wy-alert-success.admonition-todo .wy-alert-title,.rst-content .wy-alert-success.admonition .admonition-title,.rst-content .wy-alert-success.admonition .wy-alert-title,.rst-content .wy-alert-success.attention .admonition-title,.rst-content .wy-alert-success.attention .wy-alert-title,.rst-content .wy-alert-success.caution .admonition-title,.rst-content .wy-alert-success.caution .wy-alert-title,.rst-content .wy-alert-success.danger .admonition-title,.rst-content .wy-alert-success.danger .wy-alert-title,.rst-content .wy-alert-success.error .admonition-title,.rst-content .wy-alert-success.error .wy-alert-title,.rst-content .wy-alert-success.note .admonition-title,.rst-content .wy-alert-success.note .wy-alert-title,.rst-content .wy-alert-success.seealso .admonition-title,.rst-content .wy-alert-success.seealso .wy-alert-title,.rst-content .wy-alert-success.warning .admonition-title,.rst-content .wy-alert-success.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-success .admonition-title,.wy-alert.wy-alert-success .rst-content .admonition-title,.wy-alert.wy-alert-success .wy-alert-title{background:#1abc9c}.rst-content .wy-alert-neutral.admonition,.rst-content .wy-alert-neutral.admonition-todo,.rst-content .wy-alert-neutral.attention,.rst-content .wy-alert-neutral.caution,.rst-content .wy-alert-neutral.danger,.rst-content .wy-alert-neutral.error,.rst-content .wy-alert-neutral.hint,.rst-content .wy-alert-neutral.important,.rst-content .wy-alert-neutral.note,.rst-content .wy-alert-neutral.seealso,.rst-content .wy-alert-neutral.tip,.rst-content .wy-alert-neutral.warning,.wy-alert.wy-alert-neutral{background:#f3f6f6}.rst-content .wy-alert-neutral.admonition-todo .admonition-title,.rst-content .wy-alert-neutral.admonition-todo .wy-alert-title,.rst-content .wy-alert-neutral.admonition .admonition-title,.rst-content .wy-alert-neutral.admonition .wy-alert-title,.rst-content .wy-alert-neutral.attention .admonition-title,.rst-content .wy-alert-neutral.attention .wy-alert-title,.rst-content .wy-alert-neutral.caution .admonition-title,.rst-content .wy-alert-neutral.caution .wy-alert-title,.rst-content .wy-alert-neutral.danger .admonition-title,.rst-content .wy-alert-neutral.danger .wy-alert-title,.rst-content .wy-alert-neutral.error .admonition-title,.rst-content .wy-alert-neutral.error .wy-alert-title,.rst-content .wy-alert-neutral.hint .admonition-title,.rst-content .wy-alert-neutral.hint .wy-alert-title,.rst-content .wy-alert-neutral.important .admonition-title,.rst-content .wy-alert-neutral.important .wy-alert-title,.rst-content .wy-alert-neutral.note .admonition-title,.rst-content .wy-alert-neutral.note .wy-alert-title,.rst-content .wy-alert-neutral.seealso .admonition-title,.rst-content .wy-alert-neutral.seealso .wy-alert-title,.rst-content .wy-alert-neutral.tip .admonition-title,.rst-content .wy-alert-neutral.tip .wy-alert-title,.rst-content .wy-alert-neutral.warning .admonition-title,.rst-content .wy-alert-neutral.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-neutral .admonition-title,.wy-alert.wy-alert-neutral .rst-content .admonition-title,.wy-alert.wy-alert-neutral .wy-alert-title{color:#404040;background:#e1e4e5}.rst-content .wy-alert-neutral.admonition-todo a,.rst-content .wy-alert-neutral.admonition a,.rst-content .wy-alert-neutral.attention a,.rst-content .wy-alert-neutral.caution a,.rst-content .wy-alert-neutral.danger a,.rst-content .wy-alert-neutral.error a,.rst-content .wy-alert-neutral.hint a,.rst-content .wy-alert-neutral.important a,.rst-content .wy-alert-neutral.note a,.rst-content .wy-alert-neutral.seealso a,.rst-content .wy-alert-neutral.tip a,.rst-content .wy-alert-neutral.warning a,.wy-alert.wy-alert-neutral a{color:#2980b9}.rst-content .admonition-todo p:last-child,.rst-content .admonition p:last-child,.rst-content .attention p:last-child,.rst-content .caution p:last-child,.rst-content .danger p:last-child,.rst-content .error p:last-child,.rst-content .hint p:last-child,.rst-content .important p:last-child,.rst-content .note p:last-child,.rst-content .seealso p:last-child,.rst-content .tip p:last-child,.rst-content .warning p:last-child,.wy-alert p:last-child{margin-bottom:0}.wy-tray-container{position:fixed;bottom:0;left:0;z-index:600}.wy-tray-container li{display:block;width:300px;background:transparent;color:#fff;text-align:center;box-shadow:0 5px 5px 0 rgba(0,0,0,.1);padding:0 24px;min-width:20%;opacity:0;height:0;line-height:56px;overflow:hidden;-webkit-transition:all .3s ease-in;-moz-transition:all .3s ease-in;transition:all .3s ease-in}.wy-tray-container li.wy-tray-item-success{background:#27ae60}.wy-tray-container li.wy-tray-item-info{background:#2980b9}.wy-tray-container li.wy-tray-item-warning{background:#e67e22}.wy-tray-container li.wy-tray-item-danger{background:#e74c3c}.wy-tray-container li.on{opacity:1;height:56px}@media screen and (max-width:768px){.wy-tray-container{bottom:auto;top:0;width:100%}.wy-tray-container li{width:100%}}button{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle;cursor:pointer;line-height:normal;-webkit-appearance:button;*overflow:visible}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}button[disabled]{cursor:default}.btn{display:inline-block;border-radius:2px;line-height:normal;white-space:nowrap;text-align:center;cursor:pointer;font-size:100%;padding:6px 12px 8px;color:#fff;border:1px solid rgba(0,0,0,.1);background-color:#27ae60;text-decoration:none;font-weight:400;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;box-shadow:inset 0 1px 2px -1px hsla(0,0%,100%,.5),inset 0 -2px 0 0 rgba(0,0,0,.1);outline-none:false;vertical-align:middle;*display:inline;zoom:1;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-transition:all .1s linear;-moz-transition:all .1s linear;transition:all .1s linear}.btn-hover{background:#2e8ece;color:#fff}.btn:hover{background:#2cc36b;color:#fff}.btn:focus{background:#2cc36b;outline:0}.btn:active{box-shadow:inset 0 -1px 0 0 rgba(0,0,0,.05),inset 0 2px 0 0 rgba(0,0,0,.1);padding:8px 12px 6px}.btn:visited{color:#fff}.btn-disabled,.btn-disabled:active,.btn-disabled:focus,.btn-disabled:hover,.btn:disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn::-moz-focus-inner{padding:0;border:0}.btn-small{font-size:80%}.btn-info{background-color:#2980b9!important}.btn-info:hover{background-color:#2e8ece!important}.btn-neutral{background-color:#f3f6f6!important;color:#404040!important}.btn-neutral:hover{background-color:#e5ebeb!important;color:#404040}.btn-neutral:visited{color:#404040!important}.btn-success{background-color:#27ae60!important}.btn-success:hover{background-color:#295!important}.btn-danger{background-color:#e74c3c!important}.btn-danger:hover{background-color:#ea6153!important}.btn-warning{background-color:#e67e22!important}.btn-warning:hover{background-color:#e98b39!important}.btn-invert{background-color:#222}.btn-invert:hover{background-color:#2f2f2f!important}.btn-link{background-color:transparent!important;color:#2980b9;box-shadow:none;border-color:transparent!important}.btn-link:active,.btn-link:hover{background-color:transparent!important;color:#409ad5!important;box-shadow:none}.btn-link:visited{color:#9b59b6}.wy-btn-group .btn,.wy-control .btn{vertical-align:middle}.wy-btn-group{margin-bottom:24px;*zoom:1}.wy-btn-group:after,.wy-btn-group:before{display:table;content:""}.wy-btn-group:after{clear:both}.wy-dropdown{position:relative;display:inline-block}.wy-dropdown-active .wy-dropdown-menu{display:block}.wy-dropdown-menu{position:absolute;left:0;display:none;float:left;top:100%;min-width:100%;background:#fcfcfc;z-index:100;border:1px solid #cfd7dd;box-shadow:0 2px 2px 0 rgba(0,0,0,.1);padding:12px}.wy-dropdown-menu>dd>a{display:block;clear:both;color:#404040;white-space:nowrap;font-size:90%;padding:0 12px;cursor:pointer}.wy-dropdown-menu>dd>a:hover{background:#2980b9;color:#fff}.wy-dropdown-menu>dd.divider{border-top:1px solid #cfd7dd;margin:6px 0}.wy-dropdown-menu>dd.search{padding-bottom:12px}.wy-dropdown-menu>dd.search input[type=search]{width:100%}.wy-dropdown-menu>dd.call-to-action{background:#e3e3e3;text-transform:uppercase;font-weight:500;font-size:80%}.wy-dropdown-menu>dd.call-to-action:hover{background:#e3e3e3}.wy-dropdown-menu>dd.call-to-action .btn{color:#fff}.wy-dropdown.wy-dropdown-up .wy-dropdown-menu{bottom:100%;top:auto;left:auto;right:0}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu{background:#fcfcfc;margin-top:2px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a{padding:6px 12px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a:hover{background:#2980b9;color:#fff}.wy-dropdown.wy-dropdown-left .wy-dropdown-menu{right:0;left:auto;text-align:right}.wy-dropdown-arrow:before{content:" ";border-bottom:5px solid #f5f5f5;border-left:5px solid transparent;border-right:5px solid transparent;position:absolute;display:block;top:-4px;left:50%;margin-left:-3px}.wy-dropdown-arrow.wy-dropdown-arrow-left:before{left:11px}.wy-form-stacked select{display:block}.wy-form-aligned .wy-help-inline,.wy-form-aligned input,.wy-form-aligned label,.wy-form-aligned select,.wy-form-aligned textarea{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-form-aligned .wy-control-group>label{display:inline-block;vertical-align:middle;width:10em;margin:6px 12px 0 0;float:left}.wy-form-aligned .wy-control{float:left}.wy-form-aligned .wy-control label{display:block}.wy-form-aligned .wy-control select{margin-top:6px}fieldset{margin:0}fieldset,legend{border:0;padding:0}legend{width:100%;white-space:normal;margin-bottom:24px;font-size:150%;*margin-left:-7px}label,legend{display:block}label{margin:0 0 .3125em;color:#333;font-size:90%}input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}.wy-control-group{margin-bottom:24px;max-width:1200px;margin-left:auto;margin-right:auto;*zoom:1}.wy-control-group:after,.wy-control-group:before{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group.wy-control-group-required>label:after{content:" *";color:#e74c3c}.wy-control-group .wy-form-full,.wy-control-group .wy-form-halves,.wy-control-group .wy-form-thirds{padding-bottom:12px}.wy-control-group .wy-form-full input[type=color],.wy-control-group .wy-form-full input[type=date],.wy-control-group .wy-form-full input[type=datetime-local],.wy-control-group .wy-form-full input[type=datetime],.wy-control-group .wy-form-full input[type=email],.wy-control-group .wy-form-full input[type=month],.wy-control-group .wy-form-full input[type=number],.wy-control-group .wy-form-full input[type=password],.wy-control-group .wy-form-full input[type=search],.wy-control-group .wy-form-full input[type=tel],.wy-control-group .wy-form-full input[type=text],.wy-control-group .wy-form-full input[type=time],.wy-control-group .wy-form-full input[type=url],.wy-control-group .wy-form-full input[type=week],.wy-control-group .wy-form-full select,.wy-control-group .wy-form-halves input[type=color],.wy-control-group .wy-form-halves input[type=date],.wy-control-group .wy-form-halves input[type=datetime-local],.wy-control-group .wy-form-halves input[type=datetime],.wy-control-group .wy-form-halves input[type=email],.wy-control-group .wy-form-halves input[type=month],.wy-control-group .wy-form-halves input[type=number],.wy-control-group .wy-form-halves input[type=password],.wy-control-group .wy-form-halves input[type=search],.wy-control-group .wy-form-halves input[type=tel],.wy-control-group .wy-form-halves input[type=text],.wy-control-group .wy-form-halves input[type=time],.wy-control-group .wy-form-halves input[type=url],.wy-control-group .wy-form-halves input[type=week],.wy-control-group .wy-form-halves select,.wy-control-group .wy-form-thirds input[type=color],.wy-control-group .wy-form-thirds input[type=date],.wy-control-group .wy-form-thirds input[type=datetime-local],.wy-control-group .wy-form-thirds input[type=datetime],.wy-control-group .wy-form-thirds input[type=email],.wy-control-group .wy-form-thirds input[type=month],.wy-control-group .wy-form-thirds input[type=number],.wy-control-group .wy-form-thirds input[type=password],.wy-control-group .wy-form-thirds input[type=search],.wy-control-group .wy-form-thirds input[type=tel],.wy-control-group .wy-form-thirds input[type=text],.wy-control-group .wy-form-thirds input[type=time],.wy-control-group .wy-form-thirds input[type=url],.wy-control-group .wy-form-thirds input[type=week],.wy-control-group .wy-form-thirds select{width:100%}.wy-control-group .wy-form-full{float:left;display:block;width:100%;margin-right:0}.wy-control-group .wy-form-full:last-child{margin-right:0}.wy-control-group .wy-form-halves{float:left;display:block;margin-right:2.35765%;width:48.82117%}.wy-control-group .wy-form-halves:last-child,.wy-control-group .wy-form-halves:nth-of-type(2n){margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(odd){clear:left}.wy-control-group .wy-form-thirds{float:left;display:block;margin-right:2.35765%;width:31.76157%}.wy-control-group .wy-form-thirds:last-child,.wy-control-group .wy-form-thirds:nth-of-type(3n){margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n+1){clear:left}.wy-control-group.wy-control-group-no-input .wy-control,.wy-control-no-input{margin:6px 0 0;font-size:90%}.wy-control-no-input{display:inline-block}.wy-control-group.fluid-input input[type=color],.wy-control-group.fluid-input input[type=date],.wy-control-group.fluid-input input[type=datetime-local],.wy-control-group.fluid-input input[type=datetime],.wy-control-group.fluid-input input[type=email],.wy-control-group.fluid-input input[type=month],.wy-control-group.fluid-input input[type=number],.wy-control-group.fluid-input input[type=password],.wy-control-group.fluid-input input[type=search],.wy-control-group.fluid-input input[type=tel],.wy-control-group.fluid-input input[type=text],.wy-control-group.fluid-input input[type=time],.wy-control-group.fluid-input input[type=url],.wy-control-group.fluid-input input[type=week]{width:100%}.wy-form-message-inline{padding-left:.3em;color:#666;font-size:90%}.wy-form-message{display:block;color:#999;font-size:70%;margin-top:.3125em;font-style:italic}.wy-form-message p{font-size:inherit;font-style:italic;margin-bottom:6px}.wy-form-message p:last-child{margin-bottom:0}input{line-height:normal}input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;*overflow:visible}input[type=color],input[type=date],input[type=datetime-local],input[type=datetime],input[type=email],input[type=month],input[type=number],input[type=password],input[type=search],input[type=tel],input[type=text],input[type=time],input[type=url],input[type=week]{-webkit-appearance:none;padding:6px;display:inline-block;border:1px solid #ccc;font-size:80%;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;box-shadow:inset 0 1px 3px #ddd;border-radius:0;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}input[type=datetime-local]{padding:.34375em .625em}input[disabled]{cursor:default}input[type=checkbox],input[type=radio]{padding:0;margin-right:.3125em;*height:13px;*width:13px}input[type=checkbox],input[type=radio],input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}input[type=color]:focus,input[type=date]:focus,input[type=datetime-local]:focus,input[type=datetime]:focus,input[type=email]:focus,input[type=month]:focus,input[type=number]:focus,input[type=password]:focus,input[type=search]:focus,input[type=tel]:focus,input[type=text]:focus,input[type=time]:focus,input[type=url]:focus,input[type=week]:focus{outline:0;outline:thin dotted\9;border-color:#333}input.no-focus:focus{border-color:#ccc!important}input[type=checkbox]:focus,input[type=file]:focus,input[type=radio]:focus{outline:thin dotted #333;outline:1px auto #129fea}input[type=color][disabled],input[type=date][disabled],input[type=datetime-local][disabled],input[type=datetime][disabled],input[type=email][disabled],input[type=month][disabled],input[type=number][disabled],input[type=password][disabled],input[type=search][disabled],input[type=tel][disabled],input[type=text][disabled],input[type=time][disabled],input[type=url][disabled],input[type=week][disabled]{cursor:not-allowed;background-color:#fafafa}input:focus:invalid,select:focus:invalid,textarea:focus:invalid{color:#e74c3c;border:1px solid #e74c3c}input:focus:invalid:focus,select:focus:invalid:focus,textarea:focus:invalid:focus{border-color:#e74c3c}input[type=checkbox]:focus:invalid:focus,input[type=file]:focus:invalid:focus,input[type=radio]:focus:invalid:focus{outline-color:#e74c3c}input.wy-input-large{padding:12px;font-size:100%}textarea{overflow:auto;vertical-align:top;width:100%;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif}select,textarea{padding:.5em .625em;display:inline-block;border:1px solid #ccc;font-size:80%;box-shadow:inset 0 1px 3px #ddd;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}select{border:1px solid #ccc;background-color:#fff}select[multiple]{height:auto}select:focus,textarea:focus{outline:0}input[readonly],select[disabled],select[readonly],textarea[disabled],textarea[readonly]{cursor:not-allowed;background-color:#fafafa}input[type=checkbox][disabled],input[type=radio][disabled]{cursor:not-allowed}.wy-checkbox,.wy-radio{margin:6px 0;color:#404040;display:block}.wy-checkbox input,.wy-radio input{vertical-align:baseline}.wy-form-message-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-input-prefix,.wy-input-suffix{white-space:nowrap;padding:6px}.wy-input-prefix .wy-input-context,.wy-input-suffix .wy-input-context{line-height:27px;padding:0 8px;display:inline-block;font-size:80%;background-color:#f3f6f6;border:1px solid #ccc;color:#999}.wy-input-suffix .wy-input-context{border-left:0}.wy-input-prefix .wy-input-context{border-right:0}.wy-switch{position:relative;display:block;height:24px;margin-top:12px;cursor:pointer}.wy-switch:before{left:0;top:0;width:36px;height:12px;background:#ccc}.wy-switch:after,.wy-switch:before{position:absolute;content:"";display:block;border-radius:4px;-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.wy-switch:after{width:18px;height:18px;background:#999;left:-3px;top:-3px}.wy-switch span{position:absolute;left:48px;display:block;font-size:12px;color:#ccc;line-height:1}.wy-switch.active:before{background:#1e8449}.wy-switch.active:after{left:24px;background:#27ae60}.wy-switch.disabled{cursor:not-allowed;opacity:.8}.wy-control-group.wy-control-group-error .wy-form-message,.wy-control-group.wy-control-group-error>label{color:#e74c3c}.wy-control-group.wy-control-group-error input[type=color],.wy-control-group.wy-control-group-error input[type=date],.wy-control-group.wy-control-group-error input[type=datetime-local],.wy-control-group.wy-control-group-error input[type=datetime],.wy-control-group.wy-control-group-error input[type=email],.wy-control-group.wy-control-group-error input[type=month],.wy-control-group.wy-control-group-error input[type=number],.wy-control-group.wy-control-group-error input[type=password],.wy-control-group.wy-control-group-error input[type=search],.wy-control-group.wy-control-group-error input[type=tel],.wy-control-group.wy-control-group-error input[type=text],.wy-control-group.wy-control-group-error input[type=time],.wy-control-group.wy-control-group-error input[type=url],.wy-control-group.wy-control-group-error input[type=week],.wy-control-group.wy-control-group-error textarea{border:1px solid #e74c3c}.wy-inline-validate{white-space:nowrap}.wy-inline-validate .wy-input-context{padding:.5em .625em;display:inline-block;font-size:80%}.wy-inline-validate.wy-inline-validate-success .wy-input-context{color:#27ae60}.wy-inline-validate.wy-inline-validate-danger .wy-input-context{color:#e74c3c}.wy-inline-validate.wy-inline-validate-warning .wy-input-context{color:#e67e22}.wy-inline-validate.wy-inline-validate-info .wy-input-context{color:#2980b9}.rotate-90{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.rotate-180{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.rotate-270{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.mirror{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1);-ms-transform:scaleX(-1);-o-transform:scaleX(-1);transform:scaleX(-1)}.mirror.rotate-90{-webkit-transform:scaleX(-1) rotate(90deg);-moz-transform:scaleX(-1) rotate(90deg);-ms-transform:scaleX(-1) rotate(90deg);-o-transform:scaleX(-1) rotate(90deg);transform:scaleX(-1) rotate(90deg)}.mirror.rotate-180{-webkit-transform:scaleX(-1) rotate(180deg);-moz-transform:scaleX(-1) rotate(180deg);-ms-transform:scaleX(-1) rotate(180deg);-o-transform:scaleX(-1) rotate(180deg);transform:scaleX(-1) rotate(180deg)}.mirror.rotate-270{-webkit-transform:scaleX(-1) rotate(270deg);-moz-transform:scaleX(-1) rotate(270deg);-ms-transform:scaleX(-1) rotate(270deg);-o-transform:scaleX(-1) rotate(270deg);transform:scaleX(-1) rotate(270deg)}@media only screen and (max-width:480px){.wy-form button[type=submit]{margin:.7em 0 0}.wy-form input[type=color],.wy-form input[type=date],.wy-form input[type=datetime-local],.wy-form input[type=datetime],.wy-form input[type=email],.wy-form input[type=month],.wy-form input[type=number],.wy-form input[type=password],.wy-form input[type=search],.wy-form input[type=tel],.wy-form input[type=text],.wy-form input[type=time],.wy-form input[type=url],.wy-form input[type=week],.wy-form label{margin-bottom:.3em;display:block}.wy-form input[type=color],.wy-form input[type=date],.wy-form input[type=datetime-local],.wy-form input[type=datetime],.wy-form input[type=email],.wy-form input[type=month],.wy-form input[type=number],.wy-form input[type=password],.wy-form input[type=search],.wy-form input[type=tel],.wy-form input[type=time],.wy-form input[type=url],.wy-form input[type=week]{margin-bottom:0}.wy-form-aligned .wy-control-group label{margin-bottom:.3em;text-align:left;display:block;width:100%}.wy-form-aligned .wy-control{margin:1.5em 0 0}.wy-form-message,.wy-form-message-inline,.wy-form .wy-help-inline{display:block;font-size:80%;padding:6px 0}}@media screen and (max-width:768px){.tablet-hide{display:none}}@media screen and (max-width:480px){.mobile-hide{display:none}}.float-left{float:left}.float-right{float:right}.full-width{width:100%}.rst-content table.docutils,.rst-content table.field-list,.wy-table{border-collapse:collapse;border-spacing:0;empty-cells:show;margin-bottom:24px}.rst-content table.docutils caption,.rst-content table.field-list caption,.wy-table caption{color:#000;font:italic 85%/1 arial,sans-serif;padding:1em 0;text-align:center}.rst-content table.docutils td,.rst-content table.docutils th,.rst-content table.field-list td,.rst-content table.field-list th,.wy-table td,.wy-table th{font-size:90%;margin:0;overflow:visible;padding:8px 16px}.rst-content table.docutils td:first-child,.rst-content table.docutils th:first-child,.rst-content table.field-list td:first-child,.rst-content table.field-list th:first-child,.wy-table td:first-child,.wy-table th:first-child{border-left-width:0}.rst-content table.docutils thead,.rst-content table.field-list thead,.wy-table thead{color:#000;text-align:left;vertical-align:bottom;white-space:nowrap}.rst-content table.docutils thead th,.rst-content table.field-list thead th,.wy-table thead th{font-weight:700;border-bottom:2px solid #e1e4e5}.rst-content table.docutils td,.rst-content table.field-list td,.wy-table td{background-color:transparent;vertical-align:middle}.rst-content table.docutils td p,.rst-content table.field-list td p,.wy-table td p{line-height:18px}.rst-content table.docutils td p:last-child,.rst-content table.field-list td p:last-child,.wy-table td p:last-child{margin-bottom:0}.rst-content table.docutils .wy-table-cell-min,.rst-content table.field-list .wy-table-cell-min,.wy-table .wy-table-cell-min{width:1%;padding-right:0}.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox],.wy-table .wy-table-cell-min input[type=checkbox]{margin:0}.wy-table-secondary{color:grey;font-size:90%}.wy-table-tertiary{color:grey;font-size:80%}.rst-content table.docutils:not(.field-list) tr:nth-child(2n-1) td,.wy-table-backed,.wy-table-odd td,.wy-table-striped tr:nth-child(2n-1) td{background-color:#f3f6f6}.rst-content table.docutils,.wy-table-bordered-all{border:1px solid #e1e4e5}.rst-content table.docutils td,.wy-table-bordered-all td{border-bottom:1px solid #e1e4e5;border-left:1px solid #e1e4e5}.rst-content table.docutils tbody>tr:last-child td,.wy-table-bordered-all tbody>tr:last-child td{border-bottom-width:0}.wy-table-bordered{border:1px solid #e1e4e5}.wy-table-bordered-rows td{border-bottom:1px solid #e1e4e5}.wy-table-bordered-rows tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal td,.wy-table-horizontal th{border-width:0 0 1px;border-bottom:1px solid #e1e4e5}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-responsive{margin-bottom:24px;max-width:100%;overflow:auto}.wy-table-responsive table{margin-bottom:0!important}.wy-table-responsive table td,.wy-table-responsive table th{white-space:nowrap}a{color:#2980b9;text-decoration:none;cursor:pointer}a:hover{color:#3091d1}a:visited{color:#9b59b6}html{height:100%}body,html{overflow-x:hidden}body{font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;font-weight:400;color:#404040;min-height:100%;background:#edf0f2}.wy-text-left{text-align:left}.wy-text-center{text-align:center}.wy-text-right{text-align:right}.wy-text-large{font-size:120%}.wy-text-normal{font-size:100%}.wy-text-small,small{font-size:80%}.wy-text-strike{text-decoration:line-through}.wy-text-warning{color:#e67e22!important}a.wy-text-warning:hover{color:#eb9950!important}.wy-text-info{color:#2980b9!important}a.wy-text-info:hover{color:#409ad5!important}.wy-text-success{color:#27ae60!important}a.wy-text-success:hover{color:#36d278!important}.wy-text-danger{color:#e74c3c!important}a.wy-text-danger:hover{color:#ed7669!important}.wy-text-neutral{color:#404040!important}a.wy-text-neutral:hover{color:#595959!important}.rst-content .toctree-wrapper>p.caption,h1,h2,h3,h4,h5,h6,legend{margin-top:0;font-weight:700;font-family:Roboto Slab,ff-tisa-web-pro,Georgia,Arial,sans-serif}p{line-height:24px;font-size:16px;margin:0 0 24px}h1{font-size:175%}.rst-content .toctree-wrapper>p.caption,h2{font-size:150%}h3{font-size:125%}h4{font-size:115%}h5{font-size:110%}h6{font-size:100%}hr{display:block;height:1px;border:0;border-top:1px solid #e1e4e5;margin:24px 0;padding:0}.rst-content code,.rst-content tt,code{white-space:nowrap;max-width:100%;background:#fff;border:1px solid #e1e4e5;font-size:75%;padding:0 5px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;color:#e74c3c;overflow-x:auto}.rst-content tt.code-large,code.code-large{font-size:90%}.rst-content .section ul,.rst-content .toctree-wrapper ul,.rst-content section ul,.wy-plain-list-disc,article ul{list-style:disc;line-height:24px;margin-bottom:24px}.rst-content .section ul li,.rst-content .toctree-wrapper ul li,.rst-content section ul li,.wy-plain-list-disc li,article ul li{list-style:disc;margin-left:24px}.rst-content .section ul li p:last-child,.rst-content .section ul li ul,.rst-content .toctree-wrapper ul li p:last-child,.rst-content .toctree-wrapper ul li ul,.rst-content section ul li p:last-child,.rst-content section ul li ul,.wy-plain-list-disc li p:last-child,.wy-plain-list-disc li ul,article ul li p:last-child,article ul li ul{margin-bottom:0}.rst-content .section ul li li,.rst-content .toctree-wrapper ul li li,.rst-content section ul li li,.wy-plain-list-disc li li,article ul li li{list-style:circle}.rst-content .section ul li li li,.rst-content .toctree-wrapper ul li li li,.rst-content section ul li li li,.wy-plain-list-disc li li li,article ul li li li{list-style:square}.rst-content .section ul li ol li,.rst-content .toctree-wrapper ul li ol li,.rst-content section ul li ol li,.wy-plain-list-disc li ol li,article ul li ol li{list-style:decimal}.rst-content .section ol,.rst-content .section ol.arabic,.rst-content .toctree-wrapper ol,.rst-content .toctree-wrapper ol.arabic,.rst-content section ol,.rst-content section ol.arabic,.wy-plain-list-decimal,article ol{list-style:decimal;line-height:24px;margin-bottom:24px}.rst-content .section ol.arabic li,.rst-content .section ol li,.rst-content .toctree-wrapper ol.arabic li,.rst-content .toctree-wrapper ol li,.rst-content section ol.arabic li,.rst-content section ol li,.wy-plain-list-decimal li,article ol li{list-style:decimal;margin-left:24px}.rst-content .section ol.arabic li ul,.rst-content .section ol li p:last-child,.rst-content .section ol li ul,.rst-content .toctree-wrapper ol.arabic li ul,.rst-content .toctree-wrapper ol li p:last-child,.rst-content .toctree-wrapper ol li ul,.rst-content section ol.arabic li ul,.rst-content section ol li p:last-child,.rst-content section ol li ul,.wy-plain-list-decimal li p:last-child,.wy-plain-list-decimal li ul,article ol li p:last-child,article ol li ul{margin-bottom:0}.rst-content .section ol.arabic li ul li,.rst-content .section ol li ul li,.rst-content .toctree-wrapper ol.arabic li ul li,.rst-content .toctree-wrapper ol li ul li,.rst-content section ol.arabic li ul li,.rst-content section ol li ul li,.wy-plain-list-decimal li ul li,article ol li ul li{list-style:disc}.wy-breadcrumbs{*zoom:1}.wy-breadcrumbs:after,.wy-breadcrumbs:before{display:table;content:""}.wy-breadcrumbs:after{clear:both}.wy-breadcrumbs>li{display:inline-block;padding-top:5px}.wy-breadcrumbs>li.wy-breadcrumbs-aside{float:right}.rst-content .wy-breadcrumbs>li code,.rst-content .wy-breadcrumbs>li tt,.wy-breadcrumbs>li .rst-content tt,.wy-breadcrumbs>li code{all:inherit;color:inherit}.breadcrumb-item:before{content:"/";color:#bbb;font-size:13px;padding:0 6px 0 3px}.wy-breadcrumbs-extra{margin-bottom:0;color:#b3b3b3;font-size:80%;display:inline-block}@media screen and (max-width:480px){.wy-breadcrumbs-extra,.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}@media print{.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}html{font-size:16px}.wy-affix{position:fixed;top:1.618em}.wy-menu a:hover{text-decoration:none}.wy-menu-horiz{*zoom:1}.wy-menu-horiz:after,.wy-menu-horiz:before{display:table;content:""}.wy-menu-horiz:after{clear:both}.wy-menu-horiz li,.wy-menu-horiz ul{display:inline-block}.wy-menu-horiz li:hover{background:hsla(0,0%,100%,.1)}.wy-menu-horiz li.divide-left{border-left:1px solid #404040}.wy-menu-horiz li.divide-right{border-right:1px solid #404040}.wy-menu-horiz a{height:32px;display:inline-block;line-height:32px;padding:0 16px}.wy-menu-vertical{width:300px}.wy-menu-vertical header,.wy-menu-vertical p.caption{color:#55a5d9;height:32px;line-height:32px;padding:0 1.618em;margin:12px 0 0;display:block;font-weight:700;text-transform:uppercase;font-size:85%;white-space:nowrap}.wy-menu-vertical ul{margin-bottom:0}.wy-menu-vertical li.divide-top{border-top:1px solid #404040}.wy-menu-vertical li.divide-bottom{border-bottom:1px solid #404040}.wy-menu-vertical li.current{background:#e3e3e3}.wy-menu-vertical li.current a{color:grey;border-right:1px solid #c9c9c9;padding:.4045em 2.427em}.wy-menu-vertical li.current a:hover{background:#d6d6d6}.rst-content .wy-menu-vertical li tt,.wy-menu-vertical li .rst-content tt,.wy-menu-vertical li code{border:none;background:inherit;color:inherit;padding-left:0;padding-right:0}.wy-menu-vertical li button.toctree-expand{display:block;float:left;margin-left:-1.2em;line-height:18px;color:#4d4d4d;border:none;background:none;padding:0}.wy-menu-vertical li.current>a,.wy-menu-vertical li.on a{color:#404040;font-weight:700;position:relative;background:#fcfcfc;border:none;padding:.4045em 1.618em}.wy-menu-vertical li.current>a:hover,.wy-menu-vertical li.on a:hover{background:#fcfcfc}.wy-menu-vertical li.current>a:hover button.toctree-expand,.wy-menu-vertical li.on a:hover button.toctree-expand{color:grey}.wy-menu-vertical li.current>a button.toctree-expand,.wy-menu-vertical li.on a button.toctree-expand{display:block;line-height:18px;color:#333}.wy-menu-vertical li.toctree-l1.current>a{border-bottom:1px solid #c9c9c9;border-top:1px solid #c9c9c9}.wy-menu-vertical .toctree-l1.current .toctree-l2>ul,.wy-menu-vertical .toctree-l2.current .toctree-l3>ul,.wy-menu-vertical .toctree-l3.current .toctree-l4>ul,.wy-menu-vertical .toctree-l4.current .toctree-l5>ul,.wy-menu-vertical .toctree-l5.current .toctree-l6>ul,.wy-menu-vertical .toctree-l6.current .toctree-l7>ul,.wy-menu-vertical .toctree-l7.current .toctree-l8>ul,.wy-menu-vertical .toctree-l8.current .toctree-l9>ul,.wy-menu-vertical .toctree-l9.current .toctree-l10>ul,.wy-menu-vertical .toctree-l10.current .toctree-l11>ul{display:none}.wy-menu-vertical .toctree-l1.current .current.toctree-l2>ul,.wy-menu-vertical .toctree-l2.current .current.toctree-l3>ul,.wy-menu-vertical .toctree-l3.current .current.toctree-l4>ul,.wy-menu-vertical .toctree-l4.current .current.toctree-l5>ul,.wy-menu-vertical .toctree-l5.current .current.toctree-l6>ul,.wy-menu-vertical .toctree-l6.current .current.toctree-l7>ul,.wy-menu-vertical .toctree-l7.current .current.toctree-l8>ul,.wy-menu-vertical .toctree-l8.current .current.toctree-l9>ul,.wy-menu-vertical .toctree-l9.current .current.toctree-l10>ul,.wy-menu-vertical .toctree-l10.current .current.toctree-l11>ul{display:block}.wy-menu-vertical li.toctree-l3,.wy-menu-vertical li.toctree-l4{font-size:.9em}.wy-menu-vertical li.toctree-l2 a,.wy-menu-vertical li.toctree-l3 a,.wy-menu-vertical li.toctree-l4 a,.wy-menu-vertical li.toctree-l5 a,.wy-menu-vertical li.toctree-l6 a,.wy-menu-vertical li.toctree-l7 a,.wy-menu-vertical li.toctree-l8 a,.wy-menu-vertical li.toctree-l9 a,.wy-menu-vertical li.toctree-l10 a{color:#404040}.wy-menu-vertical li.toctree-l2 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l3 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l4 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l5 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l6 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l7 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l8 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l9 a:hover button.toctree-expand,.wy-menu-vertical li.toctree-l10 a:hover button.toctree-expand{color:grey}.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a,.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a,.wy-menu-vertical li.toctree-l4.current li.toctree-l5>a,.wy-menu-vertical li.toctree-l5.current li.toctree-l6>a,.wy-menu-vertical li.toctree-l6.current li.toctree-l7>a,.wy-menu-vertical li.toctree-l7.current li.toctree-l8>a,.wy-menu-vertical li.toctree-l8.current li.toctree-l9>a,.wy-menu-vertical li.toctree-l9.current li.toctree-l10>a,.wy-menu-vertical li.toctree-l10.current li.toctree-l11>a{display:block}.wy-menu-vertical li.toctree-l2.current>a{padding:.4045em 2.427em}.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a{padding:.4045em 1.618em .4045em 4.045em}.wy-menu-vertical li.toctree-l3.current>a{padding:.4045em 4.045em}.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a{padding:.4045em 1.618em .4045em 5.663em}.wy-menu-vertical li.toctree-l4.current>a{padding:.4045em 5.663em}.wy-menu-vertical li.toctree-l4.current li.toctree-l5>a{padding:.4045em 1.618em .4045em 7.281em}.wy-menu-vertical li.toctree-l5.current>a{padding:.4045em 7.281em}.wy-menu-vertical li.toctree-l5.current li.toctree-l6>a{padding:.4045em 1.618em .4045em 8.899em}.wy-menu-vertical li.toctree-l6.current>a{padding:.4045em 8.899em}.wy-menu-vertical li.toctree-l6.current li.toctree-l7>a{padding:.4045em 1.618em .4045em 10.517em}.wy-menu-vertical li.toctree-l7.current>a{padding:.4045em 10.517em}.wy-menu-vertical li.toctree-l7.current li.toctree-l8>a{padding:.4045em 1.618em .4045em 12.135em}.wy-menu-vertical li.toctree-l8.current>a{padding:.4045em 12.135em}.wy-menu-vertical li.toctree-l8.current li.toctree-l9>a{padding:.4045em 1.618em .4045em 13.753em}.wy-menu-vertical li.toctree-l9.current>a{padding:.4045em 13.753em}.wy-menu-vertical li.toctree-l9.current li.toctree-l10>a{padding:.4045em 1.618em .4045em 15.371em}.wy-menu-vertical li.toctree-l10.current>a{padding:.4045em 15.371em}.wy-menu-vertical li.toctree-l10.current li.toctree-l11>a{padding:.4045em 1.618em .4045em 16.989em}.wy-menu-vertical li.toctree-l2.current>a,.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a{background:#c9c9c9}.wy-menu-vertical li.toctree-l2 button.toctree-expand{color:#a3a3a3}.wy-menu-vertical li.toctree-l3.current>a,.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a{background:#bdbdbd}.wy-menu-vertical li.toctree-l3 button.toctree-expand{color:#969696}.wy-menu-vertical li.current ul{display:block}.wy-menu-vertical li ul{margin-bottom:0;display:none}.wy-menu-vertical li ul li a{margin-bottom:0;color:#d9d9d9;font-weight:400}.wy-menu-vertical a{line-height:18px;padding:.4045em 1.618em;display:block;position:relative;font-size:90%;color:#d9d9d9}.wy-menu-vertical a:hover{background-color:#4e4a4a;cursor:pointer}.wy-menu-vertical a:hover button.toctree-expand{color:#d9d9d9}.wy-menu-vertical a:active{background-color:#2980b9;cursor:pointer;color:#fff}.wy-menu-vertical a:active button.toctree-expand{color:#fff}.wy-side-nav-search{display:block;width:300px;padding:.809em;margin-bottom:.809em;z-index:200;background-color:#2980b9;text-align:center;color:#fcfcfc}.wy-side-nav-search input[type=text]{width:100%;border-radius:50px;padding:6px 12px;border-color:#2472a4}.wy-side-nav-search img{display:block;margin:auto auto .809em;height:45px;width:45px;background-color:#2980b9;padding:5px;border-radius:100%}.wy-side-nav-search .wy-dropdown>a,.wy-side-nav-search>a{color:#fcfcfc;font-size:100%;font-weight:700;display:inline-block;padding:4px 6px;margin-bottom:.809em;max-width:100%}.wy-side-nav-search .wy-dropdown>a:hover,.wy-side-nav-search>a:hover{background:hsla(0,0%,100%,.1)}.wy-side-nav-search .wy-dropdown>a img.logo,.wy-side-nav-search>a img.logo{display:block;margin:0 auto;height:auto;width:auto;border-radius:0;max-width:100%;background:transparent}.wy-side-nav-search .wy-dropdown>a.icon img.logo,.wy-side-nav-search>a.icon img.logo{margin-top:.85em}.wy-side-nav-search>div.version{margin-top:-.4045em;margin-bottom:.809em;font-weight:400;color:hsla(0,0%,100%,.3)}.wy-nav .wy-menu-vertical header{color:#2980b9}.wy-nav .wy-menu-vertical a{color:#b3b3b3}.wy-nav .wy-menu-vertical a:hover{background-color:#2980b9;color:#fff}[data-menu-wrap]{-webkit-transition:all .2s ease-in;-moz-transition:all .2s ease-in;transition:all .2s ease-in;position:absolute;opacity:1;width:100%;opacity:0}[data-menu-wrap].move-center{left:0;right:auto;opacity:1}[data-menu-wrap].move-left{right:auto;left:-100%;opacity:0}[data-menu-wrap].move-right{right:-100%;left:auto;opacity:0}.wy-body-for-nav{background:#fcfcfc}.wy-grid-for-nav{position:absolute;width:100%;height:100%}.wy-nav-side{position:fixed;top:0;bottom:0;left:0;padding-bottom:2em;width:300px;overflow-x:hidden;overflow-y:hidden;min-height:100%;color:#9b9b9b;background:#343131;z-index:200}.wy-side-scroll{width:320px;position:relative;overflow-x:hidden;overflow-y:scroll;height:100%}.wy-nav-top{display:none;background:#2980b9;color:#fff;padding:.4045em .809em;position:relative;line-height:50px;text-align:center;font-size:100%;*zoom:1}.wy-nav-top:after,.wy-nav-top:before{display:table;content:""}.wy-nav-top:after{clear:both}.wy-nav-top a{color:#fff;font-weight:700}.wy-nav-top img{margin-right:12px;height:45px;width:45px;background-color:#2980b9;padding:5px;border-radius:100%}.wy-nav-top i{font-size:30px;float:left;cursor:pointer;padding-top:inherit}.wy-nav-content-wrap{margin-left:300px;background:#fcfcfc;min-height:100%}.wy-nav-content{padding:1.618em 3.236em;height:100%;max-width:800px;margin:auto}.wy-body-mask{position:fixed;width:100%;height:100%;background:rgba(0,0,0,.2);display:none;z-index:499}.wy-body-mask.on{display:block}footer{color:grey}footer p{margin-bottom:12px}.rst-content footer span.commit tt,footer span.commit .rst-content tt,footer span.commit code{padding:0;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;font-size:1em;background:none;border:none;color:grey}.rst-footer-buttons{*zoom:1}.rst-footer-buttons:after,.rst-footer-buttons:before{width:100%;display:table;content:""}.rst-footer-buttons:after{clear:both}.rst-breadcrumbs-buttons{margin-top:12px;*zoom:1}.rst-breadcrumbs-buttons:after,.rst-breadcrumbs-buttons:before{display:table;content:""}.rst-breadcrumbs-buttons:after{clear:both}#search-results .search li{margin-bottom:24px;border-bottom:1px solid #e1e4e5;padding-bottom:24px}#search-results .search li:first-child{border-top:1px solid #e1e4e5;padding-top:24px}#search-results .search li a{font-size:120%;margin-bottom:12px;display:inline-block}#search-results .context{color:grey;font-size:90%}.genindextable li>ul{margin-left:24px}@media screen and (max-width:768px){.wy-body-for-nav{background:#fcfcfc}.wy-nav-top{display:block}.wy-nav-side{left:-300px}.wy-nav-side.shift{width:85%;left:0}.wy-menu.wy-menu-vertical,.wy-side-nav-search,.wy-side-scroll{width:auto}.wy-nav-content-wrap{margin-left:0}.wy-nav-content-wrap .wy-nav-content{padding:1.618em}.wy-nav-content-wrap.shift{position:fixed;min-width:100%;left:85%;top:0;height:100%;overflow:hidden}}@media screen and (min-width:1100px){.wy-nav-content-wrap{background:rgba(0,0,0,.05)}.wy-nav-content{margin:0;background:#fcfcfc}}@media print{.rst-versions,.wy-nav-side,footer{display:none}.wy-nav-content-wrap{margin-left:0}}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;z-index:400}.rst-versions a{color:#2980b9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27ae60;*zoom:1}.rst-versions .rst-current-version:after,.rst-versions .rst-current-version:before{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-content .code-block-caption .rst-versions .rst-current-version .headerlink,.rst-content .eqno .rst-versions .rst-current-version .headerlink,.rst-content .rst-versions .rst-current-version .admonition-title,.rst-content code.download .rst-versions .rst-current-version span:first-child,.rst-content dl dt .rst-versions .rst-current-version .headerlink,.rst-content h1 .rst-versions .rst-current-version .headerlink,.rst-content h2 .rst-versions .rst-current-version .headerlink,.rst-content h3 .rst-versions .rst-current-version .headerlink,.rst-content h4 .rst-versions .rst-current-version .headerlink,.rst-content h5 .rst-versions .rst-current-version .headerlink,.rst-content h6 .rst-versions .rst-current-version .headerlink,.rst-content p .rst-versions .rst-current-version .headerlink,.rst-content table>caption .rst-versions .rst-current-version .headerlink,.rst-content tt.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .fa,.rst-versions .rst-current-version .icon,.rst-versions .rst-current-version .rst-content .admonition-title,.rst-versions .rst-current-version .rst-content .code-block-caption .headerlink,.rst-versions .rst-current-version .rst-content .eqno .headerlink,.rst-versions .rst-current-version .rst-content code.download span:first-child,.rst-versions .rst-current-version .rst-content dl dt .headerlink,.rst-versions .rst-current-version .rst-content h1 .headerlink,.rst-versions .rst-current-version .rst-content h2 .headerlink,.rst-versions .rst-current-version .rst-content h3 .headerlink,.rst-versions .rst-current-version .rst-content h4 .headerlink,.rst-versions .rst-current-version .rst-content h5 .headerlink,.rst-versions .rst-current-version .rst-content h6 .headerlink,.rst-versions .rst-current-version .rst-content p .headerlink,.rst-versions .rst-current-version .rst-content table>caption .headerlink,.rst-versions .rst-current-version .rst-content tt.download span:first-child,.rst-versions .rst-current-version .wy-menu-vertical li button.toctree-expand,.wy-menu-vertical li .rst-versions .rst-current-version button.toctree-expand{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#e74c3c;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#f1c40f;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:grey;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:1px solid #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none;line-height:30px}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge>.rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width:768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}}.rst-content .toctree-wrapper>p.caption,.rst-content h1,.rst-content h2,.rst-content h3,.rst-content h4,.rst-content h5,.rst-content h6{margin-bottom:24px}.rst-content img{max-width:100%;height:auto}.rst-content div.figure,.rst-content figure{margin-bottom:24px}.rst-content div.figure .caption-text,.rst-content figure .caption-text{font-style:italic}.rst-content div.figure p:last-child.caption,.rst-content figure p:last-child.caption{margin-bottom:0}.rst-content div.figure.align-center,.rst-content figure.align-center{text-align:center}.rst-content .section>a>img,.rst-content .section>img,.rst-content section>a>img,.rst-content section>img{margin-bottom:24px}.rst-content abbr[title]{text-decoration:none}.rst-content.style-external-links a.reference.external:after{font-family:FontAwesome;content:"\f08e";color:#b3b3b3;vertical-align:super;font-size:60%;margin:0 .2em}.rst-content blockquote{margin-left:24px;line-height:24px;margin-bottom:24px}.rst-content pre.literal-block{white-space:pre;margin:0;padding:12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;display:block;overflow:auto}.rst-content div[class^=highlight],.rst-content pre.literal-block{border:1px solid #e1e4e5;overflow-x:auto;margin:1px 0 24px}.rst-content div[class^=highlight] div[class^=highlight],.rst-content pre.literal-block div[class^=highlight]{padding:0;border:none;margin:0}.rst-content div[class^=highlight] td.code{width:100%}.rst-content .linenodiv pre{border-right:1px solid #e6e9ea;margin:0;padding:12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;user-select:none;pointer-events:none}.rst-content div[class^=highlight] pre{white-space:pre;margin:0;padding:12px;display:block;overflow:auto}.rst-content div[class^=highlight] pre .hll{display:block;margin:0 -12px;padding:0 12px}.rst-content .linenodiv pre,.rst-content div[class^=highlight] pre,.rst-content pre.literal-block{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;font-size:12px;line-height:1.4}.rst-content div.highlight .gp,.rst-content div.highlight span.linenos{user-select:none;pointer-events:none}.rst-content div.highlight span.linenos{display:inline-block;padding-left:0;padding-right:12px;margin-right:12px;border-right:1px solid #e6e9ea}.rst-content .code-block-caption{font-style:italic;font-size:85%;line-height:1;padding:1em 0;text-align:center}@media print{.rst-content .codeblock,.rst-content div[class^=highlight],.rst-content div[class^=highlight] pre{white-space:pre-wrap}}.rst-content .admonition,.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .note,.rst-content .seealso,.rst-content .tip,.rst-content .warning{clear:both}.rst-content .admonition-todo .last,.rst-content .admonition-todo>:last-child,.rst-content .admonition .last,.rst-content .admonition>:last-child,.rst-content .attention .last,.rst-content .attention>:last-child,.rst-content .caution .last,.rst-content .caution>:last-child,.rst-content .danger .last,.rst-content .danger>:last-child,.rst-content .error .last,.rst-content .error>:last-child,.rst-content .hint .last,.rst-content .hint>:last-child,.rst-content .important .last,.rst-content .important>:last-child,.rst-content .note .last,.rst-content .note>:last-child,.rst-content .seealso .last,.rst-content .seealso>:last-child,.rst-content .tip .last,.rst-content .tip>:last-child,.rst-content .warning .last,.rst-content .warning>:last-child{margin-bottom:0}.rst-content .admonition-title:before{margin-right:4px}.rst-content .admonition table{border-color:rgba(0,0,0,.1)}.rst-content .admonition table td,.rst-content .admonition table th{background:transparent!important;border-color:rgba(0,0,0,.1)!important}.rst-content .section ol.loweralpha,.rst-content .section ol.loweralpha>li,.rst-content .toctree-wrapper ol.loweralpha,.rst-content .toctree-wrapper ol.loweralpha>li,.rst-content section ol.loweralpha,.rst-content section ol.loweralpha>li{list-style:lower-alpha}.rst-content .section ol.upperalpha,.rst-content .section ol.upperalpha>li,.rst-content .toctree-wrapper ol.upperalpha,.rst-content .toctree-wrapper ol.upperalpha>li,.rst-content section ol.upperalpha,.rst-content section ol.upperalpha>li{list-style:upper-alpha}.rst-content .section ol li>*,.rst-content .section ul li>*,.rst-content .toctree-wrapper ol li>*,.rst-content .toctree-wrapper ul li>*,.rst-content section ol li>*,.rst-content section ul li>*{margin-top:12px;margin-bottom:12px}.rst-content .section ol li>:first-child,.rst-content .section ul li>:first-child,.rst-content .toctree-wrapper ol li>:first-child,.rst-content .toctree-wrapper ul li>:first-child,.rst-content section ol li>:first-child,.rst-content section ul li>:first-child{margin-top:0}.rst-content .section ol li>p,.rst-content .section ol li>p:last-child,.rst-content .section ul li>p,.rst-content .section ul li>p:last-child,.rst-content .toctree-wrapper ol li>p,.rst-content .toctree-wrapper ol li>p:last-child,.rst-content .toctree-wrapper ul li>p,.rst-content .toctree-wrapper ul li>p:last-child,.rst-content section ol li>p,.rst-content section ol li>p:last-child,.rst-content section ul li>p,.rst-content section ul li>p:last-child{margin-bottom:12px}.rst-content .section ol li>p:only-child,.rst-content .section ol li>p:only-child:last-child,.rst-content .section ul li>p:only-child,.rst-content .section ul li>p:only-child:last-child,.rst-content .toctree-wrapper ol li>p:only-child,.rst-content .toctree-wrapper ol li>p:only-child:last-child,.rst-content .toctree-wrapper ul li>p:only-child,.rst-content .toctree-wrapper ul li>p:only-child:last-child,.rst-content section ol li>p:only-child,.rst-content section ol li>p:only-child:last-child,.rst-content section ul li>p:only-child,.rst-content section ul li>p:only-child:last-child{margin-bottom:0}.rst-content .section ol li>ol,.rst-content .section ol li>ul,.rst-content .section ul li>ol,.rst-content .section ul li>ul,.rst-content .toctree-wrapper ol li>ol,.rst-content .toctree-wrapper ol li>ul,.rst-content .toctree-wrapper ul li>ol,.rst-content .toctree-wrapper ul li>ul,.rst-content section ol li>ol,.rst-content section ol li>ul,.rst-content section ul li>ol,.rst-content section ul li>ul{margin-bottom:12px}.rst-content .section ol.simple li>*,.rst-content .section ol.simple li ol,.rst-content .section ol.simple li ul,.rst-content .section ul.simple li>*,.rst-content .section ul.simple li ol,.rst-content .section ul.simple li ul,.rst-content .toctree-wrapper ol.simple li>*,.rst-content .toctree-wrapper ol.simple li ol,.rst-content .toctree-wrapper ol.simple li ul,.rst-content .toctree-wrapper ul.simple li>*,.rst-content .toctree-wrapper ul.simple li ol,.rst-content .toctree-wrapper ul.simple li ul,.rst-content section ol.simple li>*,.rst-content section ol.simple li ol,.rst-content section ol.simple li ul,.rst-content section ul.simple li>*,.rst-content section ul.simple li ol,.rst-content section ul.simple li ul{margin-top:0;margin-bottom:0}.rst-content .line-block{margin-left:0;margin-bottom:24px;line-height:24px}.rst-content .line-block .line-block{margin-left:24px;margin-bottom:0}.rst-content .topic-title{font-weight:700;margin-bottom:12px}.rst-content .toc-backref{color:#404040}.rst-content .align-right{float:right;margin:0 0 24px 24px}.rst-content .align-left{float:left;margin:0 24px 24px 0}.rst-content .align-center{margin:auto}.rst-content .align-center:not(table){display:block}.rst-content .code-block-caption .headerlink,.rst-content .eqno .headerlink,.rst-content .toctree-wrapper>p.caption .headerlink,.rst-content dl dt .headerlink,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content p.caption .headerlink,.rst-content p .headerlink,.rst-content table>caption .headerlink{opacity:0;font-size:14px;font-family:FontAwesome;margin-left:.5em}.rst-content .code-block-caption .headerlink:focus,.rst-content .code-block-caption:hover .headerlink,.rst-content .eqno .headerlink:focus,.rst-content .eqno:hover .headerlink,.rst-content .toctree-wrapper>p.caption .headerlink:focus,.rst-content .toctree-wrapper>p.caption:hover .headerlink,.rst-content dl dt .headerlink:focus,.rst-content dl dt:hover .headerlink,.rst-content h1 .headerlink:focus,.rst-content h1:hover .headerlink,.rst-content h2 .headerlink:focus,.rst-content h2:hover .headerlink,.rst-content h3 .headerlink:focus,.rst-content h3:hover .headerlink,.rst-content h4 .headerlink:focus,.rst-content h4:hover .headerlink,.rst-content h5 .headerlink:focus,.rst-content h5:hover .headerlink,.rst-content h6 .headerlink:focus,.rst-content h6:hover .headerlink,.rst-content p.caption .headerlink:focus,.rst-content p.caption:hover .headerlink,.rst-content p .headerlink:focus,.rst-content p:hover .headerlink,.rst-content table>caption .headerlink:focus,.rst-content table>caption:hover .headerlink{opacity:1}.rst-content p a{overflow-wrap:anywhere}.rst-content .wy-table td p,.rst-content .wy-table td ul,.rst-content .wy-table th p,.rst-content .wy-table th ul,.rst-content table.docutils td p,.rst-content table.docutils td ul,.rst-content table.docutils th p,.rst-content table.docutils th ul,.rst-content table.field-list td p,.rst-content table.field-list td ul,.rst-content table.field-list th p,.rst-content table.field-list th ul{font-size:inherit}.rst-content .btn:focus{outline:2px solid}.rst-content table>caption .headerlink:after{font-size:12px}.rst-content .centered{text-align:center}.rst-content .sidebar{float:right;width:40%;display:block;margin:0 0 24px 24px;padding:24px;background:#f3f6f6;border:1px solid #e1e4e5}.rst-content .sidebar dl,.rst-content .sidebar p,.rst-content .sidebar ul{font-size:90%}.rst-content .sidebar .last,.rst-content .sidebar>:last-child{margin-bottom:0}.rst-content .sidebar .sidebar-title{display:block;font-family:Roboto Slab,ff-tisa-web-pro,Georgia,Arial,sans-serif;font-weight:700;background:#e1e4e5;padding:6px 12px;margin:-24px -24px 24px;font-size:100%}.rst-content .highlighted{background:#f1c40f;box-shadow:0 0 0 2px #f1c40f;display:inline;font-weight:700}.rst-content .citation-reference,.rst-content .footnote-reference{vertical-align:baseline;position:relative;top:-.4em;line-height:0;font-size:90%}.rst-content .citation-reference>span.fn-bracket,.rst-content .footnote-reference>span.fn-bracket{display:none}.rst-content .hlist{width:100%}.rst-content dl dt span.classifier:before{content:" : "}.rst-content dl dt span.classifier-delimiter{display:none!important}html.writer-html4 .rst-content table.docutils.citation,html.writer-html4 .rst-content table.docutils.footnote{background:none;border:none}html.writer-html4 .rst-content table.docutils.citation td,html.writer-html4 .rst-content table.docutils.citation tr,html.writer-html4 .rst-content table.docutils.footnote td,html.writer-html4 .rst-content table.docutils.footnote tr{border:none;background-color:transparent!important;white-space:normal}html.writer-html4 .rst-content table.docutils.citation td.label,html.writer-html4 .rst-content table.docutils.footnote td.label{padding-left:0;padding-right:0;vertical-align:top}html.writer-html5 .rst-content dl.citation,html.writer-html5 .rst-content dl.field-list,html.writer-html5 .rst-content dl.footnote{display:grid;grid-template-columns:auto minmax(80%,95%)}html.writer-html5 .rst-content dl.citation>dt,html.writer-html5 .rst-content dl.field-list>dt,html.writer-html5 .rst-content dl.footnote>dt{display:inline-grid;grid-template-columns:max-content auto}html.writer-html5 .rst-content aside.citation,html.writer-html5 .rst-content aside.footnote,html.writer-html5 .rst-content div.citation{display:grid;grid-template-columns:auto auto minmax(.65rem,auto) minmax(40%,95%)}html.writer-html5 .rst-content aside.citation>span.label,html.writer-html5 .rst-content aside.footnote>span.label,html.writer-html5 .rst-content div.citation>span.label{grid-column-start:1;grid-column-end:2}html.writer-html5 .rst-content aside.citation>span.backrefs,html.writer-html5 .rst-content aside.footnote>span.backrefs,html.writer-html5 .rst-content div.citation>span.backrefs{grid-column-start:2;grid-column-end:3;grid-row-start:1;grid-row-end:3}html.writer-html5 .rst-content aside.citation>p,html.writer-html5 .rst-content aside.footnote>p,html.writer-html5 .rst-content div.citation>p{grid-column-start:4;grid-column-end:5}html.writer-html5 .rst-content dl.citation,html.writer-html5 .rst-content dl.field-list,html.writer-html5 .rst-content dl.footnote{margin-bottom:24px}html.writer-html5 .rst-content dl.citation>dt,html.writer-html5 .rst-content dl.field-list>dt,html.writer-html5 .rst-content dl.footnote>dt{padding-left:1rem}html.writer-html5 .rst-content dl.citation>dd,html.writer-html5 .rst-content dl.citation>dt,html.writer-html5 .rst-content dl.field-list>dd,html.writer-html5 .rst-content dl.field-list>dt,html.writer-html5 .rst-content dl.footnote>dd,html.writer-html5 .rst-content dl.footnote>dt{margin-bottom:0}html.writer-html5 .rst-content dl.citation,html.writer-html5 .rst-content dl.footnote{font-size:.9rem}html.writer-html5 .rst-content dl.citation>dt,html.writer-html5 .rst-content dl.footnote>dt{margin:0 .5rem .5rem 0;line-height:1.2rem;word-break:break-all;font-weight:400}html.writer-html5 .rst-content dl.citation>dt>span.brackets:before,html.writer-html5 .rst-content dl.footnote>dt>span.brackets:before{content:"["}html.writer-html5 .rst-content dl.citation>dt>span.brackets:after,html.writer-html5 .rst-content dl.footnote>dt>span.brackets:after{content:"]"}html.writer-html5 .rst-content dl.citation>dt>span.fn-backref,html.writer-html5 .rst-content dl.footnote>dt>span.fn-backref{text-align:left;font-style:italic;margin-left:.65rem;word-break:break-word;word-spacing:-.1rem;max-width:5rem}html.writer-html5 .rst-content dl.citation>dt>span.fn-backref>a,html.writer-html5 .rst-content dl.footnote>dt>span.fn-backref>a{word-break:keep-all}html.writer-html5 .rst-content dl.citation>dt>span.fn-backref>a:not(:first-child):before,html.writer-html5 .rst-content dl.footnote>dt>span.fn-backref>a:not(:first-child):before{content:" "}html.writer-html5 .rst-content dl.citation>dd,html.writer-html5 .rst-content dl.footnote>dd{margin:0 0 .5rem;line-height:1.2rem}html.writer-html5 .rst-content dl.citation>dd p,html.writer-html5 .rst-content dl.footnote>dd p{font-size:.9rem}html.writer-html5 .rst-content aside.citation,html.writer-html5 .rst-content aside.footnote,html.writer-html5 .rst-content div.citation{padding-left:1rem;padding-right:1rem;font-size:.9rem;line-height:1.2rem}html.writer-html5 .rst-content aside.citation p,html.writer-html5 .rst-content aside.footnote p,html.writer-html5 .rst-content div.citation p{font-size:.9rem;line-height:1.2rem;margin-bottom:12px}html.writer-html5 .rst-content aside.citation span.backrefs,html.writer-html5 .rst-content aside.footnote span.backrefs,html.writer-html5 .rst-content div.citation span.backrefs{text-align:left;font-style:italic;margin-left:.65rem;word-break:break-word;word-spacing:-.1rem;max-width:5rem}html.writer-html5 .rst-content aside.citation span.backrefs>a,html.writer-html5 .rst-content aside.footnote span.backrefs>a,html.writer-html5 .rst-content div.citation span.backrefs>a{word-break:keep-all}html.writer-html5 .rst-content aside.citation span.backrefs>a:not(:first-child):before,html.writer-html5 .rst-content aside.footnote span.backrefs>a:not(:first-child):before,html.writer-html5 .rst-content div.citation span.backrefs>a:not(:first-child):before{content:" "}html.writer-html5 .rst-content aside.citation span.label,html.writer-html5 .rst-content aside.footnote span.label,html.writer-html5 .rst-content div.citation span.label{line-height:1.2rem}html.writer-html5 .rst-content aside.citation-list,html.writer-html5 .rst-content aside.footnote-list,html.writer-html5 .rst-content div.citation-list{margin-bottom:24px}html.writer-html5 .rst-content dl.option-list kbd{font-size:.9rem}.rst-content table.docutils.footnote,html.writer-html4 .rst-content table.docutils.citation,html.writer-html5 .rst-content aside.footnote,html.writer-html5 .rst-content aside.footnote-list aside.footnote,html.writer-html5 .rst-content div.citation-list>div.citation,html.writer-html5 .rst-content dl.citation,html.writer-html5 .rst-content dl.footnote{color:grey}.rst-content table.docutils.footnote code,.rst-content table.docutils.footnote tt,html.writer-html4 .rst-content table.docutils.citation code,html.writer-html4 .rst-content table.docutils.citation tt,html.writer-html5 .rst-content aside.footnote-list aside.footnote code,html.writer-html5 .rst-content aside.footnote-list aside.footnote tt,html.writer-html5 .rst-content aside.footnote code,html.writer-html5 .rst-content aside.footnote tt,html.writer-html5 .rst-content div.citation-list>div.citation code,html.writer-html5 .rst-content div.citation-list>div.citation tt,html.writer-html5 .rst-content dl.citation code,html.writer-html5 .rst-content dl.citation tt,html.writer-html5 .rst-content dl.footnote code,html.writer-html5 .rst-content dl.footnote tt{color:#555}.rst-content .wy-table-responsive.citation,.rst-content .wy-table-responsive.footnote{margin-bottom:0}.rst-content .wy-table-responsive.citation+:not(.citation),.rst-content .wy-table-responsive.footnote+:not(.footnote){margin-top:24px}.rst-content .wy-table-responsive.citation:last-child,.rst-content .wy-table-responsive.footnote:last-child{margin-bottom:24px}.rst-content table.docutils th{border-color:#e1e4e5}html.writer-html5 .rst-content table.docutils th{border:1px solid #e1e4e5}html.writer-html5 .rst-content table.docutils td>p,html.writer-html5 .rst-content table.docutils th>p{line-height:1rem;margin-bottom:0;font-size:.9rem}.rst-content table.docutils td .last,.rst-content table.docutils td .last>:last-child{margin-bottom:0}.rst-content table.field-list,.rst-content table.field-list td{border:none}.rst-content table.field-list td p{line-height:inherit}.rst-content table.field-list td>strong{display:inline-block}.rst-content table.field-list .field-name{padding-right:10px;text-align:left;white-space:nowrap}.rst-content table.field-list .field-body{text-align:left}.rst-content code,.rst-content tt{color:#000;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;padding:2px 5px}.rst-content code big,.rst-content code em,.rst-content tt big,.rst-content tt em{font-size:100%!important;line-height:normal}.rst-content code.literal,.rst-content tt.literal{color:#e74c3c;white-space:normal}.rst-content code.xref,.rst-content tt.xref,a .rst-content code,a .rst-content tt{font-weight:700;color:#404040;overflow-wrap:normal}.rst-content kbd,.rst-content pre,.rst-content samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace}.rst-content a code,.rst-content a tt{color:#2980b9}.rst-content dl{margin-bottom:24px}.rst-content dl dt{font-weight:700;margin-bottom:12px}.rst-content dl ol,.rst-content dl p,.rst-content dl table,.rst-content dl ul{margin-bottom:12px}.rst-content dl dd{margin:0 0 12px 24px;line-height:24px}.rst-content dl dd>ol:last-child,.rst-content dl dd>p:last-child,.rst-content dl dd>table:last-child,.rst-content dl dd>ul:last-child{margin-bottom:0}html.writer-html4 .rst-content dl:not(.docutils),html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple){margin-bottom:24px}html.writer-html4 .rst-content dl:not(.docutils)>dt,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt{display:table;margin:6px 0;font-size:90%;line-height:normal;background:#e7f2fa;color:#2980b9;border-top:3px solid #6ab0de;padding:6px;position:relative}html.writer-html4 .rst-content dl:not(.docutils)>dt:before,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt:before{color:#6ab0de}html.writer-html4 .rst-content dl:not(.docutils)>dt .headerlink,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt .headerlink{color:#404040;font-size:100%!important}html.writer-html4 .rst-content dl:not(.docutils) dl:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) dl:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt{margin-bottom:6px;border:none;border-left:3px solid #ccc;background:#f0f0f0;color:#555}html.writer-html4 .rst-content dl:not(.docutils) dl:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt .headerlink,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) dl:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt .headerlink{color:#404040;font-size:100%!important}html.writer-html4 .rst-content dl:not(.docutils)>dt:first-child,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple)>dt:first-child{margin-top:0}html.writer-html4 .rst-content dl:not(.docutils) code.descclassname,html.writer-html4 .rst-content dl:not(.docutils) code.descname,html.writer-html4 .rst-content dl:not(.docutils) tt.descclassname,html.writer-html4 .rst-content dl:not(.docutils) tt.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) code.descclassname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) code.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) tt.descclassname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) tt.descname{background-color:transparent;border:none;padding:0;font-size:100%!important}html.writer-html4 .rst-content dl:not(.docutils) code.descname,html.writer-html4 .rst-content dl:not(.docutils) tt.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) code.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) tt.descname{font-weight:700}html.writer-html4 .rst-content dl:not(.docutils) .optional,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) .optional{display:inline-block;padding:0 4px;color:#000;font-weight:700}html.writer-html4 .rst-content dl:not(.docutils) .property,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) .property{display:inline-block;padding-right:8px;max-width:100%}html.writer-html4 .rst-content dl:not(.docutils) .k,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) .k{font-style:italic}html.writer-html4 .rst-content dl:not(.docutils) .descclassname,html.writer-html4 .rst-content dl:not(.docutils) .descname,html.writer-html4 .rst-content dl:not(.docutils) .sig-name,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) .descclassname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) .descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.citation):not(.glossary):not(.simple) .sig-name{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;color:#000}.rst-content .viewcode-back,.rst-content .viewcode-link{display:inline-block;color:#27ae60;font-size:80%;padding-left:24px}.rst-content .viewcode-back{display:block;float:right}.rst-content p.rubric{margin-bottom:12px;font-weight:700}.rst-content code.download,.rst-content tt.download{background:inherit;padding:inherit;font-weight:400;font-family:inherit;font-size:inherit;color:inherit;border:inherit;white-space:inherit}.rst-content code.download span:first-child,.rst-content tt.download span:first-child{-webkit-font-smoothing:subpixel-antialiased}.rst-content code.download span:first-child:before,.rst-content tt.download span:first-child:before{margin-right:4px}.rst-content .guilabel{border:1px solid #7fbbe3;background:#e7f2fa;font-size:80%;font-weight:700;border-radius:4px;padding:2.4px 6px;margin:auto 2px}.rst-content :not(dl.option-list)>:not(dt):not(kbd):not(.kbd)>.kbd,.rst-content :not(dl.option-list)>:not(dt):not(kbd):not(.kbd)>kbd{color:inherit;font-size:80%;background-color:#fff;border:1px solid #a6a6a6;border-radius:4px;box-shadow:0 2px grey;padding:2.4px 6px;margin:auto 0}.rst-content .versionmodified{font-style:italic}@media screen and (max-width:480px){.rst-content .sidebar{width:100%}}span[id*=MathJax-Span]{color:#404040}.math{text-align:center}@font-face{font-family:Lato;src:url(fonts/lato-normal.woff2?bd03a2cc277bbbc338d464e679fe9942) format("woff2"),url(fonts/lato-normal.woff?27bd77b9162d388cb8d4c4217c7c5e2a) format("woff");font-weight:400;font-style:normal;font-display:block}@font-face{font-family:Lato;src:url(fonts/lato-bold.woff2?cccb897485813c7c256901dbca54ecf2) format("woff2"),url(fonts/lato-bold.woff?d878b6c29b10beca227e9eef4246111b) format("woff");font-weight:700;font-style:normal;font-display:block}@font-face{font-family:Lato;src:url(fonts/lato-bold-italic.woff2?0b6bb6725576b072c5d0b02ecdd1900d) format("woff2"),url(fonts/lato-bold-italic.woff?9c7e4e9eb485b4a121c760e61bc3707c) format("woff");font-weight:700;font-style:italic;font-display:block}@font-face{font-family:Lato;src:url(fonts/lato-normal-italic.woff2?4eb103b4d12be57cb1d040ed5e162e9d) format("woff2"),url(fonts/lato-normal-italic.woff?f28f2d6482446544ef1ea1ccc6dd5892) format("woff");font-weight:400;font-style:italic;font-display:block}@font-face{font-family:Roboto Slab;font-style:normal;font-weight:400;src:url(fonts/Roboto-Slab-Regular.woff2?7abf5b8d04d26a2cafea937019bca958) format("woff2"),url(fonts/Roboto-Slab-Regular.woff?c1be9284088d487c5e3ff0a10a92e58c) format("woff");font-display:block}@font-face{font-family:Roboto Slab;font-style:normal;font-weight:700;src:url(fonts/Roboto-Slab-Bold.woff2?9984f4a9bda09be08e83f2506954adbe) format("woff2"),url(fonts/Roboto-Slab-Bold.woff?bed5564a116b05148e3b3bea6fb1162a) format("woff");font-display:block} diff --git a/wiki/css/theme_extra.css b/wiki/css/theme_extra.css new file mode 100644 index 000000000..ab0631a18 --- /dev/null +++ b/wiki/css/theme_extra.css @@ -0,0 +1,197 @@ +/* + * Wrap inline code samples otherwise they shoot of the side and + * can't be read at all. + * + * https://github.com/mkdocs/mkdocs/issues/313 + * https://github.com/mkdocs/mkdocs/issues/233 + * https://github.com/mkdocs/mkdocs/issues/834 + */ +.rst-content code { + white-space: pre-wrap; + word-wrap: break-word; + padding: 2px 5px; +} + +/** + * Make code blocks display as blocks and give them the appropriate + * font size and padding. + * + * https://github.com/mkdocs/mkdocs/issues/855 + * https://github.com/mkdocs/mkdocs/issues/834 + * https://github.com/mkdocs/mkdocs/issues/233 + */ +.rst-content pre code { + white-space: pre; + word-wrap: normal; + display: block; + padding: 12px; + font-size: 12px; +} + +/** + * Fix code colors + * + * https://github.com/mkdocs/mkdocs/issues/2027 + */ +.rst-content code { + color: #E74C3C; +} + +.rst-content pre code { + color: #000; + background: #f8f8f8; +} + +/* + * Fix link colors when the link text is inline code. + * + * https://github.com/mkdocs/mkdocs/issues/718 + */ +a code { + color: #2980B9; +} +a:hover code { + color: #3091d1; +} +a:visited code { + color: #9B59B6; +} + +/* + * The CSS classes from highlight.js seem to clash with the + * ReadTheDocs theme causing some code to be incorrectly made + * bold and italic. + * + * https://github.com/mkdocs/mkdocs/issues/411 + */ +pre .cs, pre .c { + font-weight: inherit; + font-style: inherit; +} + +/* + * Fix some issues with the theme and non-highlighted code + * samples. Without and highlighting styles attached the + * formatting is broken. + * + * https://github.com/mkdocs/mkdocs/issues/319 + */ +.rst-content .no-highlight { + display: block; + padding: 0.5em; + color: #333; +} + + +/* + * Additions specific to the search functionality provided by MkDocs + */ + +.search-results { + margin-top: 23px; +} + +.search-results article { + border-top: 1px solid #E1E4E5; + padding-top: 24px; +} + +.search-results article:first-child { + border-top: none; +} + +form .search-query { + width: 100%; + border-radius: 50px; + padding: 6px 12px; + border-color: #D1D4D5; +} + +/* + * Improve inline code blocks within admonitions. + * + * https://github.com/mkdocs/mkdocs/issues/656 + */ + .rst-content .admonition code { + color: #404040; + border: 1px solid #c7c9cb; + border: 1px solid rgba(0, 0, 0, 0.2); + background: #f8fbfd; + background: rgba(255, 255, 255, 0.7); +} + +/* + * Account for wide tables which go off the side. + * Override borders to avoid weirdness on narrow tables. + * + * https://github.com/mkdocs/mkdocs/issues/834 + * https://github.com/mkdocs/mkdocs/pull/1034 + */ +.rst-content .section .docutils { + width: 100%; + overflow: auto; + display: block; + border: none; +} + +td, th { + border: 1px solid #e1e4e5 !important; + border-collapse: collapse; +} + +/* + * Without the following amendments, the navigation in the theme will be + * slightly cut off. This is due to the fact that the .wy-nav-side has a + * padding-bottom of 2em, which must not necessarily align with the font-size of + * 90 % on the .rst-current-version container, combined with the padding of 12px + * above and below. These amendments fix this in two steps: First, make sure the + * .rst-current-version container has a fixed height of 40px, achieved using + * line-height, and then applying a padding-bottom of 40px to this container. In + * a second step, the items within that container are re-aligned using flexbox. + * + * https://github.com/mkdocs/mkdocs/issues/2012 + */ + .wy-nav-side { + padding-bottom: 40px; +} + +/* For section-index only */ +.wy-menu-vertical .current-section p { + background-color: #e3e3e3; + color: #404040; +} + +/* + * The second step of above amendment: Here we make sure the items are aligned + * correctly within the .rst-current-version container. Using flexbox, we + * achieve it in such a way that it will look like the following: + * + * [No repo_name] + * Next >> // On the first page + * << Previous Next >> // On all subsequent pages + * + * [With repo_name] + * Next >> // On the first page + * << Previous Next >> // On all subsequent pages + * + * https://github.com/mkdocs/mkdocs/issues/2012 + */ +.rst-versions .rst-current-version { + padding: 0 12px; + display: flex; + font-size: initial; + justify-content: space-between; + align-items: center; + line-height: 40px; +} + +/* + * Please note that this amendment also involves removing certain inline-styles + * from the file ./mkdocs/themes/readthedocs/versions.html. + * + * https://github.com/mkdocs/mkdocs/issues/2012 + */ +.rst-current-version span { + flex: 1; + text-align: center; +} diff --git a/wiki/filters/index.html b/wiki/filters/index.html new file mode 100644 index 000000000..fe7ce5017 --- /dev/null +++ b/wiki/filters/index.html @@ -0,0 +1,1304 @@ + + + + + + + + Filters - NLog Wiki + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+
+
+
+ +

See https://github.com/NLog/NLog/wiki/Filtering-log-messages

+ +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + « Previous + + + +
+ + + + + + + + + diff --git a/wiki/img/favicon.ico b/wiki/img/favicon.ico new file mode 100644 index 000000000..e85006a3c Binary files /dev/null and b/wiki/img/favicon.ico differ diff --git a/wiki/index.html b/wiki/index.html new file mode 100644 index 000000000..ca6880fd5 --- /dev/null +++ b/wiki/index.html @@ -0,0 +1,14 @@ + + + + + + Redirecting... + + + + + +You're being redirected to a new destination. + + diff --git a/wiki/js/html5shiv.min.js b/wiki/js/html5shiv.min.js new file mode 100644 index 000000000..1a01c94ba --- /dev/null +++ b/wiki/js/html5shiv.min.js @@ -0,0 +1,4 @@ +/** +* @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed +*/ +!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.3",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b),"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:this,document); diff --git a/wiki/js/jquery-3.6.0.min.js b/wiki/js/jquery-3.6.0.min.js new file mode 100644 index 000000000..c4c6022f2 --- /dev/null +++ b/wiki/js/jquery-3.6.0.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="
",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0"),n("table.docutils.footnote").wrap("
"),n("table.docutils.citation").wrap("
"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each((function(){var t=n(this);expand=n(''),expand.on("click",(function(n){return e.toggleCurrent(t),n.stopPropagation(),!1})),t.prepend(expand)}))},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),t=e.find('[href="'+n+'"]');if(0===t.length){var i=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(t=e.find('[href="#'+i.attr("id")+'"]')).length&&(t=e.find('[href="#"]'))}if(t.length>0){$(".wy-menu-vertical .current").removeClass("current").attr("aria-expanded","false"),t.addClass("current").attr("aria-expanded","true"),t.closest("li.toctree-l1").parent().addClass("current").attr("aria-expanded","true");for(let n=1;n<=10;n++)t.closest("li.toctree-l"+n).addClass("current").attr("aria-expanded","true");t[0].scrollIntoView()}}catch(n){console.log("Error expanding nav for anchor",n)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,t=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(t),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",(function(){this.linkScroll=!1}))},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current").attr("aria-expanded","false"),e.siblings().find("li.current").removeClass("current").attr("aria-expanded","false");var t=e.find("> ul li");t.length&&(t.removeClass("current").attr("aria-expanded","false"),e.toggleClass("current").attr("aria-expanded",(function(n,e){return"true"==e?"false":"true"})))}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:n.exports.ThemeNav,StickyNav:n.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],t=0;t + + + + + + + NLog Wiki + + + + + + + + + + + +
+ + +
+ +
+
+
    +
  • +
  • +
  • +
+
+
+
+
+ + +

Search Results

+ + + +
+ Searching... +
+ + +
+
+ +
+
+ +
+ +
+ +
+ + + + GitHub + + + + + +
+ + + + + + + + + diff --git a/wiki/search/lunr.js b/wiki/search/lunr.js new file mode 100644 index 000000000..aca0a167f --- /dev/null +++ b/wiki/search/lunr.js @@ -0,0 +1,3475 @@ +/** + * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9 + * Copyright (C) 2020 Oliver Nightingale + * @license MIT + */ + +;(function(){ + +/** + * A convenience function for configuring and constructing + * a new lunr Index. + * + * A lunr.Builder instance is created and the pipeline setup + * with a trimmer, stop word filter and stemmer. + * + * This builder object is yielded to the configuration function + * that is passed as a parameter, allowing the list of fields + * and other builder parameters to be customised. + * + * All documents _must_ be added within the passed config function. + * + * @example + * var idx = lunr(function () { + * this.field('title') + * this.field('body') + * this.ref('id') + * + * documents.forEach(function (doc) { + * this.add(doc) + * }, this) + * }) + * + * @see {@link lunr.Builder} + * @see {@link lunr.Pipeline} + * @see {@link lunr.trimmer} + * @see {@link lunr.stopWordFilter} + * @see {@link lunr.stemmer} + * @namespace {function} lunr + */ +var lunr = function (config) { + var builder = new lunr.Builder + + builder.pipeline.add( + lunr.trimmer, + lunr.stopWordFilter, + lunr.stemmer + ) + + builder.searchPipeline.add( + lunr.stemmer + ) + + config.call(builder, builder) + return builder.build() +} + +lunr.version = "2.3.9" +/*! + * lunr.utils + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A namespace containing utils for the rest of the lunr library + * @namespace lunr.utils + */ +lunr.utils = {} + +/** + * Print a warning message to the console. + * + * @param {String} message The message to be printed. + * @memberOf lunr.utils + * @function + */ +lunr.utils.warn = (function (global) { + /* eslint-disable no-console */ + return function (message) { + if (global.console && console.warn) { + console.warn(message) + } + } + /* eslint-enable no-console */ +})(this) + +/** + * Convert an object to a string. + * + * In the case of `null` and `undefined` the function returns + * the empty string, in all other cases the result of calling + * `toString` on the passed object is returned. + * + * @param {Any} obj The object to convert to a string. + * @return {String} string representation of the passed object. + * @memberOf lunr.utils + */ +lunr.utils.asString = function (obj) { + if (obj === void 0 || obj === null) { + return "" + } else { + return obj.toString() + } +} + +/** + * Clones an object. + * + * Will create a copy of an existing object such that any mutations + * on the copy cannot affect the original. + * + * Only shallow objects are supported, passing a nested object to this + * function will cause a TypeError. + * + * Objects with primitives, and arrays of primitives are supported. + * + * @param {Object} obj The object to clone. + * @return {Object} a clone of the passed object. + * @throws {TypeError} when a nested object is passed. + * @memberOf Utils + */ +lunr.utils.clone = function (obj) { + if (obj === null || obj === undefined) { + return obj + } + + var clone = Object.create(null), + keys = Object.keys(obj) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i], + val = obj[key] + + if (Array.isArray(val)) { + clone[key] = val.slice() + continue + } + + if (typeof val === 'string' || + typeof val === 'number' || + typeof val === 'boolean') { + clone[key] = val + continue + } + + throw new TypeError("clone is not deep and does not support nested objects") + } + + return clone +} +lunr.FieldRef = function (docRef, fieldName, stringValue) { + this.docRef = docRef + this.fieldName = fieldName + this._stringValue = stringValue +} + +lunr.FieldRef.joiner = "/" + +lunr.FieldRef.fromString = function (s) { + var n = s.indexOf(lunr.FieldRef.joiner) + + if (n === -1) { + throw "malformed field ref string" + } + + var fieldRef = s.slice(0, n), + docRef = s.slice(n + 1) + + return new lunr.FieldRef (docRef, fieldRef, s) +} + +lunr.FieldRef.prototype.toString = function () { + if (this._stringValue == undefined) { + this._stringValue = this.fieldName + lunr.FieldRef.joiner + this.docRef + } + + return this._stringValue +} +/*! + * lunr.Set + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A lunr set. + * + * @constructor + */ +lunr.Set = function (elements) { + this.elements = Object.create(null) + + if (elements) { + this.length = elements.length + + for (var i = 0; i < this.length; i++) { + this.elements[elements[i]] = true + } + } else { + this.length = 0 + } +} + +/** + * A complete set that contains all elements. + * + * @static + * @readonly + * @type {lunr.Set} + */ +lunr.Set.complete = { + intersect: function (other) { + return other + }, + + union: function () { + return this + }, + + contains: function () { + return true + } +} + +/** + * An empty set that contains no elements. + * + * @static + * @readonly + * @type {lunr.Set} + */ +lunr.Set.empty = { + intersect: function () { + return this + }, + + union: function (other) { + return other + }, + + contains: function () { + return false + } +} + +/** + * Returns true if this set contains the specified object. + * + * @param {object} object - Object whose presence in this set is to be tested. + * @returns {boolean} - True if this set contains the specified object. + */ +lunr.Set.prototype.contains = function (object) { + return !!this.elements[object] +} + +/** + * Returns a new set containing only the elements that are present in both + * this set and the specified set. + * + * @param {lunr.Set} other - set to intersect with this set. + * @returns {lunr.Set} a new set that is the intersection of this and the specified set. + */ + +lunr.Set.prototype.intersect = function (other) { + var a, b, elements, intersection = [] + + if (other === lunr.Set.complete) { + return this + } + + if (other === lunr.Set.empty) { + return other + } + + if (this.length < other.length) { + a = this + b = other + } else { + a = other + b = this + } + + elements = Object.keys(a.elements) + + for (var i = 0; i < elements.length; i++) { + var element = elements[i] + if (element in b.elements) { + intersection.push(element) + } + } + + return new lunr.Set (intersection) +} + +/** + * Returns a new set combining the elements of this and the specified set. + * + * @param {lunr.Set} other - set to union with this set. + * @return {lunr.Set} a new set that is the union of this and the specified set. + */ + +lunr.Set.prototype.union = function (other) { + if (other === lunr.Set.complete) { + return lunr.Set.complete + } + + if (other === lunr.Set.empty) { + return this + } + + return new lunr.Set(Object.keys(this.elements).concat(Object.keys(other.elements))) +} +/** + * A function to calculate the inverse document frequency for + * a posting. This is shared between the builder and the index + * + * @private + * @param {object} posting - The posting for a given term + * @param {number} documentCount - The total number of documents. + */ +lunr.idf = function (posting, documentCount) { + var documentsWithTerm = 0 + + for (var fieldName in posting) { + if (fieldName == '_index') continue // Ignore the term index, its not a field + documentsWithTerm += Object.keys(posting[fieldName]).length + } + + var x = (documentCount - documentsWithTerm + 0.5) / (documentsWithTerm + 0.5) + + return Math.log(1 + Math.abs(x)) +} + +/** + * A token wraps a string representation of a token + * as it is passed through the text processing pipeline. + * + * @constructor + * @param {string} [str=''] - The string token being wrapped. + * @param {object} [metadata={}] - Metadata associated with this token. + */ +lunr.Token = function (str, metadata) { + this.str = str || "" + this.metadata = metadata || {} +} + +/** + * Returns the token string that is being wrapped by this object. + * + * @returns {string} + */ +lunr.Token.prototype.toString = function () { + return this.str +} + +/** + * A token update function is used when updating or optionally + * when cloning a token. + * + * @callback lunr.Token~updateFunction + * @param {string} str - The string representation of the token. + * @param {Object} metadata - All metadata associated with this token. + */ + +/** + * Applies the given function to the wrapped string token. + * + * @example + * token.update(function (str, metadata) { + * return str.toUpperCase() + * }) + * + * @param {lunr.Token~updateFunction} fn - A function to apply to the token string. + * @returns {lunr.Token} + */ +lunr.Token.prototype.update = function (fn) { + this.str = fn(this.str, this.metadata) + return this +} + +/** + * Creates a clone of this token. Optionally a function can be + * applied to the cloned token. + * + * @param {lunr.Token~updateFunction} [fn] - An optional function to apply to the cloned token. + * @returns {lunr.Token} + */ +lunr.Token.prototype.clone = function (fn) { + fn = fn || function (s) { return s } + return new lunr.Token (fn(this.str, this.metadata), this.metadata) +} +/*! + * lunr.tokenizer + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A function for splitting a string into tokens ready to be inserted into + * the search index. Uses `lunr.tokenizer.separator` to split strings, change + * the value of this property to change how strings are split into tokens. + * + * This tokenizer will convert its parameter to a string by calling `toString` and + * then will split this string on the character in `lunr.tokenizer.separator`. + * Arrays will have their elements converted to strings and wrapped in a lunr.Token. + * + * Optional metadata can be passed to the tokenizer, this metadata will be cloned and + * added as metadata to every token that is created from the object to be tokenized. + * + * @static + * @param {?(string|object|object[])} obj - The object to convert into tokens + * @param {?object} metadata - Optional metadata to associate with every token + * @returns {lunr.Token[]} + * @see {@link lunr.Pipeline} + */ +lunr.tokenizer = function (obj, metadata) { + if (obj == null || obj == undefined) { + return [] + } + + if (Array.isArray(obj)) { + return obj.map(function (t) { + return new lunr.Token( + lunr.utils.asString(t).toLowerCase(), + lunr.utils.clone(metadata) + ) + }) + } + + var str = obj.toString().toLowerCase(), + len = str.length, + tokens = [] + + for (var sliceEnd = 0, sliceStart = 0; sliceEnd <= len; sliceEnd++) { + var char = str.charAt(sliceEnd), + sliceLength = sliceEnd - sliceStart + + if ((char.match(lunr.tokenizer.separator) || sliceEnd == len)) { + + if (sliceLength > 0) { + var tokenMetadata = lunr.utils.clone(metadata) || {} + tokenMetadata["position"] = [sliceStart, sliceLength] + tokenMetadata["index"] = tokens.length + + tokens.push( + new lunr.Token ( + str.slice(sliceStart, sliceEnd), + tokenMetadata + ) + ) + } + + sliceStart = sliceEnd + 1 + } + + } + + return tokens +} + +/** + * The separator used to split a string into tokens. Override this property to change the behaviour of + * `lunr.tokenizer` behaviour when tokenizing strings. By default this splits on whitespace and hyphens. + * + * @static + * @see lunr.tokenizer + */ +lunr.tokenizer.separator = /[\s\-]+/ +/*! + * lunr.Pipeline + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.Pipelines maintain an ordered list of functions to be applied to all + * tokens in documents entering the search index and queries being ran against + * the index. + * + * An instance of lunr.Index created with the lunr shortcut will contain a + * pipeline with a stop word filter and an English language stemmer. Extra + * functions can be added before or after either of these functions or these + * default functions can be removed. + * + * When run the pipeline will call each function in turn, passing a token, the + * index of that token in the original list of all tokens and finally a list of + * all the original tokens. + * + * The output of functions in the pipeline will be passed to the next function + * in the pipeline. To exclude a token from entering the index the function + * should return undefined, the rest of the pipeline will not be called with + * this token. + * + * For serialisation of pipelines to work, all functions used in an instance of + * a pipeline should be registered with lunr.Pipeline. Registered functions can + * then be loaded. If trying to load a serialised pipeline that uses functions + * that are not registered an error will be thrown. + * + * If not planning on serialising the pipeline then registering pipeline functions + * is not necessary. + * + * @constructor + */ +lunr.Pipeline = function () { + this._stack = [] +} + +lunr.Pipeline.registeredFunctions = Object.create(null) + +/** + * A pipeline function maps lunr.Token to lunr.Token. A lunr.Token contains the token + * string as well as all known metadata. A pipeline function can mutate the token string + * or mutate (or add) metadata for a given token. + * + * A pipeline function can indicate that the passed token should be discarded by returning + * null, undefined or an empty string. This token will not be passed to any downstream pipeline + * functions and will not be added to the index. + * + * Multiple tokens can be returned by returning an array of tokens. Each token will be passed + * to any downstream pipeline functions and all will returned tokens will be added to the index. + * + * Any number of pipeline functions may be chained together using a lunr.Pipeline. + * + * @interface lunr.PipelineFunction + * @param {lunr.Token} token - A token from the document being processed. + * @param {number} i - The index of this token in the complete list of tokens for this document/field. + * @param {lunr.Token[]} tokens - All tokens for this document/field. + * @returns {(?lunr.Token|lunr.Token[])} + */ + +/** + * Register a function with the pipeline. + * + * Functions that are used in the pipeline should be registered if the pipeline + * needs to be serialised, or a serialised pipeline needs to be loaded. + * + * Registering a function does not add it to a pipeline, functions must still be + * added to instances of the pipeline for them to be used when running a pipeline. + * + * @param {lunr.PipelineFunction} fn - The function to check for. + * @param {String} label - The label to register this function with + */ +lunr.Pipeline.registerFunction = function (fn, label) { + if (label in this.registeredFunctions) { + lunr.utils.warn('Overwriting existing registered function: ' + label) + } + + fn.label = label + lunr.Pipeline.registeredFunctions[fn.label] = fn +} + +/** + * Warns if the function is not registered as a Pipeline function. + * + * @param {lunr.PipelineFunction} fn - The function to check for. + * @private + */ +lunr.Pipeline.warnIfFunctionNotRegistered = function (fn) { + var isRegistered = fn.label && (fn.label in this.registeredFunctions) + + if (!isRegistered) { + lunr.utils.warn('Function is not registered with pipeline. This may cause problems when serialising the index.\n', fn) + } +} + +/** + * Loads a previously serialised pipeline. + * + * All functions to be loaded must already be registered with lunr.Pipeline. + * If any function from the serialised data has not been registered then an + * error will be thrown. + * + * @param {Object} serialised - The serialised pipeline to load. + * @returns {lunr.Pipeline} + */ +lunr.Pipeline.load = function (serialised) { + var pipeline = new lunr.Pipeline + + serialised.forEach(function (fnName) { + var fn = lunr.Pipeline.registeredFunctions[fnName] + + if (fn) { + pipeline.add(fn) + } else { + throw new Error('Cannot load unregistered function: ' + fnName) + } + }) + + return pipeline +} + +/** + * Adds new functions to the end of the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param {lunr.PipelineFunction[]} functions - Any number of functions to add to the pipeline. + */ +lunr.Pipeline.prototype.add = function () { + var fns = Array.prototype.slice.call(arguments) + + fns.forEach(function (fn) { + lunr.Pipeline.warnIfFunctionNotRegistered(fn) + this._stack.push(fn) + }, this) +} + +/** + * Adds a single function after a function that already exists in the + * pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline. + * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline. + */ +lunr.Pipeline.prototype.after = function (existingFn, newFn) { + lunr.Pipeline.warnIfFunctionNotRegistered(newFn) + + var pos = this._stack.indexOf(existingFn) + if (pos == -1) { + throw new Error('Cannot find existingFn') + } + + pos = pos + 1 + this._stack.splice(pos, 0, newFn) +} + +/** + * Adds a single function before a function that already exists in the + * pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline. + * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline. + */ +lunr.Pipeline.prototype.before = function (existingFn, newFn) { + lunr.Pipeline.warnIfFunctionNotRegistered(newFn) + + var pos = this._stack.indexOf(existingFn) + if (pos == -1) { + throw new Error('Cannot find existingFn') + } + + this._stack.splice(pos, 0, newFn) +} + +/** + * Removes a function from the pipeline. + * + * @param {lunr.PipelineFunction} fn The function to remove from the pipeline. + */ +lunr.Pipeline.prototype.remove = function (fn) { + var pos = this._stack.indexOf(fn) + if (pos == -1) { + return + } + + this._stack.splice(pos, 1) +} + +/** + * Runs the current list of functions that make up the pipeline against the + * passed tokens. + * + * @param {Array} tokens The tokens to run through the pipeline. + * @returns {Array} + */ +lunr.Pipeline.prototype.run = function (tokens) { + var stackLength = this._stack.length + + for (var i = 0; i < stackLength; i++) { + var fn = this._stack[i] + var memo = [] + + for (var j = 0; j < tokens.length; j++) { + var result = fn(tokens[j], j, tokens) + + if (result === null || result === void 0 || result === '') continue + + if (Array.isArray(result)) { + for (var k = 0; k < result.length; k++) { + memo.push(result[k]) + } + } else { + memo.push(result) + } + } + + tokens = memo + } + + return tokens +} + +/** + * Convenience method for passing a string through a pipeline and getting + * strings out. This method takes care of wrapping the passed string in a + * token and mapping the resulting tokens back to strings. + * + * @param {string} str - The string to pass through the pipeline. + * @param {?object} metadata - Optional metadata to associate with the token + * passed to the pipeline. + * @returns {string[]} + */ +lunr.Pipeline.prototype.runString = function (str, metadata) { + var token = new lunr.Token (str, metadata) + + return this.run([token]).map(function (t) { + return t.toString() + }) +} + +/** + * Resets the pipeline by removing any existing processors. + * + */ +lunr.Pipeline.prototype.reset = function () { + this._stack = [] +} + +/** + * Returns a representation of the pipeline ready for serialisation. + * + * Logs a warning if the function has not been registered. + * + * @returns {Array} + */ +lunr.Pipeline.prototype.toJSON = function () { + return this._stack.map(function (fn) { + lunr.Pipeline.warnIfFunctionNotRegistered(fn) + + return fn.label + }) +} +/*! + * lunr.Vector + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A vector is used to construct the vector space of documents and queries. These + * vectors support operations to determine the similarity between two documents or + * a document and a query. + * + * Normally no parameters are required for initializing a vector, but in the case of + * loading a previously dumped vector the raw elements can be provided to the constructor. + * + * For performance reasons vectors are implemented with a flat array, where an elements + * index is immediately followed by its value. E.g. [index, value, index, value]. This + * allows the underlying array to be as sparse as possible and still offer decent + * performance when being used for vector calculations. + * + * @constructor + * @param {Number[]} [elements] - The flat list of element index and element value pairs. + */ +lunr.Vector = function (elements) { + this._magnitude = 0 + this.elements = elements || [] +} + + +/** + * Calculates the position within the vector to insert a given index. + * + * This is used internally by insert and upsert. If there are duplicate indexes then + * the position is returned as if the value for that index were to be updated, but it + * is the callers responsibility to check whether there is a duplicate at that index + * + * @param {Number} insertIdx - The index at which the element should be inserted. + * @returns {Number} + */ +lunr.Vector.prototype.positionForIndex = function (index) { + // For an empty vector the tuple can be inserted at the beginning + if (this.elements.length == 0) { + return 0 + } + + var start = 0, + end = this.elements.length / 2, + sliceLength = end - start, + pivotPoint = Math.floor(sliceLength / 2), + pivotIndex = this.elements[pivotPoint * 2] + + while (sliceLength > 1) { + if (pivotIndex < index) { + start = pivotPoint + } + + if (pivotIndex > index) { + end = pivotPoint + } + + if (pivotIndex == index) { + break + } + + sliceLength = end - start + pivotPoint = start + Math.floor(sliceLength / 2) + pivotIndex = this.elements[pivotPoint * 2] + } + + if (pivotIndex == index) { + return pivotPoint * 2 + } + + if (pivotIndex > index) { + return pivotPoint * 2 + } + + if (pivotIndex < index) { + return (pivotPoint + 1) * 2 + } +} + +/** + * Inserts an element at an index within the vector. + * + * Does not allow duplicates, will throw an error if there is already an entry + * for this index. + * + * @param {Number} insertIdx - The index at which the element should be inserted. + * @param {Number} val - The value to be inserted into the vector. + */ +lunr.Vector.prototype.insert = function (insertIdx, val) { + this.upsert(insertIdx, val, function () { + throw "duplicate index" + }) +} + +/** + * Inserts or updates an existing index within the vector. + * + * @param {Number} insertIdx - The index at which the element should be inserted. + * @param {Number} val - The value to be inserted into the vector. + * @param {function} fn - A function that is called for updates, the existing value and the + * requested value are passed as arguments + */ +lunr.Vector.prototype.upsert = function (insertIdx, val, fn) { + this._magnitude = 0 + var position = this.positionForIndex(insertIdx) + + if (this.elements[position] == insertIdx) { + this.elements[position + 1] = fn(this.elements[position + 1], val) + } else { + this.elements.splice(position, 0, insertIdx, val) + } +} + +/** + * Calculates the magnitude of this vector. + * + * @returns {Number} + */ +lunr.Vector.prototype.magnitude = function () { + if (this._magnitude) return this._magnitude + + var sumOfSquares = 0, + elementsLength = this.elements.length + + for (var i = 1; i < elementsLength; i += 2) { + var val = this.elements[i] + sumOfSquares += val * val + } + + return this._magnitude = Math.sqrt(sumOfSquares) +} + +/** + * Calculates the dot product of this vector and another vector. + * + * @param {lunr.Vector} otherVector - The vector to compute the dot product with. + * @returns {Number} + */ +lunr.Vector.prototype.dot = function (otherVector) { + var dotProduct = 0, + a = this.elements, b = otherVector.elements, + aLen = a.length, bLen = b.length, + aVal = 0, bVal = 0, + i = 0, j = 0 + + while (i < aLen && j < bLen) { + aVal = a[i], bVal = b[j] + if (aVal < bVal) { + i += 2 + } else if (aVal > bVal) { + j += 2 + } else if (aVal == bVal) { + dotProduct += a[i + 1] * b[j + 1] + i += 2 + j += 2 + } + } + + return dotProduct +} + +/** + * Calculates the similarity between this vector and another vector. + * + * @param {lunr.Vector} otherVector - The other vector to calculate the + * similarity with. + * @returns {Number} + */ +lunr.Vector.prototype.similarity = function (otherVector) { + return this.dot(otherVector) / this.magnitude() || 0 +} + +/** + * Converts the vector to an array of the elements within the vector. + * + * @returns {Number[]} + */ +lunr.Vector.prototype.toArray = function () { + var output = new Array (this.elements.length / 2) + + for (var i = 1, j = 0; i < this.elements.length; i += 2, j++) { + output[j] = this.elements[i] + } + + return output +} + +/** + * A JSON serializable representation of the vector. + * + * @returns {Number[]} + */ +lunr.Vector.prototype.toJSON = function () { + return this.elements +} +/* eslint-disable */ +/*! + * lunr.stemmer + * Copyright (C) 2020 Oliver Nightingale + * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt + */ + +/** + * lunr.stemmer is an english language stemmer, this is a JavaScript + * implementation of the PorterStemmer taken from http://tartarus.org/~martin + * + * @static + * @implements {lunr.PipelineFunction} + * @param {lunr.Token} token - The string to stem + * @returns {lunr.Token} + * @see {@link lunr.Pipeline} + * @function + */ +lunr.stemmer = (function(){ + var step2list = { + "ational" : "ate", + "tional" : "tion", + "enci" : "ence", + "anci" : "ance", + "izer" : "ize", + "bli" : "ble", + "alli" : "al", + "entli" : "ent", + "eli" : "e", + "ousli" : "ous", + "ization" : "ize", + "ation" : "ate", + "ator" : "ate", + "alism" : "al", + "iveness" : "ive", + "fulness" : "ful", + "ousness" : "ous", + "aliti" : "al", + "iviti" : "ive", + "biliti" : "ble", + "logi" : "log" + }, + + step3list = { + "icate" : "ic", + "ative" : "", + "alize" : "al", + "iciti" : "ic", + "ical" : "ic", + "ful" : "", + "ness" : "" + }, + + c = "[^aeiou]", // consonant + v = "[aeiouy]", // vowel + C = c + "[^aeiouy]*", // consonant sequence + V = v + "[aeiou]*", // vowel sequence + + mgr0 = "^(" + C + ")?" + V + C, // [C]VC... is m>0 + meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$", // [C]VC[V] is m=1 + mgr1 = "^(" + C + ")?" + V + C + V + C, // [C]VCVC... is m>1 + s_v = "^(" + C + ")?" + v; // vowel in stem + + var re_mgr0 = new RegExp(mgr0); + var re_mgr1 = new RegExp(mgr1); + var re_meq1 = new RegExp(meq1); + var re_s_v = new RegExp(s_v); + + var re_1a = /^(.+?)(ss|i)es$/; + var re2_1a = /^(.+?)([^s])s$/; + var re_1b = /^(.+?)eed$/; + var re2_1b = /^(.+?)(ed|ing)$/; + var re_1b_2 = /.$/; + var re2_1b_2 = /(at|bl|iz)$/; + var re3_1b_2 = new RegExp("([^aeiouylsz])\\1$"); + var re4_1b_2 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + + var re_1c = /^(.+?[^aeiou])y$/; + var re_2 = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; + + var re_3 = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; + + var re_4 = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; + var re2_4 = /^(.+?)(s|t)(ion)$/; + + var re_5 = /^(.+?)e$/; + var re_5_1 = /ll$/; + var re3_5 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + + var porterStemmer = function porterStemmer(w) { + var stem, + suffix, + firstch, + re, + re2, + re3, + re4; + + if (w.length < 3) { return w; } + + firstch = w.substr(0,1); + if (firstch == "y") { + w = firstch.toUpperCase() + w.substr(1); + } + + // Step 1a + re = re_1a + re2 = re2_1a; + + if (re.test(w)) { w = w.replace(re,"$1$2"); } + else if (re2.test(w)) { w = w.replace(re2,"$1$2"); } + + // Step 1b + re = re_1b; + re2 = re2_1b; + if (re.test(w)) { + var fp = re.exec(w); + re = re_mgr0; + if (re.test(fp[1])) { + re = re_1b_2; + w = w.replace(re,""); + } + } else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1]; + re2 = re_s_v; + if (re2.test(stem)) { + w = stem; + re2 = re2_1b_2; + re3 = re3_1b_2; + re4 = re4_1b_2; + if (re2.test(w)) { w = w + "e"; } + else if (re3.test(w)) { re = re_1b_2; w = w.replace(re,""); } + else if (re4.test(w)) { w = w + "e"; } + } + } + + // Step 1c - replace suffix y or Y by i if preceded by a non-vowel which is not the first letter of the word (so cry -> cri, by -> by, say -> say) + re = re_1c; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + w = stem + "i"; + } + + // Step 2 + re = re_2; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = re_mgr0; + if (re.test(stem)) { + w = stem + step2list[suffix]; + } + } + + // Step 3 + re = re_3; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = re_mgr0; + if (re.test(stem)) { + w = stem + step3list[suffix]; + } + } + + // Step 4 + re = re_4; + re2 = re2_4; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = re_mgr1; + if (re.test(stem)) { + w = stem; + } + } else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1] + fp[2]; + re2 = re_mgr1; + if (re2.test(stem)) { + w = stem; + } + } + + // Step 5 + re = re_5; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = re_mgr1; + re2 = re_meq1; + re3 = re3_5; + if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) { + w = stem; + } + } + + re = re_5_1; + re2 = re_mgr1; + if (re.test(w) && re2.test(w)) { + re = re_1b_2; + w = w.replace(re,""); + } + + // and turn initial Y back to y + + if (firstch == "y") { + w = firstch.toLowerCase() + w.substr(1); + } + + return w; + }; + + return function (token) { + return token.update(porterStemmer); + } +})(); + +lunr.Pipeline.registerFunction(lunr.stemmer, 'stemmer') +/*! + * lunr.stopWordFilter + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.generateStopWordFilter builds a stopWordFilter function from the provided + * list of stop words. + * + * The built in lunr.stopWordFilter is built using this generator and can be used + * to generate custom stopWordFilters for applications or non English languages. + * + * @function + * @param {Array} token The token to pass through the filter + * @returns {lunr.PipelineFunction} + * @see lunr.Pipeline + * @see lunr.stopWordFilter + */ +lunr.generateStopWordFilter = function (stopWords) { + var words = stopWords.reduce(function (memo, stopWord) { + memo[stopWord] = stopWord + return memo + }, {}) + + return function (token) { + if (token && words[token.toString()] !== token.toString()) return token + } +} + +/** + * lunr.stopWordFilter is an English language stop word list filter, any words + * contained in the list will not be passed through the filter. + * + * This is intended to be used in the Pipeline. If the token does not pass the + * filter then undefined will be returned. + * + * @function + * @implements {lunr.PipelineFunction} + * @params {lunr.Token} token - A token to check for being a stop word. + * @returns {lunr.Token} + * @see {@link lunr.Pipeline} + */ +lunr.stopWordFilter = lunr.generateStopWordFilter([ + 'a', + 'able', + 'about', + 'across', + 'after', + 'all', + 'almost', + 'also', + 'am', + 'among', + 'an', + 'and', + 'any', + 'are', + 'as', + 'at', + 'be', + 'because', + 'been', + 'but', + 'by', + 'can', + 'cannot', + 'could', + 'dear', + 'did', + 'do', + 'does', + 'either', + 'else', + 'ever', + 'every', + 'for', + 'from', + 'get', + 'got', + 'had', + 'has', + 'have', + 'he', + 'her', + 'hers', + 'him', + 'his', + 'how', + 'however', + 'i', + 'if', + 'in', + 'into', + 'is', + 'it', + 'its', + 'just', + 'least', + 'let', + 'like', + 'likely', + 'may', + 'me', + 'might', + 'most', + 'must', + 'my', + 'neither', + 'no', + 'nor', + 'not', + 'of', + 'off', + 'often', + 'on', + 'only', + 'or', + 'other', + 'our', + 'own', + 'rather', + 'said', + 'say', + 'says', + 'she', + 'should', + 'since', + 'so', + 'some', + 'than', + 'that', + 'the', + 'their', + 'them', + 'then', + 'there', + 'these', + 'they', + 'this', + 'tis', + 'to', + 'too', + 'twas', + 'us', + 'wants', + 'was', + 'we', + 'were', + 'what', + 'when', + 'where', + 'which', + 'while', + 'who', + 'whom', + 'why', + 'will', + 'with', + 'would', + 'yet', + 'you', + 'your' +]) + +lunr.Pipeline.registerFunction(lunr.stopWordFilter, 'stopWordFilter') +/*! + * lunr.trimmer + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.trimmer is a pipeline function for trimming non word + * characters from the beginning and end of tokens before they + * enter the index. + * + * This implementation may not work correctly for non latin + * characters and should either be removed or adapted for use + * with languages with non-latin characters. + * + * @static + * @implements {lunr.PipelineFunction} + * @param {lunr.Token} token The token to pass through the filter + * @returns {lunr.Token} + * @see lunr.Pipeline + */ +lunr.trimmer = function (token) { + return token.update(function (s) { + return s.replace(/^\W+/, '').replace(/\W+$/, '') + }) +} + +lunr.Pipeline.registerFunction(lunr.trimmer, 'trimmer') +/*! + * lunr.TokenSet + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A token set is used to store the unique list of all tokens + * within an index. Token sets are also used to represent an + * incoming query to the index, this query token set and index + * token set are then intersected to find which tokens to look + * up in the inverted index. + * + * A token set can hold multiple tokens, as in the case of the + * index token set, or it can hold a single token as in the + * case of a simple query token set. + * + * Additionally token sets are used to perform wildcard matching. + * Leading, contained and trailing wildcards are supported, and + * from this edit distance matching can also be provided. + * + * Token sets are implemented as a minimal finite state automata, + * where both common prefixes and suffixes are shared between tokens. + * This helps to reduce the space used for storing the token set. + * + * @constructor + */ +lunr.TokenSet = function () { + this.final = false + this.edges = {} + this.id = lunr.TokenSet._nextId + lunr.TokenSet._nextId += 1 +} + +/** + * Keeps track of the next, auto increment, identifier to assign + * to a new tokenSet. + * + * TokenSets require a unique identifier to be correctly minimised. + * + * @private + */ +lunr.TokenSet._nextId = 1 + +/** + * Creates a TokenSet instance from the given sorted array of words. + * + * @param {String[]} arr - A sorted array of strings to create the set from. + * @returns {lunr.TokenSet} + * @throws Will throw an error if the input array is not sorted. + */ +lunr.TokenSet.fromArray = function (arr) { + var builder = new lunr.TokenSet.Builder + + for (var i = 0, len = arr.length; i < len; i++) { + builder.insert(arr[i]) + } + + builder.finish() + return builder.root +} + +/** + * Creates a token set from a query clause. + * + * @private + * @param {Object} clause - A single clause from lunr.Query. + * @param {string} clause.term - The query clause term. + * @param {number} [clause.editDistance] - The optional edit distance for the term. + * @returns {lunr.TokenSet} + */ +lunr.TokenSet.fromClause = function (clause) { + if ('editDistance' in clause) { + return lunr.TokenSet.fromFuzzyString(clause.term, clause.editDistance) + } else { + return lunr.TokenSet.fromString(clause.term) + } +} + +/** + * Creates a token set representing a single string with a specified + * edit distance. + * + * Insertions, deletions, substitutions and transpositions are each + * treated as an edit distance of 1. + * + * Increasing the allowed edit distance will have a dramatic impact + * on the performance of both creating and intersecting these TokenSets. + * It is advised to keep the edit distance less than 3. + * + * @param {string} str - The string to create the token set from. + * @param {number} editDistance - The allowed edit distance to match. + * @returns {lunr.Vector} + */ +lunr.TokenSet.fromFuzzyString = function (str, editDistance) { + var root = new lunr.TokenSet + + var stack = [{ + node: root, + editsRemaining: editDistance, + str: str + }] + + while (stack.length) { + var frame = stack.pop() + + // no edit + if (frame.str.length > 0) { + var char = frame.str.charAt(0), + noEditNode + + if (char in frame.node.edges) { + noEditNode = frame.node.edges[char] + } else { + noEditNode = new lunr.TokenSet + frame.node.edges[char] = noEditNode + } + + if (frame.str.length == 1) { + noEditNode.final = true + } + + stack.push({ + node: noEditNode, + editsRemaining: frame.editsRemaining, + str: frame.str.slice(1) + }) + } + + if (frame.editsRemaining == 0) { + continue + } + + // insertion + if ("*" in frame.node.edges) { + var insertionNode = frame.node.edges["*"] + } else { + var insertionNode = new lunr.TokenSet + frame.node.edges["*"] = insertionNode + } + + if (frame.str.length == 0) { + insertionNode.final = true + } + + stack.push({ + node: insertionNode, + editsRemaining: frame.editsRemaining - 1, + str: frame.str + }) + + // deletion + // can only do a deletion if we have enough edits remaining + // and if there are characters left to delete in the string + if (frame.str.length > 1) { + stack.push({ + node: frame.node, + editsRemaining: frame.editsRemaining - 1, + str: frame.str.slice(1) + }) + } + + // deletion + // just removing the last character from the str + if (frame.str.length == 1) { + frame.node.final = true + } + + // substitution + // can only do a substitution if we have enough edits remaining + // and if there are characters left to substitute + if (frame.str.length >= 1) { + if ("*" in frame.node.edges) { + var substitutionNode = frame.node.edges["*"] + } else { + var substitutionNode = new lunr.TokenSet + frame.node.edges["*"] = substitutionNode + } + + if (frame.str.length == 1) { + substitutionNode.final = true + } + + stack.push({ + node: substitutionNode, + editsRemaining: frame.editsRemaining - 1, + str: frame.str.slice(1) + }) + } + + // transposition + // can only do a transposition if there are edits remaining + // and there are enough characters to transpose + if (frame.str.length > 1) { + var charA = frame.str.charAt(0), + charB = frame.str.charAt(1), + transposeNode + + if (charB in frame.node.edges) { + transposeNode = frame.node.edges[charB] + } else { + transposeNode = new lunr.TokenSet + frame.node.edges[charB] = transposeNode + } + + if (frame.str.length == 1) { + transposeNode.final = true + } + + stack.push({ + node: transposeNode, + editsRemaining: frame.editsRemaining - 1, + str: charA + frame.str.slice(2) + }) + } + } + + return root +} + +/** + * Creates a TokenSet from a string. + * + * The string may contain one or more wildcard characters (*) + * that will allow wildcard matching when intersecting with + * another TokenSet. + * + * @param {string} str - The string to create a TokenSet from. + * @returns {lunr.TokenSet} + */ +lunr.TokenSet.fromString = function (str) { + var node = new lunr.TokenSet, + root = node + + /* + * Iterates through all characters within the passed string + * appending a node for each character. + * + * When a wildcard character is found then a self + * referencing edge is introduced to continually match + * any number of any characters. + */ + for (var i = 0, len = str.length; i < len; i++) { + var char = str[i], + final = (i == len - 1) + + if (char == "*") { + node.edges[char] = node + node.final = final + + } else { + var next = new lunr.TokenSet + next.final = final + + node.edges[char] = next + node = next + } + } + + return root +} + +/** + * Converts this TokenSet into an array of strings + * contained within the TokenSet. + * + * This is not intended to be used on a TokenSet that + * contains wildcards, in these cases the results are + * undefined and are likely to cause an infinite loop. + * + * @returns {string[]} + */ +lunr.TokenSet.prototype.toArray = function () { + var words = [] + + var stack = [{ + prefix: "", + node: this + }] + + while (stack.length) { + var frame = stack.pop(), + edges = Object.keys(frame.node.edges), + len = edges.length + + if (frame.node.final) { + /* In Safari, at this point the prefix is sometimes corrupted, see: + * https://github.com/olivernn/lunr.js/issues/279 Calling any + * String.prototype method forces Safari to "cast" this string to what + * it's supposed to be, fixing the bug. */ + frame.prefix.charAt(0) + words.push(frame.prefix) + } + + for (var i = 0; i < len; i++) { + var edge = edges[i] + + stack.push({ + prefix: frame.prefix.concat(edge), + node: frame.node.edges[edge] + }) + } + } + + return words +} + +/** + * Generates a string representation of a TokenSet. + * + * This is intended to allow TokenSets to be used as keys + * in objects, largely to aid the construction and minimisation + * of a TokenSet. As such it is not designed to be a human + * friendly representation of the TokenSet. + * + * @returns {string} + */ +lunr.TokenSet.prototype.toString = function () { + // NOTE: Using Object.keys here as this.edges is very likely + // to enter 'hash-mode' with many keys being added + // + // avoiding a for-in loop here as it leads to the function + // being de-optimised (at least in V8). From some simple + // benchmarks the performance is comparable, but allowing + // V8 to optimize may mean easy performance wins in the future. + + if (this._str) { + return this._str + } + + var str = this.final ? '1' : '0', + labels = Object.keys(this.edges).sort(), + len = labels.length + + for (var i = 0; i < len; i++) { + var label = labels[i], + node = this.edges[label] + + str = str + label + node.id + } + + return str +} + +/** + * Returns a new TokenSet that is the intersection of + * this TokenSet and the passed TokenSet. + * + * This intersection will take into account any wildcards + * contained within the TokenSet. + * + * @param {lunr.TokenSet} b - An other TokenSet to intersect with. + * @returns {lunr.TokenSet} + */ +lunr.TokenSet.prototype.intersect = function (b) { + var output = new lunr.TokenSet, + frame = undefined + + var stack = [{ + qNode: b, + output: output, + node: this + }] + + while (stack.length) { + frame = stack.pop() + + // NOTE: As with the #toString method, we are using + // Object.keys and a for loop instead of a for-in loop + // as both of these objects enter 'hash' mode, causing + // the function to be de-optimised in V8 + var qEdges = Object.keys(frame.qNode.edges), + qLen = qEdges.length, + nEdges = Object.keys(frame.node.edges), + nLen = nEdges.length + + for (var q = 0; q < qLen; q++) { + var qEdge = qEdges[q] + + for (var n = 0; n < nLen; n++) { + var nEdge = nEdges[n] + + if (nEdge == qEdge || qEdge == '*') { + var node = frame.node.edges[nEdge], + qNode = frame.qNode.edges[qEdge], + final = node.final && qNode.final, + next = undefined + + if (nEdge in frame.output.edges) { + // an edge already exists for this character + // no need to create a new node, just set the finality + // bit unless this node is already final + next = frame.output.edges[nEdge] + next.final = next.final || final + + } else { + // no edge exists yet, must create one + // set the finality bit and insert it + // into the output + next = new lunr.TokenSet + next.final = final + frame.output.edges[nEdge] = next + } + + stack.push({ + qNode: qNode, + output: next, + node: node + }) + } + } + } + } + + return output +} +lunr.TokenSet.Builder = function () { + this.previousWord = "" + this.root = new lunr.TokenSet + this.uncheckedNodes = [] + this.minimizedNodes = {} +} + +lunr.TokenSet.Builder.prototype.insert = function (word) { + var node, + commonPrefix = 0 + + if (word < this.previousWord) { + throw new Error ("Out of order word insertion") + } + + for (var i = 0; i < word.length && i < this.previousWord.length; i++) { + if (word[i] != this.previousWord[i]) break + commonPrefix++ + } + + this.minimize(commonPrefix) + + if (this.uncheckedNodes.length == 0) { + node = this.root + } else { + node = this.uncheckedNodes[this.uncheckedNodes.length - 1].child + } + + for (var i = commonPrefix; i < word.length; i++) { + var nextNode = new lunr.TokenSet, + char = word[i] + + node.edges[char] = nextNode + + this.uncheckedNodes.push({ + parent: node, + char: char, + child: nextNode + }) + + node = nextNode + } + + node.final = true + this.previousWord = word +} + +lunr.TokenSet.Builder.prototype.finish = function () { + this.minimize(0) +} + +lunr.TokenSet.Builder.prototype.minimize = function (downTo) { + for (var i = this.uncheckedNodes.length - 1; i >= downTo; i--) { + var node = this.uncheckedNodes[i], + childKey = node.child.toString() + + if (childKey in this.minimizedNodes) { + node.parent.edges[node.char] = this.minimizedNodes[childKey] + } else { + // Cache the key for this node since + // we know it can't change anymore + node.child._str = childKey + + this.minimizedNodes[childKey] = node.child + } + + this.uncheckedNodes.pop() + } +} +/*! + * lunr.Index + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * An index contains the built index of all documents and provides a query interface + * to the index. + * + * Usually instances of lunr.Index will not be created using this constructor, instead + * lunr.Builder should be used to construct new indexes, or lunr.Index.load should be + * used to load previously built and serialized indexes. + * + * @constructor + * @param {Object} attrs - The attributes of the built search index. + * @param {Object} attrs.invertedIndex - An index of term/field to document reference. + * @param {Object} attrs.fieldVectors - Field vectors + * @param {lunr.TokenSet} attrs.tokenSet - An set of all corpus tokens. + * @param {string[]} attrs.fields - The names of indexed document fields. + * @param {lunr.Pipeline} attrs.pipeline - The pipeline to use for search terms. + */ +lunr.Index = function (attrs) { + this.invertedIndex = attrs.invertedIndex + this.fieldVectors = attrs.fieldVectors + this.tokenSet = attrs.tokenSet + this.fields = attrs.fields + this.pipeline = attrs.pipeline +} + +/** + * A result contains details of a document matching a search query. + * @typedef {Object} lunr.Index~Result + * @property {string} ref - The reference of the document this result represents. + * @property {number} score - A number between 0 and 1 representing how similar this document is to the query. + * @property {lunr.MatchData} matchData - Contains metadata about this match including which term(s) caused the match. + */ + +/** + * Although lunr provides the ability to create queries using lunr.Query, it also provides a simple + * query language which itself is parsed into an instance of lunr.Query. + * + * For programmatically building queries it is advised to directly use lunr.Query, the query language + * is best used for human entered text rather than program generated text. + * + * At its simplest queries can just be a single term, e.g. `hello`, multiple terms are also supported + * and will be combined with OR, e.g `hello world` will match documents that contain either 'hello' + * or 'world', though those that contain both will rank higher in the results. + * + * Wildcards can be included in terms to match one or more unspecified characters, these wildcards can + * be inserted anywhere within the term, and more than one wildcard can exist in a single term. Adding + * wildcards will increase the number of documents that will be found but can also have a negative + * impact on query performance, especially with wildcards at the beginning of a term. + * + * Terms can be restricted to specific fields, e.g. `title:hello`, only documents with the term + * hello in the title field will match this query. Using a field not present in the index will lead + * to an error being thrown. + * + * Modifiers can also be added to terms, lunr supports edit distance and boost modifiers on terms. A term + * boost will make documents matching that term score higher, e.g. `foo^5`. Edit distance is also supported + * to provide fuzzy matching, e.g. 'hello~2' will match documents with hello with an edit distance of 2. + * Avoid large values for edit distance to improve query performance. + * + * Each term also supports a presence modifier. By default a term's presence in document is optional, however + * this can be changed to either required or prohibited. For a term's presence to be required in a document the + * term should be prefixed with a '+', e.g. `+foo bar` is a search for documents that must contain 'foo' and + * optionally contain 'bar'. Conversely a leading '-' sets the terms presence to prohibited, i.e. it must not + * appear in a document, e.g. `-foo bar` is a search for documents that do not contain 'foo' but may contain 'bar'. + * + * To escape special characters the backslash character '\' can be used, this allows searches to include + * characters that would normally be considered modifiers, e.g. `foo\~2` will search for a term "foo~2" instead + * of attempting to apply a boost of 2 to the search term "foo". + * + * @typedef {string} lunr.Index~QueryString + * @example Simple single term query + * hello + * @example Multiple term query + * hello world + * @example term scoped to a field + * title:hello + * @example term with a boost of 10 + * hello^10 + * @example term with an edit distance of 2 + * hello~2 + * @example terms with presence modifiers + * -foo +bar baz + */ + +/** + * Performs a search against the index using lunr query syntax. + * + * Results will be returned sorted by their score, the most relevant results + * will be returned first. For details on how the score is calculated, please see + * the {@link https://lunrjs.com/guides/searching.html#scoring|guide}. + * + * For more programmatic querying use lunr.Index#query. + * + * @param {lunr.Index~QueryString} queryString - A string containing a lunr query. + * @throws {lunr.QueryParseError} If the passed query string cannot be parsed. + * @returns {lunr.Index~Result[]} + */ +lunr.Index.prototype.search = function (queryString) { + return this.query(function (query) { + var parser = new lunr.QueryParser(queryString, query) + parser.parse() + }) +} + +/** + * A query builder callback provides a query object to be used to express + * the query to perform on the index. + * + * @callback lunr.Index~queryBuilder + * @param {lunr.Query} query - The query object to build up. + * @this lunr.Query + */ + +/** + * Performs a query against the index using the yielded lunr.Query object. + * + * If performing programmatic queries against the index, this method is preferred + * over lunr.Index#search so as to avoid the additional query parsing overhead. + * + * A query object is yielded to the supplied function which should be used to + * express the query to be run against the index. + * + * Note that although this function takes a callback parameter it is _not_ an + * asynchronous operation, the callback is just yielded a query object to be + * customized. + * + * @param {lunr.Index~queryBuilder} fn - A function that is used to build the query. + * @returns {lunr.Index~Result[]} + */ +lunr.Index.prototype.query = function (fn) { + // for each query clause + // * process terms + // * expand terms from token set + // * find matching documents and metadata + // * get document vectors + // * score documents + + var query = new lunr.Query(this.fields), + matchingFields = Object.create(null), + queryVectors = Object.create(null), + termFieldCache = Object.create(null), + requiredMatches = Object.create(null), + prohibitedMatches = Object.create(null) + + /* + * To support field level boosts a query vector is created per + * field. An empty vector is eagerly created to support negated + * queries. + */ + for (var i = 0; i < this.fields.length; i++) { + queryVectors[this.fields[i]] = new lunr.Vector + } + + fn.call(query, query) + + for (var i = 0; i < query.clauses.length; i++) { + /* + * Unless the pipeline has been disabled for this term, which is + * the case for terms with wildcards, we need to pass the clause + * term through the search pipeline. A pipeline returns an array + * of processed terms. Pipeline functions may expand the passed + * term, which means we may end up performing multiple index lookups + * for a single query term. + */ + var clause = query.clauses[i], + terms = null, + clauseMatches = lunr.Set.empty + + if (clause.usePipeline) { + terms = this.pipeline.runString(clause.term, { + fields: clause.fields + }) + } else { + terms = [clause.term] + } + + for (var m = 0; m < terms.length; m++) { + var term = terms[m] + + /* + * Each term returned from the pipeline needs to use the same query + * clause object, e.g. the same boost and or edit distance. The + * simplest way to do this is to re-use the clause object but mutate + * its term property. + */ + clause.term = term + + /* + * From the term in the clause we create a token set which will then + * be used to intersect the indexes token set to get a list of terms + * to lookup in the inverted index + */ + var termTokenSet = lunr.TokenSet.fromClause(clause), + expandedTerms = this.tokenSet.intersect(termTokenSet).toArray() + + /* + * If a term marked as required does not exist in the tokenSet it is + * impossible for the search to return any matches. We set all the field + * scoped required matches set to empty and stop examining any further + * clauses. + */ + if (expandedTerms.length === 0 && clause.presence === lunr.Query.presence.REQUIRED) { + for (var k = 0; k < clause.fields.length; k++) { + var field = clause.fields[k] + requiredMatches[field] = lunr.Set.empty + } + + break + } + + for (var j = 0; j < expandedTerms.length; j++) { + /* + * For each term get the posting and termIndex, this is required for + * building the query vector. + */ + var expandedTerm = expandedTerms[j], + posting = this.invertedIndex[expandedTerm], + termIndex = posting._index + + for (var k = 0; k < clause.fields.length; k++) { + /* + * For each field that this query term is scoped by (by default + * all fields are in scope) we need to get all the document refs + * that have this term in that field. + * + * The posting is the entry in the invertedIndex for the matching + * term from above. + */ + var field = clause.fields[k], + fieldPosting = posting[field], + matchingDocumentRefs = Object.keys(fieldPosting), + termField = expandedTerm + "/" + field, + matchingDocumentsSet = new lunr.Set(matchingDocumentRefs) + + /* + * if the presence of this term is required ensure that the matching + * documents are added to the set of required matches for this clause. + * + */ + if (clause.presence == lunr.Query.presence.REQUIRED) { + clauseMatches = clauseMatches.union(matchingDocumentsSet) + + if (requiredMatches[field] === undefined) { + requiredMatches[field] = lunr.Set.complete + } + } + + /* + * if the presence of this term is prohibited ensure that the matching + * documents are added to the set of prohibited matches for this field, + * creating that set if it does not yet exist. + */ + if (clause.presence == lunr.Query.presence.PROHIBITED) { + if (prohibitedMatches[field] === undefined) { + prohibitedMatches[field] = lunr.Set.empty + } + + prohibitedMatches[field] = prohibitedMatches[field].union(matchingDocumentsSet) + + /* + * Prohibited matches should not be part of the query vector used for + * similarity scoring and no metadata should be extracted so we continue + * to the next field + */ + continue + } + + /* + * The query field vector is populated using the termIndex found for + * the term and a unit value with the appropriate boost applied. + * Using upsert because there could already be an entry in the vector + * for the term we are working with. In that case we just add the scores + * together. + */ + queryVectors[field].upsert(termIndex, clause.boost, function (a, b) { return a + b }) + + /** + * If we've already seen this term, field combo then we've already collected + * the matching documents and metadata, no need to go through all that again + */ + if (termFieldCache[termField]) { + continue + } + + for (var l = 0; l < matchingDocumentRefs.length; l++) { + /* + * All metadata for this term/field/document triple + * are then extracted and collected into an instance + * of lunr.MatchData ready to be returned in the query + * results + */ + var matchingDocumentRef = matchingDocumentRefs[l], + matchingFieldRef = new lunr.FieldRef (matchingDocumentRef, field), + metadata = fieldPosting[matchingDocumentRef], + fieldMatch + + if ((fieldMatch = matchingFields[matchingFieldRef]) === undefined) { + matchingFields[matchingFieldRef] = new lunr.MatchData (expandedTerm, field, metadata) + } else { + fieldMatch.add(expandedTerm, field, metadata) + } + + } + + termFieldCache[termField] = true + } + } + } + + /** + * If the presence was required we need to update the requiredMatches field sets. + * We do this after all fields for the term have collected their matches because + * the clause terms presence is required in _any_ of the fields not _all_ of the + * fields. + */ + if (clause.presence === lunr.Query.presence.REQUIRED) { + for (var k = 0; k < clause.fields.length; k++) { + var field = clause.fields[k] + requiredMatches[field] = requiredMatches[field].intersect(clauseMatches) + } + } + } + + /** + * Need to combine the field scoped required and prohibited + * matching documents into a global set of required and prohibited + * matches + */ + var allRequiredMatches = lunr.Set.complete, + allProhibitedMatches = lunr.Set.empty + + for (var i = 0; i < this.fields.length; i++) { + var field = this.fields[i] + + if (requiredMatches[field]) { + allRequiredMatches = allRequiredMatches.intersect(requiredMatches[field]) + } + + if (prohibitedMatches[field]) { + allProhibitedMatches = allProhibitedMatches.union(prohibitedMatches[field]) + } + } + + var matchingFieldRefs = Object.keys(matchingFields), + results = [], + matches = Object.create(null) + + /* + * If the query is negated (contains only prohibited terms) + * we need to get _all_ fieldRefs currently existing in the + * index. This is only done when we know that the query is + * entirely prohibited terms to avoid any cost of getting all + * fieldRefs unnecessarily. + * + * Additionally, blank MatchData must be created to correctly + * populate the results. + */ + if (query.isNegated()) { + matchingFieldRefs = Object.keys(this.fieldVectors) + + for (var i = 0; i < matchingFieldRefs.length; i++) { + var matchingFieldRef = matchingFieldRefs[i] + var fieldRef = lunr.FieldRef.fromString(matchingFieldRef) + matchingFields[matchingFieldRef] = new lunr.MatchData + } + } + + for (var i = 0; i < matchingFieldRefs.length; i++) { + /* + * Currently we have document fields that match the query, but we + * need to return documents. The matchData and scores are combined + * from multiple fields belonging to the same document. + * + * Scores are calculated by field, using the query vectors created + * above, and combined into a final document score using addition. + */ + var fieldRef = lunr.FieldRef.fromString(matchingFieldRefs[i]), + docRef = fieldRef.docRef + + if (!allRequiredMatches.contains(docRef)) { + continue + } + + if (allProhibitedMatches.contains(docRef)) { + continue + } + + var fieldVector = this.fieldVectors[fieldRef], + score = queryVectors[fieldRef.fieldName].similarity(fieldVector), + docMatch + + if ((docMatch = matches[docRef]) !== undefined) { + docMatch.score += score + docMatch.matchData.combine(matchingFields[fieldRef]) + } else { + var match = { + ref: docRef, + score: score, + matchData: matchingFields[fieldRef] + } + matches[docRef] = match + results.push(match) + } + } + + /* + * Sort the results objects by score, highest first. + */ + return results.sort(function (a, b) { + return b.score - a.score + }) +} + +/** + * Prepares the index for JSON serialization. + * + * The schema for this JSON blob will be described in a + * separate JSON schema file. + * + * @returns {Object} + */ +lunr.Index.prototype.toJSON = function () { + var invertedIndex = Object.keys(this.invertedIndex) + .sort() + .map(function (term) { + return [term, this.invertedIndex[term]] + }, this) + + var fieldVectors = Object.keys(this.fieldVectors) + .map(function (ref) { + return [ref, this.fieldVectors[ref].toJSON()] + }, this) + + return { + version: lunr.version, + fields: this.fields, + fieldVectors: fieldVectors, + invertedIndex: invertedIndex, + pipeline: this.pipeline.toJSON() + } +} + +/** + * Loads a previously serialized lunr.Index + * + * @param {Object} serializedIndex - A previously serialized lunr.Index + * @returns {lunr.Index} + */ +lunr.Index.load = function (serializedIndex) { + var attrs = {}, + fieldVectors = {}, + serializedVectors = serializedIndex.fieldVectors, + invertedIndex = Object.create(null), + serializedInvertedIndex = serializedIndex.invertedIndex, + tokenSetBuilder = new lunr.TokenSet.Builder, + pipeline = lunr.Pipeline.load(serializedIndex.pipeline) + + if (serializedIndex.version != lunr.version) { + lunr.utils.warn("Version mismatch when loading serialised index. Current version of lunr '" + lunr.version + "' does not match serialized index '" + serializedIndex.version + "'") + } + + for (var i = 0; i < serializedVectors.length; i++) { + var tuple = serializedVectors[i], + ref = tuple[0], + elements = tuple[1] + + fieldVectors[ref] = new lunr.Vector(elements) + } + + for (var i = 0; i < serializedInvertedIndex.length; i++) { + var tuple = serializedInvertedIndex[i], + term = tuple[0], + posting = tuple[1] + + tokenSetBuilder.insert(term) + invertedIndex[term] = posting + } + + tokenSetBuilder.finish() + + attrs.fields = serializedIndex.fields + + attrs.fieldVectors = fieldVectors + attrs.invertedIndex = invertedIndex + attrs.tokenSet = tokenSetBuilder.root + attrs.pipeline = pipeline + + return new lunr.Index(attrs) +} +/*! + * lunr.Builder + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.Builder performs indexing on a set of documents and + * returns instances of lunr.Index ready for querying. + * + * All configuration of the index is done via the builder, the + * fields to index, the document reference, the text processing + * pipeline and document scoring parameters are all set on the + * builder before indexing. + * + * @constructor + * @property {string} _ref - Internal reference to the document reference field. + * @property {string[]} _fields - Internal reference to the document fields to index. + * @property {object} invertedIndex - The inverted index maps terms to document fields. + * @property {object} documentTermFrequencies - Keeps track of document term frequencies. + * @property {object} documentLengths - Keeps track of the length of documents added to the index. + * @property {lunr.tokenizer} tokenizer - Function for splitting strings into tokens for indexing. + * @property {lunr.Pipeline} pipeline - The pipeline performs text processing on tokens before indexing. + * @property {lunr.Pipeline} searchPipeline - A pipeline for processing search terms before querying the index. + * @property {number} documentCount - Keeps track of the total number of documents indexed. + * @property {number} _b - A parameter to control field length normalization, setting this to 0 disabled normalization, 1 fully normalizes field lengths, the default value is 0.75. + * @property {number} _k1 - A parameter to control how quickly an increase in term frequency results in term frequency saturation, the default value is 1.2. + * @property {number} termIndex - A counter incremented for each unique term, used to identify a terms position in the vector space. + * @property {array} metadataWhitelist - A list of metadata keys that have been whitelisted for entry in the index. + */ +lunr.Builder = function () { + this._ref = "id" + this._fields = Object.create(null) + this._documents = Object.create(null) + this.invertedIndex = Object.create(null) + this.fieldTermFrequencies = {} + this.fieldLengths = {} + this.tokenizer = lunr.tokenizer + this.pipeline = new lunr.Pipeline + this.searchPipeline = new lunr.Pipeline + this.documentCount = 0 + this._b = 0.75 + this._k1 = 1.2 + this.termIndex = 0 + this.metadataWhitelist = [] +} + +/** + * Sets the document field used as the document reference. Every document must have this field. + * The type of this field in the document should be a string, if it is not a string it will be + * coerced into a string by calling toString. + * + * The default ref is 'id'. + * + * The ref should _not_ be changed during indexing, it should be set before any documents are + * added to the index. Changing it during indexing can lead to inconsistent results. + * + * @param {string} ref - The name of the reference field in the document. + */ +lunr.Builder.prototype.ref = function (ref) { + this._ref = ref +} + +/** + * A function that is used to extract a field from a document. + * + * Lunr expects a field to be at the top level of a document, if however the field + * is deeply nested within a document an extractor function can be used to extract + * the right field for indexing. + * + * @callback fieldExtractor + * @param {object} doc - The document being added to the index. + * @returns {?(string|object|object[])} obj - The object that will be indexed for this field. + * @example Extracting a nested field + * function (doc) { return doc.nested.field } + */ + +/** + * Adds a field to the list of document fields that will be indexed. Every document being + * indexed should have this field. Null values for this field in indexed documents will + * not cause errors but will limit the chance of that document being retrieved by searches. + * + * All fields should be added before adding documents to the index. Adding fields after + * a document has been indexed will have no effect on already indexed documents. + * + * Fields can be boosted at build time. This allows terms within that field to have more + * importance when ranking search results. Use a field boost to specify that matches within + * one field are more important than other fields. + * + * @param {string} fieldName - The name of a field to index in all documents. + * @param {object} attributes - Optional attributes associated with this field. + * @param {number} [attributes.boost=1] - Boost applied to all terms within this field. + * @param {fieldExtractor} [attributes.extractor] - Function to extract a field from a document. + * @throws {RangeError} fieldName cannot contain unsupported characters '/' + */ +lunr.Builder.prototype.field = function (fieldName, attributes) { + if (/\//.test(fieldName)) { + throw new RangeError ("Field '" + fieldName + "' contains illegal character '/'") + } + + this._fields[fieldName] = attributes || {} +} + +/** + * A parameter to tune the amount of field length normalisation that is applied when + * calculating relevance scores. A value of 0 will completely disable any normalisation + * and a value of 1 will fully normalise field lengths. The default is 0.75. Values of b + * will be clamped to the range 0 - 1. + * + * @param {number} number - The value to set for this tuning parameter. + */ +lunr.Builder.prototype.b = function (number) { + if (number < 0) { + this._b = 0 + } else if (number > 1) { + this._b = 1 + } else { + this._b = number + } +} + +/** + * A parameter that controls the speed at which a rise in term frequency results in term + * frequency saturation. The default value is 1.2. Setting this to a higher value will give + * slower saturation levels, a lower value will result in quicker saturation. + * + * @param {number} number - The value to set for this tuning parameter. + */ +lunr.Builder.prototype.k1 = function (number) { + this._k1 = number +} + +/** + * Adds a document to the index. + * + * Before adding fields to the index the index should have been fully setup, with the document + * ref and all fields to index already having been specified. + * + * The document must have a field name as specified by the ref (by default this is 'id') and + * it should have all fields defined for indexing, though null or undefined values will not + * cause errors. + * + * Entire documents can be boosted at build time. Applying a boost to a document indicates that + * this document should rank higher in search results than other documents. + * + * @param {object} doc - The document to add to the index. + * @param {object} attributes - Optional attributes associated with this document. + * @param {number} [attributes.boost=1] - Boost applied to all terms within this document. + */ +lunr.Builder.prototype.add = function (doc, attributes) { + var docRef = doc[this._ref], + fields = Object.keys(this._fields) + + this._documents[docRef] = attributes || {} + this.documentCount += 1 + + for (var i = 0; i < fields.length; i++) { + var fieldName = fields[i], + extractor = this._fields[fieldName].extractor, + field = extractor ? extractor(doc) : doc[fieldName], + tokens = this.tokenizer(field, { + fields: [fieldName] + }), + terms = this.pipeline.run(tokens), + fieldRef = new lunr.FieldRef (docRef, fieldName), + fieldTerms = Object.create(null) + + this.fieldTermFrequencies[fieldRef] = fieldTerms + this.fieldLengths[fieldRef] = 0 + + // store the length of this field for this document + this.fieldLengths[fieldRef] += terms.length + + // calculate term frequencies for this field + for (var j = 0; j < terms.length; j++) { + var term = terms[j] + + if (fieldTerms[term] == undefined) { + fieldTerms[term] = 0 + } + + fieldTerms[term] += 1 + + // add to inverted index + // create an initial posting if one doesn't exist + if (this.invertedIndex[term] == undefined) { + var posting = Object.create(null) + posting["_index"] = this.termIndex + this.termIndex += 1 + + for (var k = 0; k < fields.length; k++) { + posting[fields[k]] = Object.create(null) + } + + this.invertedIndex[term] = posting + } + + // add an entry for this term/fieldName/docRef to the invertedIndex + if (this.invertedIndex[term][fieldName][docRef] == undefined) { + this.invertedIndex[term][fieldName][docRef] = Object.create(null) + } + + // store all whitelisted metadata about this token in the + // inverted index + for (var l = 0; l < this.metadataWhitelist.length; l++) { + var metadataKey = this.metadataWhitelist[l], + metadata = term.metadata[metadataKey] + + if (this.invertedIndex[term][fieldName][docRef][metadataKey] == undefined) { + this.invertedIndex[term][fieldName][docRef][metadataKey] = [] + } + + this.invertedIndex[term][fieldName][docRef][metadataKey].push(metadata) + } + } + + } +} + +/** + * Calculates the average document length for this index + * + * @private + */ +lunr.Builder.prototype.calculateAverageFieldLengths = function () { + + var fieldRefs = Object.keys(this.fieldLengths), + numberOfFields = fieldRefs.length, + accumulator = {}, + documentsWithField = {} + + for (var i = 0; i < numberOfFields; i++) { + var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]), + field = fieldRef.fieldName + + documentsWithField[field] || (documentsWithField[field] = 0) + documentsWithField[field] += 1 + + accumulator[field] || (accumulator[field] = 0) + accumulator[field] += this.fieldLengths[fieldRef] + } + + var fields = Object.keys(this._fields) + + for (var i = 0; i < fields.length; i++) { + var fieldName = fields[i] + accumulator[fieldName] = accumulator[fieldName] / documentsWithField[fieldName] + } + + this.averageFieldLength = accumulator +} + +/** + * Builds a vector space model of every document using lunr.Vector + * + * @private + */ +lunr.Builder.prototype.createFieldVectors = function () { + var fieldVectors = {}, + fieldRefs = Object.keys(this.fieldTermFrequencies), + fieldRefsLength = fieldRefs.length, + termIdfCache = Object.create(null) + + for (var i = 0; i < fieldRefsLength; i++) { + var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]), + fieldName = fieldRef.fieldName, + fieldLength = this.fieldLengths[fieldRef], + fieldVector = new lunr.Vector, + termFrequencies = this.fieldTermFrequencies[fieldRef], + terms = Object.keys(termFrequencies), + termsLength = terms.length + + + var fieldBoost = this._fields[fieldName].boost || 1, + docBoost = this._documents[fieldRef.docRef].boost || 1 + + for (var j = 0; j < termsLength; j++) { + var term = terms[j], + tf = termFrequencies[term], + termIndex = this.invertedIndex[term]._index, + idf, score, scoreWithPrecision + + if (termIdfCache[term] === undefined) { + idf = lunr.idf(this.invertedIndex[term], this.documentCount) + termIdfCache[term] = idf + } else { + idf = termIdfCache[term] + } + + score = idf * ((this._k1 + 1) * tf) / (this._k1 * (1 - this._b + this._b * (fieldLength / this.averageFieldLength[fieldName])) + tf) + score *= fieldBoost + score *= docBoost + scoreWithPrecision = Math.round(score * 1000) / 1000 + // Converts 1.23456789 to 1.234. + // Reducing the precision so that the vectors take up less + // space when serialised. Doing it now so that they behave + // the same before and after serialisation. Also, this is + // the fastest approach to reducing a number's precision in + // JavaScript. + + fieldVector.insert(termIndex, scoreWithPrecision) + } + + fieldVectors[fieldRef] = fieldVector + } + + this.fieldVectors = fieldVectors +} + +/** + * Creates a token set of all tokens in the index using lunr.TokenSet + * + * @private + */ +lunr.Builder.prototype.createTokenSet = function () { + this.tokenSet = lunr.TokenSet.fromArray( + Object.keys(this.invertedIndex).sort() + ) +} + +/** + * Builds the index, creating an instance of lunr.Index. + * + * This completes the indexing process and should only be called + * once all documents have been added to the index. + * + * @returns {lunr.Index} + */ +lunr.Builder.prototype.build = function () { + this.calculateAverageFieldLengths() + this.createFieldVectors() + this.createTokenSet() + + return new lunr.Index({ + invertedIndex: this.invertedIndex, + fieldVectors: this.fieldVectors, + tokenSet: this.tokenSet, + fields: Object.keys(this._fields), + pipeline: this.searchPipeline + }) +} + +/** + * Applies a plugin to the index builder. + * + * A plugin is a function that is called with the index builder as its context. + * Plugins can be used to customise or extend the behaviour of the index + * in some way. A plugin is just a function, that encapsulated the custom + * behaviour that should be applied when building the index. + * + * The plugin function will be called with the index builder as its argument, additional + * arguments can also be passed when calling use. The function will be called + * with the index builder as its context. + * + * @param {Function} plugin The plugin to apply. + */ +lunr.Builder.prototype.use = function (fn) { + var args = Array.prototype.slice.call(arguments, 1) + args.unshift(this) + fn.apply(this, args) +} +/** + * Contains and collects metadata about a matching document. + * A single instance of lunr.MatchData is returned as part of every + * lunr.Index~Result. + * + * @constructor + * @param {string} term - The term this match data is associated with + * @param {string} field - The field in which the term was found + * @param {object} metadata - The metadata recorded about this term in this field + * @property {object} metadata - A cloned collection of metadata associated with this document. + * @see {@link lunr.Index~Result} + */ +lunr.MatchData = function (term, field, metadata) { + var clonedMetadata = Object.create(null), + metadataKeys = Object.keys(metadata || {}) + + // Cloning the metadata to prevent the original + // being mutated during match data combination. + // Metadata is kept in an array within the inverted + // index so cloning the data can be done with + // Array#slice + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i] + clonedMetadata[key] = metadata[key].slice() + } + + this.metadata = Object.create(null) + + if (term !== undefined) { + this.metadata[term] = Object.create(null) + this.metadata[term][field] = clonedMetadata + } +} + +/** + * An instance of lunr.MatchData will be created for every term that matches a + * document. However only one instance is required in a lunr.Index~Result. This + * method combines metadata from another instance of lunr.MatchData with this + * objects metadata. + * + * @param {lunr.MatchData} otherMatchData - Another instance of match data to merge with this one. + * @see {@link lunr.Index~Result} + */ +lunr.MatchData.prototype.combine = function (otherMatchData) { + var terms = Object.keys(otherMatchData.metadata) + + for (var i = 0; i < terms.length; i++) { + var term = terms[i], + fields = Object.keys(otherMatchData.metadata[term]) + + if (this.metadata[term] == undefined) { + this.metadata[term] = Object.create(null) + } + + for (var j = 0; j < fields.length; j++) { + var field = fields[j], + keys = Object.keys(otherMatchData.metadata[term][field]) + + if (this.metadata[term][field] == undefined) { + this.metadata[term][field] = Object.create(null) + } + + for (var k = 0; k < keys.length; k++) { + var key = keys[k] + + if (this.metadata[term][field][key] == undefined) { + this.metadata[term][field][key] = otherMatchData.metadata[term][field][key] + } else { + this.metadata[term][field][key] = this.metadata[term][field][key].concat(otherMatchData.metadata[term][field][key]) + } + + } + } + } +} + +/** + * Add metadata for a term/field pair to this instance of match data. + * + * @param {string} term - The term this match data is associated with + * @param {string} field - The field in which the term was found + * @param {object} metadata - The metadata recorded about this term in this field + */ +lunr.MatchData.prototype.add = function (term, field, metadata) { + if (!(term in this.metadata)) { + this.metadata[term] = Object.create(null) + this.metadata[term][field] = metadata + return + } + + if (!(field in this.metadata[term])) { + this.metadata[term][field] = metadata + return + } + + var metadataKeys = Object.keys(metadata) + + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i] + + if (key in this.metadata[term][field]) { + this.metadata[term][field][key] = this.metadata[term][field][key].concat(metadata[key]) + } else { + this.metadata[term][field][key] = metadata[key] + } + } +} +/** + * A lunr.Query provides a programmatic way of defining queries to be performed + * against a {@link lunr.Index}. + * + * Prefer constructing a lunr.Query using the {@link lunr.Index#query} method + * so the query object is pre-initialized with the right index fields. + * + * @constructor + * @property {lunr.Query~Clause[]} clauses - An array of query clauses. + * @property {string[]} allFields - An array of all available fields in a lunr.Index. + */ +lunr.Query = function (allFields) { + this.clauses = [] + this.allFields = allFields +} + +/** + * Constants for indicating what kind of automatic wildcard insertion will be used when constructing a query clause. + * + * This allows wildcards to be added to the beginning and end of a term without having to manually do any string + * concatenation. + * + * The wildcard constants can be bitwise combined to select both leading and trailing wildcards. + * + * @constant + * @default + * @property {number} wildcard.NONE - The term will have no wildcards inserted, this is the default behaviour + * @property {number} wildcard.LEADING - Prepend the term with a wildcard, unless a leading wildcard already exists + * @property {number} wildcard.TRAILING - Append a wildcard to the term, unless a trailing wildcard already exists + * @see lunr.Query~Clause + * @see lunr.Query#clause + * @see lunr.Query#term + * @example query term with trailing wildcard + * query.term('foo', { wildcard: lunr.Query.wildcard.TRAILING }) + * @example query term with leading and trailing wildcard + * query.term('foo', { + * wildcard: lunr.Query.wildcard.LEADING | lunr.Query.wildcard.TRAILING + * }) + */ + +lunr.Query.wildcard = new String ("*") +lunr.Query.wildcard.NONE = 0 +lunr.Query.wildcard.LEADING = 1 +lunr.Query.wildcard.TRAILING = 2 + +/** + * Constants for indicating what kind of presence a term must have in matching documents. + * + * @constant + * @enum {number} + * @see lunr.Query~Clause + * @see lunr.Query#clause + * @see lunr.Query#term + * @example query term with required presence + * query.term('foo', { presence: lunr.Query.presence.REQUIRED }) + */ +lunr.Query.presence = { + /** + * Term's presence in a document is optional, this is the default value. + */ + OPTIONAL: 1, + + /** + * Term's presence in a document is required, documents that do not contain + * this term will not be returned. + */ + REQUIRED: 2, + + /** + * Term's presence in a document is prohibited, documents that do contain + * this term will not be returned. + */ + PROHIBITED: 3 +} + +/** + * A single clause in a {@link lunr.Query} contains a term and details on how to + * match that term against a {@link lunr.Index}. + * + * @typedef {Object} lunr.Query~Clause + * @property {string[]} fields - The fields in an index this clause should be matched against. + * @property {number} [boost=1] - Any boost that should be applied when matching this clause. + * @property {number} [editDistance] - Whether the term should have fuzzy matching applied, and how fuzzy the match should be. + * @property {boolean} [usePipeline] - Whether the term should be passed through the search pipeline. + * @property {number} [wildcard=lunr.Query.wildcard.NONE] - Whether the term should have wildcards appended or prepended. + * @property {number} [presence=lunr.Query.presence.OPTIONAL] - The terms presence in any matching documents. + */ + +/** + * Adds a {@link lunr.Query~Clause} to this query. + * + * Unless the clause contains the fields to be matched all fields will be matched. In addition + * a default boost of 1 is applied to the clause. + * + * @param {lunr.Query~Clause} clause - The clause to add to this query. + * @see lunr.Query~Clause + * @returns {lunr.Query} + */ +lunr.Query.prototype.clause = function (clause) { + if (!('fields' in clause)) { + clause.fields = this.allFields + } + + if (!('boost' in clause)) { + clause.boost = 1 + } + + if (!('usePipeline' in clause)) { + clause.usePipeline = true + } + + if (!('wildcard' in clause)) { + clause.wildcard = lunr.Query.wildcard.NONE + } + + if ((clause.wildcard & lunr.Query.wildcard.LEADING) && (clause.term.charAt(0) != lunr.Query.wildcard)) { + clause.term = "*" + clause.term + } + + if ((clause.wildcard & lunr.Query.wildcard.TRAILING) && (clause.term.slice(-1) != lunr.Query.wildcard)) { + clause.term = "" + clause.term + "*" + } + + if (!('presence' in clause)) { + clause.presence = lunr.Query.presence.OPTIONAL + } + + this.clauses.push(clause) + + return this +} + +/** + * A negated query is one in which every clause has a presence of + * prohibited. These queries require some special processing to return + * the expected results. + * + * @returns boolean + */ +lunr.Query.prototype.isNegated = function () { + for (var i = 0; i < this.clauses.length; i++) { + if (this.clauses[i].presence != lunr.Query.presence.PROHIBITED) { + return false + } + } + + return true +} + +/** + * Adds a term to the current query, under the covers this will create a {@link lunr.Query~Clause} + * to the list of clauses that make up this query. + * + * The term is used as is, i.e. no tokenization will be performed by this method. Instead conversion + * to a token or token-like string should be done before calling this method. + * + * The term will be converted to a string by calling `toString`. Multiple terms can be passed as an + * array, each term in the array will share the same options. + * + * @param {object|object[]} term - The term(s) to add to the query. + * @param {object} [options] - Any additional properties to add to the query clause. + * @returns {lunr.Query} + * @see lunr.Query#clause + * @see lunr.Query~Clause + * @example adding a single term to a query + * query.term("foo") + * @example adding a single term to a query and specifying search fields, term boost and automatic trailing wildcard + * query.term("foo", { + * fields: ["title"], + * boost: 10, + * wildcard: lunr.Query.wildcard.TRAILING + * }) + * @example using lunr.tokenizer to convert a string to tokens before using them as terms + * query.term(lunr.tokenizer("foo bar")) + */ +lunr.Query.prototype.term = function (term, options) { + if (Array.isArray(term)) { + term.forEach(function (t) { this.term(t, lunr.utils.clone(options)) }, this) + return this + } + + var clause = options || {} + clause.term = term.toString() + + this.clause(clause) + + return this +} +lunr.QueryParseError = function (message, start, end) { + this.name = "QueryParseError" + this.message = message + this.start = start + this.end = end +} + +lunr.QueryParseError.prototype = new Error +lunr.QueryLexer = function (str) { + this.lexemes = [] + this.str = str + this.length = str.length + this.pos = 0 + this.start = 0 + this.escapeCharPositions = [] +} + +lunr.QueryLexer.prototype.run = function () { + var state = lunr.QueryLexer.lexText + + while (state) { + state = state(this) + } +} + +lunr.QueryLexer.prototype.sliceString = function () { + var subSlices = [], + sliceStart = this.start, + sliceEnd = this.pos + + for (var i = 0; i < this.escapeCharPositions.length; i++) { + sliceEnd = this.escapeCharPositions[i] + subSlices.push(this.str.slice(sliceStart, sliceEnd)) + sliceStart = sliceEnd + 1 + } + + subSlices.push(this.str.slice(sliceStart, this.pos)) + this.escapeCharPositions.length = 0 + + return subSlices.join('') +} + +lunr.QueryLexer.prototype.emit = function (type) { + this.lexemes.push({ + type: type, + str: this.sliceString(), + start: this.start, + end: this.pos + }) + + this.start = this.pos +} + +lunr.QueryLexer.prototype.escapeCharacter = function () { + this.escapeCharPositions.push(this.pos - 1) + this.pos += 1 +} + +lunr.QueryLexer.prototype.next = function () { + if (this.pos >= this.length) { + return lunr.QueryLexer.EOS + } + + var char = this.str.charAt(this.pos) + this.pos += 1 + return char +} + +lunr.QueryLexer.prototype.width = function () { + return this.pos - this.start +} + +lunr.QueryLexer.prototype.ignore = function () { + if (this.start == this.pos) { + this.pos += 1 + } + + this.start = this.pos +} + +lunr.QueryLexer.prototype.backup = function () { + this.pos -= 1 +} + +lunr.QueryLexer.prototype.acceptDigitRun = function () { + var char, charCode + + do { + char = this.next() + charCode = char.charCodeAt(0) + } while (charCode > 47 && charCode < 58) + + if (char != lunr.QueryLexer.EOS) { + this.backup() + } +} + +lunr.QueryLexer.prototype.more = function () { + return this.pos < this.length +} + +lunr.QueryLexer.EOS = 'EOS' +lunr.QueryLexer.FIELD = 'FIELD' +lunr.QueryLexer.TERM = 'TERM' +lunr.QueryLexer.EDIT_DISTANCE = 'EDIT_DISTANCE' +lunr.QueryLexer.BOOST = 'BOOST' +lunr.QueryLexer.PRESENCE = 'PRESENCE' + +lunr.QueryLexer.lexField = function (lexer) { + lexer.backup() + lexer.emit(lunr.QueryLexer.FIELD) + lexer.ignore() + return lunr.QueryLexer.lexText +} + +lunr.QueryLexer.lexTerm = function (lexer) { + if (lexer.width() > 1) { + lexer.backup() + lexer.emit(lunr.QueryLexer.TERM) + } + + lexer.ignore() + + if (lexer.more()) { + return lunr.QueryLexer.lexText + } +} + +lunr.QueryLexer.lexEditDistance = function (lexer) { + lexer.ignore() + lexer.acceptDigitRun() + lexer.emit(lunr.QueryLexer.EDIT_DISTANCE) + return lunr.QueryLexer.lexText +} + +lunr.QueryLexer.lexBoost = function (lexer) { + lexer.ignore() + lexer.acceptDigitRun() + lexer.emit(lunr.QueryLexer.BOOST) + return lunr.QueryLexer.lexText +} + +lunr.QueryLexer.lexEOS = function (lexer) { + if (lexer.width() > 0) { + lexer.emit(lunr.QueryLexer.TERM) + } +} + +// This matches the separator used when tokenising fields +// within a document. These should match otherwise it is +// not possible to search for some tokens within a document. +// +// It is possible for the user to change the separator on the +// tokenizer so it _might_ clash with any other of the special +// characters already used within the search string, e.g. :. +// +// This means that it is possible to change the separator in +// such a way that makes some words unsearchable using a search +// string. +lunr.QueryLexer.termSeparator = lunr.tokenizer.separator + +lunr.QueryLexer.lexText = function (lexer) { + while (true) { + var char = lexer.next() + + if (char == lunr.QueryLexer.EOS) { + return lunr.QueryLexer.lexEOS + } + + // Escape character is '\' + if (char.charCodeAt(0) == 92) { + lexer.escapeCharacter() + continue + } + + if (char == ":") { + return lunr.QueryLexer.lexField + } + + if (char == "~") { + lexer.backup() + if (lexer.width() > 0) { + lexer.emit(lunr.QueryLexer.TERM) + } + return lunr.QueryLexer.lexEditDistance + } + + if (char == "^") { + lexer.backup() + if (lexer.width() > 0) { + lexer.emit(lunr.QueryLexer.TERM) + } + return lunr.QueryLexer.lexBoost + } + + // "+" indicates term presence is required + // checking for length to ensure that only + // leading "+" are considered + if (char == "+" && lexer.width() === 1) { + lexer.emit(lunr.QueryLexer.PRESENCE) + return lunr.QueryLexer.lexText + } + + // "-" indicates term presence is prohibited + // checking for length to ensure that only + // leading "-" are considered + if (char == "-" && lexer.width() === 1) { + lexer.emit(lunr.QueryLexer.PRESENCE) + return lunr.QueryLexer.lexText + } + + if (char.match(lunr.QueryLexer.termSeparator)) { + return lunr.QueryLexer.lexTerm + } + } +} + +lunr.QueryParser = function (str, query) { + this.lexer = new lunr.QueryLexer (str) + this.query = query + this.currentClause = {} + this.lexemeIdx = 0 +} + +lunr.QueryParser.prototype.parse = function () { + this.lexer.run() + this.lexemes = this.lexer.lexemes + + var state = lunr.QueryParser.parseClause + + while (state) { + state = state(this) + } + + return this.query +} + +lunr.QueryParser.prototype.peekLexeme = function () { + return this.lexemes[this.lexemeIdx] +} + +lunr.QueryParser.prototype.consumeLexeme = function () { + var lexeme = this.peekLexeme() + this.lexemeIdx += 1 + return lexeme +} + +lunr.QueryParser.prototype.nextClause = function () { + var completedClause = this.currentClause + this.query.clause(completedClause) + this.currentClause = {} +} + +lunr.QueryParser.parseClause = function (parser) { + var lexeme = parser.peekLexeme() + + if (lexeme == undefined) { + return + } + + switch (lexeme.type) { + case lunr.QueryLexer.PRESENCE: + return lunr.QueryParser.parsePresence + case lunr.QueryLexer.FIELD: + return lunr.QueryParser.parseField + case lunr.QueryLexer.TERM: + return lunr.QueryParser.parseTerm + default: + var errorMessage = "expected either a field or a term, found " + lexeme.type + + if (lexeme.str.length >= 1) { + errorMessage += " with value '" + lexeme.str + "'" + } + + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } +} + +lunr.QueryParser.parsePresence = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + switch (lexeme.str) { + case "-": + parser.currentClause.presence = lunr.Query.presence.PROHIBITED + break + case "+": + parser.currentClause.presence = lunr.Query.presence.REQUIRED + break + default: + var errorMessage = "unrecognised presence operator'" + lexeme.str + "'" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + var errorMessage = "expecting term or field, found nothing" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.FIELD: + return lunr.QueryParser.parseField + case lunr.QueryLexer.TERM: + return lunr.QueryParser.parseTerm + default: + var errorMessage = "expecting term or field, found '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseField = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + if (parser.query.allFields.indexOf(lexeme.str) == -1) { + var possibleFields = parser.query.allFields.map(function (f) { return "'" + f + "'" }).join(', '), + errorMessage = "unrecognised field '" + lexeme.str + "', possible fields: " + possibleFields + + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + parser.currentClause.fields = [lexeme.str] + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + var errorMessage = "expecting term, found nothing" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + return lunr.QueryParser.parseTerm + default: + var errorMessage = "expecting term, found '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseTerm = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + parser.currentClause.term = lexeme.str.toLowerCase() + + if (lexeme.str.indexOf("*") != -1) { + parser.currentClause.usePipeline = false + } + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + parser.nextClause() + return + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + parser.nextClause() + return lunr.QueryParser.parseTerm + case lunr.QueryLexer.FIELD: + parser.nextClause() + return lunr.QueryParser.parseField + case lunr.QueryLexer.EDIT_DISTANCE: + return lunr.QueryParser.parseEditDistance + case lunr.QueryLexer.BOOST: + return lunr.QueryParser.parseBoost + case lunr.QueryLexer.PRESENCE: + parser.nextClause() + return lunr.QueryParser.parsePresence + default: + var errorMessage = "Unexpected lexeme type '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseEditDistance = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + var editDistance = parseInt(lexeme.str, 10) + + if (isNaN(editDistance)) { + var errorMessage = "edit distance must be numeric" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + parser.currentClause.editDistance = editDistance + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + parser.nextClause() + return + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + parser.nextClause() + return lunr.QueryParser.parseTerm + case lunr.QueryLexer.FIELD: + parser.nextClause() + return lunr.QueryParser.parseField + case lunr.QueryLexer.EDIT_DISTANCE: + return lunr.QueryParser.parseEditDistance + case lunr.QueryLexer.BOOST: + return lunr.QueryParser.parseBoost + case lunr.QueryLexer.PRESENCE: + parser.nextClause() + return lunr.QueryParser.parsePresence + default: + var errorMessage = "Unexpected lexeme type '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseBoost = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + var boost = parseInt(lexeme.str, 10) + + if (isNaN(boost)) { + var errorMessage = "boost must be numeric" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + parser.currentClause.boost = boost + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + parser.nextClause() + return + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + parser.nextClause() + return lunr.QueryParser.parseTerm + case lunr.QueryLexer.FIELD: + parser.nextClause() + return lunr.QueryParser.parseField + case lunr.QueryLexer.EDIT_DISTANCE: + return lunr.QueryParser.parseEditDistance + case lunr.QueryLexer.BOOST: + return lunr.QueryParser.parseBoost + case lunr.QueryLexer.PRESENCE: + parser.nextClause() + return lunr.QueryParser.parsePresence + default: + var errorMessage = "Unexpected lexeme type '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + + /** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ + ;(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + root.lunr = factory() + } + }(this, function () { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return lunr + })) +})(); diff --git a/wiki/search/main.js b/wiki/search/main.js new file mode 100644 index 000000000..a5e469d7c --- /dev/null +++ b/wiki/search/main.js @@ -0,0 +1,109 @@ +function getSearchTermFromLocation() { + var sPageURL = window.location.search.substring(1); + var sURLVariables = sPageURL.split('&'); + for (var i = 0; i < sURLVariables.length; i++) { + var sParameterName = sURLVariables[i].split('='); + if (sParameterName[0] == 'q') { + return decodeURIComponent(sParameterName[1].replace(/\+/g, '%20')); + } + } +} + +function joinUrl (base, path) { + if (path.substring(0, 1) === "/") { + // path starts with `/`. Thus it is absolute. + return path; + } + if (base.substring(base.length-1) === "/") { + // base ends with `/` + return base + path; + } + return base + "/" + path; +} + +function escapeHtml (value) { + return value.replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>'); +} + +function formatResult (location, title, summary) { + return ''; +} + +function displayResults (results) { + var search_results = document.getElementById("mkdocs-search-results"); + while (search_results.firstChild) { + search_results.removeChild(search_results.firstChild); + } + if (results.length > 0){ + for (var i=0; i < results.length; i++){ + var result = results[i]; + var html = formatResult(result.location, result.title, result.summary); + search_results.insertAdjacentHTML('beforeend', html); + } + } else { + var noResultsText = search_results.getAttribute('data-no-results-text'); + if (!noResultsText) { + noResultsText = "No results found"; + } + search_results.insertAdjacentHTML('beforeend', '

' + noResultsText + '

'); + } +} + +function doSearch () { + var query = document.getElementById('mkdocs-search-query').value; + if (query.length > min_search_length) { + if (!window.Worker) { + displayResults(search(query)); + } else { + searchWorker.postMessage({query: query}); + } + } else { + // Clear results for short queries + displayResults([]); + } +} + +function initSearch () { + var search_input = document.getElementById('mkdocs-search-query'); + if (search_input) { + search_input.addEventListener("keyup", doSearch); + } + var term = getSearchTermFromLocation(); + if (term) { + search_input.value = term; + doSearch(); + } +} + +function onWorkerMessage (e) { + if (e.data.allowSearch) { + initSearch(); + } else if (e.data.results) { + var results = e.data.results; + displayResults(results); + } else if (e.data.config) { + min_search_length = e.data.config.min_search_length-1; + } +} + +if (!window.Worker) { + console.log('Web Worker API not supported'); + // load index in main thread + $.getScript(joinUrl(base_url, "search/worker.js")).done(function () { + console.log('Loaded worker'); + init(); + window.postMessage = function (msg) { + onWorkerMessage({data: msg}); + }; + }).fail(function (jqxhr, settings, exception) { + console.error('Could not load worker.js'); + }); +} else { + // Wrap search in a web worker + var searchWorker = new Worker(joinUrl(base_url, "search/worker.js")); + searchWorker.postMessage({init: true}); + searchWorker.onmessage = onWorkerMessage; +} diff --git a/wiki/search/search_index.json b/wiki/search/search_index.json new file mode 100644 index 000000000..26db96b93 --- /dev/null +++ b/wiki/search/search_index.json @@ -0,0 +1 @@ +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"All-Event-Properties-Layout-Renderer/","text":"Log event all context data. Platforms Supported: All Introduced in NLog v4.0. To log one property, use ${event-properties} . See also NLog Context . Configuration Syntax ${all-event-properties:format=String:separator=String:includeEmptyValues=boolean:includeScopeProperties=boolean} Parameters Rendering Options format - How key/value pairs will be formatted. The placeholder used to define placement of the key is, [key] , and the placeholder for value is, [value] . Default value: [key]=[value] separator - The string that will be used to separate key/value pairs. Default value: , includeCallerInformation - Also render the caller information attributes? Default: false Introduced in NLog 4.1. Deprecated with NLog v4.6.8. Removed again with NLog v5 (Net45 required) includeEmptyValues - include empty values? A value is empty when null or in case of a string, null or empty string. Default value: false Introduced in NLog 4.6.4. exclude - LogEvent property-key-names to exclude from output. List of keys can be passed as comma separated values, e.g.: Key1,Key2 Introduced in NLog 4.6.8 includeScopeProperties - Include ScopeContext Properties together with LogEvent Properties. Introduced in NLog 5.0 Examples See EventProperties-Layout-Renderer","title":"All Event Properties Layout Renderer"},{"location":"All-Event-Properties-Layout-Renderer/#configuration-syntax","text":"${all-event-properties:format=String:separator=String:includeEmptyValues=boolean:includeScopeProperties=boolean}","title":"Configuration Syntax"},{"location":"All-Event-Properties-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"All-Event-Properties-Layout-Renderer/#rendering-options","text":"format - How key/value pairs will be formatted. The placeholder used to define placement of the key is, [key] , and the placeholder for value is, [value] . Default value: [key]=[value] separator - The string that will be used to separate key/value pairs. Default value: , includeCallerInformation - Also render the caller information attributes? Default: false Introduced in NLog 4.1. Deprecated with NLog v4.6.8. Removed again with NLog v5 (Net45 required) includeEmptyValues - include empty values? A value is empty when null or in case of a string, null or empty string. Default value: false Introduced in NLog 4.6.4. exclude - LogEvent property-key-names to exclude from output. List of keys can be passed as comma separated values, e.g.: Key1,Key2 Introduced in NLog 4.6.8 includeScopeProperties - Include ScopeContext Properties together with LogEvent Properties. Introduced in NLog 5.0","title":"Rendering Options"},{"location":"All-Event-Properties-Layout-Renderer/#examples","text":"See EventProperties-Layout-Renderer","title":"Examples"},{"location":"AppDomain-Layout-Renderer/","text":"Render the application domain name. Platforms Supported: All Configuration Syntax ${appdomain:format=Format} Parameters Rendering Options format - The formating. Default to Long . possible options: Long - default. The id as four number digit, colon, friendlyname. E.g. 0003:NLog.UnitTests Short - Only the id as two number digit, like \"03\". Friendly - Just the AppDomain FriendlyName. E.g. NLog.UnitTests > Introduced with NLog v5.2.7 or custom like {0} - {1}. The first parameter is the\"AppDomain.Id\", the second is the \"AppDomain.FriendlyName\". Note: use escaping of the brackets. See examples. Example Examples in the .config ${appdomain} //e.g. 0003:NLog.UnitTests ${appdomain:format=short} //e.g. 03 ${appdomain:format=long} //e.g. 0003:NLog.UnitTests ${appdomain:format={1\\} - {0\\}} //e.g. NLog.UnitTests - 3","title":"AppDomain Layout Renderer"},{"location":"AppDomain-Layout-Renderer/#configuration-syntax","text":"${appdomain:format=Format}","title":"Configuration Syntax"},{"location":"AppDomain-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AppDomain-Layout-Renderer/#rendering-options","text":"format - The formating. Default to Long . possible options: Long - default. The id as four number digit, colon, friendlyname. E.g. 0003:NLog.UnitTests Short - Only the id as two number digit, like \"03\". Friendly - Just the AppDomain FriendlyName. E.g. NLog.UnitTests > Introduced with NLog v5.2.7 or custom like {0} - {1}. The first parameter is the\"AppDomain.Id\", the second is the \"AppDomain.FriendlyName\". Note: use escaping of the brackets. See examples.","title":"Rendering Options"},{"location":"AppDomain-Layout-Renderer/#example","text":"Examples in the .config ${appdomain} //e.g. 0003:NLog.UnitTests ${appdomain:format=short} //e.g. 03 ${appdomain:format=long} //e.g. 0003:NLog.UnitTests ${appdomain:format={1\\} - {0\\}} //e.g. NLog.UnitTests - 3","title":"Example"},{"location":"AppSetting-Layout-Renderer/","text":"Value from the App Settings configuration (app.config / web.config) Platforms Supported: Limited (.NET Framework only, when using .NET Core then ${configsetting} can be used to read values from appsettings.json -file) Introduced with NLog 3.0 and with NLog 4.6+ it was included in default NLog-package without needing NLog.Extended . Configuration Syntax ${appsetting:item=String:default=String} Parameters Rendering Options item - Key in the apps setting. Required Introduced with NLog v4.5, and replaces the Name -option. Default - Default value if not present. Optional. Example AppSettings Example .config Example renderer: produces MyApplication is this case: ${appsetting:item=MyKey:default=mydefault} Example#2 renderer: produces mydefault is this case: ${appsetting:item=MyKey2:default=mydefault} Example ConnectionStrings Introduced with NLog 4.6.5 Example#3 renderer: produces http://localhost:9200 is this case: ${appsetting:item=connectionStrings.ElasticUrl} Note remember to uninstall/remove NLog.Extended -nuget-package from the application when having upgraded to NLog v4.6.5, else connectionStrings-lookup will not work.","title":"AppSetting Layout Renderer"},{"location":"AppSetting-Layout-Renderer/#configuration-syntax","text":"${appsetting:item=String:default=String}","title":"Configuration Syntax"},{"location":"AppSetting-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AppSetting-Layout-Renderer/#rendering-options","text":"item - Key in the apps setting. Required Introduced with NLog v4.5, and replaces the Name -option. Default - Default value if not present. Optional.","title":"Rendering Options"},{"location":"AppSetting-Layout-Renderer/#example-appsettings","text":"Example .config Example renderer: produces MyApplication is this case: ${appsetting:item=MyKey:default=mydefault} Example#2 renderer: produces mydefault is this case: ${appsetting:item=MyKey2:default=mydefault}","title":"Example AppSettings"},{"location":"AppSetting-Layout-Renderer/#example-connectionstrings","text":"Introduced with NLog 4.6.5 Example#3 renderer: produces http://localhost:9200 is this case: ${appsetting:item=connectionStrings.ElasticUrl} Note remember to uninstall/remove NLog.Extended -nuget-package from the application when having upgraded to NLog v4.6.5, else connectionStrings-lookup will not work.","title":"Example ConnectionStrings"},{"location":"AspNet-AppBasePath-layout-renderer/","text":"ASP.NET AppBasePath (Content Root) Platforms Supported: All (Supported in Asp.NET and Asp.NetCore ) Introduced with NLog.Web.AspNetCore v4.5.0 and NLog.Web v4.5.2 See also ${processdir} , ${basedir} , ${aspnet-webrootpath} Configuration Syntax ${aspnet-appbasepath} Remarks Application base path is also known as the content root, while wwwroot -path is root directory for static content.","title":"AspNet AppBasePath layout renderer"},{"location":"AspNet-AppBasePath-layout-renderer/#configuration-syntax","text":"${aspnet-appbasepath}","title":"Configuration Syntax"},{"location":"AspNet-AppBasePath-layout-renderer/#remarks","text":"Application base path is also known as the content root, while wwwroot -path is root directory for static content.","title":"Remarks"},{"location":"AspNet-Environment-layout-renderer/","text":"ASP.NET EnvironmentName ( ASPNETCORE_ENVIRONMENT ) Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v4.4.0 Configuration Syntax ${aspnet-environment} Remarks The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or \"environment\" as specified in any other configuration source.","title":"AspNet Environment layout renderer"},{"location":"AspNet-Environment-layout-renderer/#configuration-syntax","text":"${aspnet-environment}","title":"Configuration Syntax"},{"location":"AspNet-Environment-layout-renderer/#remarks","text":"The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or \"environment\" as specified in any other configuration source.","title":"Remarks"},{"location":"AspNet-HttpContext-Item-Layout-Renderer/","text":"ASP.NET Item variable from HttpContext.Items dictionary. Useful for storing state per request basis. Platforms Supported: All Configuration Syntax ${aspnet-item:variable=String:objectpath=String:format=String} Parameters Rendering Options item - Key for lookup in Items-dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties -option Examples You can set the value of an ASP.NET Item variable by using the following code: Example usage of ${aspnet-item} HttpContext.Items[\"myvariable\"] = 123; HttpContext.Items[\"stringvariable\"] = \"aaa BBB\"; HttpContext.Items[\"anothervariable\"] = DateTime.Now; ${aspnet-item:variable=myvariable} - produces \"123\" ${aspnet-item:variable=anothervariable} - produces \"01/01/2006 00:00:00\" ${aspnet-item:variable=anothervariable:culture=pl-PL} - produces \"2006-01-01 00:00:00\" ${aspnet-item:variable=myvariable:padding=5} - produces \" 123\" ${aspnet-item:variable=myvariable:padding=-5} - produces \"123 \" ${aspnet-item:variable=stringvariable:upperCase=true} - produces \"AAA BBB\"","title":"AspNet HttpContext Item Layout Renderer"},{"location":"AspNet-HttpContext-Item-Layout-Renderer/#configuration-syntax","text":"${aspnet-item:variable=String:objectpath=String:format=String}","title":"Configuration Syntax"},{"location":"AspNet-HttpContext-Item-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNet-HttpContext-Item-Layout-Renderer/#rendering-options","text":"item - Key for lookup in Items-dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties -option","title":"Rendering Options"},{"location":"AspNet-HttpContext-Item-Layout-Renderer/#examples","text":"You can set the value of an ASP.NET Item variable by using the following code: Example usage of ${aspnet-item} HttpContext.Items[\"myvariable\"] = 123; HttpContext.Items[\"stringvariable\"] = \"aaa BBB\"; HttpContext.Items[\"anothervariable\"] = DateTime.Now; ${aspnet-item:variable=myvariable} - produces \"123\" ${aspnet-item:variable=anothervariable} - produces \"01/01/2006 00:00:00\" ${aspnet-item:variable=anothervariable:culture=pl-PL} - produces \"2006-01-01 00:00:00\" ${aspnet-item:variable=myvariable:padding=5} - produces \" 123\" ${aspnet-item:variable=myvariable:padding=-5} - produces \"123 \" ${aspnet-item:variable=stringvariable:upperCase=true} - produces \"AAA BBB\"","title":"Examples"},{"location":"AspNet-MVC-Action-Layout-Renderer/","text":"ASP.NET MVC Action-Name by lookup of action -value in HttpContext.Current.GetRouteData Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-mvc-action} Remarks Use this layout renderer to insert the Action Method from MVC Pipeline. See also AspNetRequest-RouteParameters-Layout-Renderer for lookup of other Route-Parameter Values.","title":"AspNet MVC Action Layout Renderer"},{"location":"AspNet-MVC-Action-Layout-Renderer/#configuration-syntax","text":"${aspnet-mvc-action}","title":"Configuration Syntax"},{"location":"AspNet-MVC-Action-Layout-Renderer/#remarks","text":"Use this layout renderer to insert the Action Method from MVC Pipeline. See also AspNetRequest-RouteParameters-Layout-Renderer for lookup of other Route-Parameter Values.","title":"Remarks"},{"location":"AspNet-MVC-Controller-Layout-Renderer/","text":"ASP.NET MVC Controller-Name by lookup of controller -value in HttpContext.Current.GetRouteData Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-mvc-controller} Remarks Use this layout renderer to insert the Controller from MVC Pipeline. See also AspNetRequest-RouteParameters-Layout-Renderer for lookup of other Route-Parameter Values.","title":"AspNet MVC Controller Layout Renderer"},{"location":"AspNet-MVC-Controller-Layout-Renderer/#configuration-syntax","text":"${aspnet-mvc-controller}","title":"Configuration Syntax"},{"location":"AspNet-MVC-Controller-Layout-Renderer/#remarks","text":"Use this layout renderer to insert the Controller from MVC Pipeline. See also AspNetRequest-RouteParameters-Layout-Renderer for lookup of other Route-Parameter Values.","title":"Remarks"},{"location":"AspNet-Request-Bidirectional-Stream-Layout-Renderer/","text":"ASP.NET Request capable of upgrading connection to an opaque, bidirectional stream. 1 = Capable / Upgradable 0 = Not available Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-bidirectional-stream}","title":"AspNet Request Bidirectional Stream Layout Renderer"},{"location":"AspNet-Request-Bidirectional-Stream-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-bidirectional-stream}","title":"Configuration Syntax"},{"location":"AspNet-Request-Client-Certificate-Layout-Renderer/","text":"ASP.NET Request Client Certificate Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 Configuration Syntax ${aspnet-request-client-certificate}","title":"AspNet Request Client Certificate Layout Renderer"},{"location":"AspNet-Request-Client-Certificate-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-client-certificate}","title":"Configuration Syntax"},{"location":"AspNet-Request-ConnectionId-Layout-Renderer/","text":"ASP.NET Http Request Connection Id . The unique identifier that represents the connection. Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-connection-id}","title":"AspNet Request ConnectionId Layout Renderer"},{"location":"AspNet-Request-ConnectionId-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-connection-id}","title":"Configuration Syntax"},{"location":"AspNet-Request-ContentLength-Layout-Renderer/","text":"ASP.NET Request Header Content-Length (Ex. 1234 ) Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.0.0 and NLog.Web v5.0.0 Configuration Syntax ${aspnet-request-contentlength}","title":"AspNet Request ContentLength Layout Renderer"},{"location":"AspNet-Request-ContentLength-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-contentlength}","title":"Configuration Syntax"},{"location":"AspNet-Request-ContentType-layout-renderer/","text":"ASP.NET Content-Type header (Ex. application/json ) Platforms Supported: All Introduced with NLog.Web.AspNetCore v4.4.0 and NLog.Web v4.8.0 Configuration Syntax ${aspnet-request-contenttype}","title":"AspNet Request ContentType layout renderer"},{"location":"AspNet-Request-ContentType-layout-renderer/#configuration-syntax","text":"${aspnet-request-contenttype}","title":"Configuration Syntax"},{"location":"AspNet-Request-Duration-Layout-Renderer/","text":"ASP.NET Request Duration. Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.0.0 and NLog.Web v5.0.0 Configuration Syntax ${aspnet-request-duration} Options format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format) . string . Default null (Outputs milliseconds) Culture - The culture used for rendering. Default CultureInfo.InvariantCulture","title":"AspNet Request Duration Layout Renderer"},{"location":"AspNet-Request-Duration-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-duration}","title":"Configuration Syntax"},{"location":"AspNet-Request-Duration-Layout-Renderer/#options","text":"format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format) . string . Default null (Outputs milliseconds) Culture - The culture used for rendering. Default CultureInfo.InvariantCulture","title":"Options"},{"location":"AspNet-Request-EndPoint-Group-Layout-Renderer/","text":"ASP.NET Http Request EndPoint MetaData Group-Name . The group name of the logical endpoint in the application. Assigned using WithGroupName or [EndpointGroupName] . Platforms Supported: Limited (Only supported in ASP.NET Core v3+ ) Introduced with NLog.Web.AspNetCore v6.0.3 Configuration Syntax ${aspnet-request-endpoint-group} Notes See also ${aspnet-request-endpoint} and ${aspnet-request-endpoint-name}","title":"AspNet Request EndPoint Group Layout Renderer"},{"location":"AspNet-Request-EndPoint-Group-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-endpoint-group}","title":"Configuration Syntax"},{"location":"AspNet-Request-EndPoint-Group-Layout-Renderer/#notes","text":"See also ${aspnet-request-endpoint} and ${aspnet-request-endpoint-name}","title":"Notes"},{"location":"AspNet-Request-EndPoint-Layout-Renderer/","text":"ASP.NET Http Request EndPoint . The informational display name of the logical endpoint in the application (Ex. HTTP: GET /weatherforecast ) Platforms Supported: Limited (Only supported in ASP.NET Core v3+ ) Introduced with NLog.Web.AspNetCore v5.3 Configuration Syntax ${aspnet-request-endpoint} Notes See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint-name}","title":"AspNet Request EndPoint Layout Renderer"},{"location":"AspNet-Request-EndPoint-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-endpoint}","title":"Configuration Syntax"},{"location":"AspNet-Request-EndPoint-Layout-Renderer/#notes","text":"See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint-name}","title":"Notes"},{"location":"AspNet-Request-EndPoint-Name-Layout-Renderer/","text":"ASP.NET Http Request EndPoint MetaData Name . The name of the logical endpoint in the application. Assigned using WithName or [EndpointName] . Platforms Supported: Limited (Only supported in ASP.NET Core v3+ ) Introduced with NLog.Web.AspNetCore v6.0.3 Configuration Syntax ${aspnet-request-endpoint-name} Notes See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint}","title":"AspNet Request EndPoint Name Layout Renderer"},{"location":"AspNet-Request-EndPoint-Name-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-endpoint-name}","title":"Configuration Syntax"},{"location":"AspNet-Request-EndPoint-Name-Layout-Renderer/#notes","text":"See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint}","title":"Notes"},{"location":"AspNet-Request-HTTP-Transport-Type-Layout-Renderer/","text":"ASP.NET supported transport types that the client can use to send HTTP requests (bitwise combination). None (0) - Specifies that no transport is used. WebSockets (1) - Specifies that the web sockets transport is used. ServerSentEvents (2) - Specifies that the server sent events transport is used. LongPolling (4) - Specifies that the long polling transport is used. Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-http-transport-type}","title":"AspNet Request HTTP Transport Type Layout Renderer"},{"location":"AspNet-Request-HTTP-Transport-Type-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-http-transport-type}","title":"Configuration Syntax"},{"location":"AspNet-Request-Has-Posted-Body-Layout-Renderer/","text":"ASP.NET Http Request includes posted-body payload: 1 = CanHaveBody or ContentLength > 0 0 = Not available Platforms Supported: > Platforms Supported: Limited (Only supported in ASP.NET Core v5+ ) Introduced with NLog.Web.AspNetCore v5.1.1 Configuration Syntax ${aspnet-request-has-posted-body}","title":"AspNet Request Has Posted Body Layout Renderer"},{"location":"AspNet-Request-Has-Posted-Body-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-has-posted-body}","title":"Configuration Syntax"},{"location":"AspNet-Request-IP-Layout-Renderer/","text":"Render Client IP address Platforms Supported: All Introduced in NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0 Configuration Syntax ${aspnet-request-ip} Parameters CheckForwardedForHeader - Should check value of X-Forwarded-For header (Default = false) Introduced with NLog Web.AspNetCore 4.7.1 & NLog.Web 4.7.1 CheckForwardedForHeaderOffset - Should check value of X-Forwarded-For header and specify index-offset from comma-separated-split-array (Default = 0) Introduced with NLog Web.AspNetCore 5.2.2 Remarks AspNetCore - Uses underlying connection for this request. See HttpContext.Connection.RemoteIpAddress AspNet - Returns the REMOTE_ADDR -ServerVariables See also AspNetRequest Host Layout Renderer","title":"AspNet Request IP Layout Renderer"},{"location":"AspNet-Request-IP-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-ip}","title":"Configuration Syntax"},{"location":"AspNet-Request-IP-Layout-Renderer/#parameters","text":"CheckForwardedForHeader - Should check value of X-Forwarded-For header (Default = false) Introduced with NLog Web.AspNetCore 4.7.1 & NLog.Web 4.7.1 CheckForwardedForHeaderOffset - Should check value of X-Forwarded-For header and specify index-offset from comma-separated-split-array (Default = 0) Introduced with NLog Web.AspNetCore 5.2.2","title":"Parameters"},{"location":"AspNet-Request-IP-Layout-Renderer/#remarks","text":"AspNetCore - Uses underlying connection for this request. See HttpContext.Connection.RemoteIpAddress AspNet - Returns the REMOTE_ADDR -ServerVariables See also AspNetRequest Host Layout Renderer","title":"Remarks"},{"location":"AspNet-Request-Inherent-KeepAlive-Layout-Renderer/","text":"ASP.NET Request using connection transport capable of \"inherent keep-alive\" 1 - Can inform the client whether connection is still active. 0 = inherent keep-alive not available. The most common example of this feature is the Long Polling HTTP transport Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-inherent-keep-alive}","title":"AspNet Request Inherent KeepAlive Layout Renderer"},{"location":"AspNet-Request-Inherent-KeepAlive-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-inherent-keep-alive}","title":"Configuration Syntax"},{"location":"AspNet-Request-IsWebSocket-Layout-Renderer/","text":"ASP.NET Request HttpContext.WebSockets.IsWebSocketRequest as 1 or 0 Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 Configuration Syntax ${aspnet-request-is-web-socket}","title":"AspNet Request IsWebSocket Layout Renderer"},{"location":"AspNet-Request-IsWebSocket-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-is-web-socket}","title":"Configuration Syntax"},{"location":"AspNet-Request-Local-IP-Layout-Renderer/","text":"ASP.NET Request HttpContext.Connection.LocalIpAddress Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 Configuration Syntax ${aspnet-request-local-ip}","title":"AspNet Request Local IP Layout Renderer"},{"location":"AspNet-Request-Local-IP-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-local-ip}","title":"Configuration Syntax"},{"location":"AspNet-Request-Local-Port-Layout-Renderer/","text":"ASP.NET Request HttpContext.Connection.LocalPort Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 Configuration Syntax ${aspnet-request-local-port}","title":"AspNet Request Local Port Layout Renderer"},{"location":"AspNet-Request-Local-Port-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-local-port}","title":"Configuration Syntax"},{"location":"AspNet-Request-Remote-Port-Layout-Renderer/","text":"ASP.NET Request HttpContext.Connection.RemotePort Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 Configuration Syntax ${aspnet-request-remote-port}","title":"AspNet Request Remote Port Layout Renderer"},{"location":"AspNet-Request-Remote-Port-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-remote-port}","title":"Configuration Syntax"},{"location":"AspNet-Request-ServerVariable-Layout-Renderer/","text":"Render ASP.NET Server Variable (Ex. APP_POOL_ID) Platforms Supported: All Introduced in NLog Web.AspNetCore 5.1.0 & NLog.Web 5.1.0 Configuration Syntax ${aspnet-request-servervariable:item=APP_POOL_ID}","title":"AspNet Request ServerVariable Layout Renderer"},{"location":"AspNet-Request-ServerVariable-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-servervariable:item=APP_POOL_ID}","title":"Configuration Syntax"},{"location":"AspNet-Request-StreamId-Layout-Renderer/","text":"ASP.NET Http Request Stream Id . The unique identifier that represents the reusable socket. Platforms Supported: Limited (Only supported in ASP.NET Core v5+ ) Introduced with NLog.Web.AspNetCore v5.1.1 Configuration Syntax ${aspnet-request-stream-id}","title":"AspNet Request StreamId Layout Renderer"},{"location":"AspNet-Request-StreamId-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-stream-id}","title":"Configuration Syntax"},{"location":"AspNet-Request-TLS-Handshake-Layout-Renderer/","text":"ASP.NET TLS Handshake Features ITlsHandshakeFeature of the connection. Platforms Supported: Limited (Only supported in ASP.NET Core ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-tls-handshake:property=Protocol} Property Enum CipherAlgorithm - Gets the CipherAlgorithmType . CipherStrength - Gets the cipher strength. HashAlgorithm - Gets the HashAlgorithmType . HashStrength - Gets the hash strength. KeyExchangeAlgorithm - Gets the ExchangeAlgorithmType . KeyExchangeStrength - Gets the key exchange algorithm strength. Protocol - Gets the SslProtocols . HostName - Gets the host name from the \"server_name\" (SNI) extension. See RFC 6066 Introduced with NLog.Web.AspNetCore v6.1.0 NegotiatedCipherSuite - Gets the TlsCipherSuite Introduced with NLog.Web.AspNetCore v6.1.0","title":"AspNet Request TLS Handshake Layout Renderer"},{"location":"AspNet-Request-TLS-Handshake-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-tls-handshake:property=Protocol}","title":"Configuration Syntax"},{"location":"AspNet-Request-TLS-Handshake-Layout-Renderer/#property-enum","text":"CipherAlgorithm - Gets the CipherAlgorithmType . CipherStrength - Gets the cipher strength. HashAlgorithm - Gets the HashAlgorithmType . HashStrength - Gets the hash strength. KeyExchangeAlgorithm - Gets the ExchangeAlgorithmType . KeyExchangeStrength - Gets the key exchange algorithm strength. Protocol - Gets the SslProtocols . HostName - Gets the host name from the \"server_name\" (SNI) extension. See RFC 6066 Introduced with NLog.Web.AspNetCore v6.1.0 NegotiatedCipherSuite - Gets the TlsCipherSuite Introduced with NLog.Web.AspNetCore v6.1.0","title":"Property Enum"},{"location":"AspNet-Request-TLS-Token-Bindng-Layout-Renderer/","text":"ASP.NET TLS Token Bindings for Provider and Referrer Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-tls-token-binding:property=provider} Options Property - Tls Token Binding Source Provider - Tls Token Binding for Provider Referrer - Tls Token Binding for Referrer Format - Tls Token Binding Format Base64 - Emit the byte array using Convert.ToBase64(byte[]) Hex - Emit the byte array using BitConverter.ToString(byte[])","title":"AspNet Request TLS Token Bindng Layout Renderer"},{"location":"AspNet-Request-TLS-Token-Bindng-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-tls-token-binding:property=provider}","title":"Configuration Syntax"},{"location":"AspNet-Request-TLS-Token-Bindng-Layout-Renderer/#options","text":"Property - Tls Token Binding Source Provider - Tls Token Binding for Provider Referrer - Tls Token Binding for Referrer Format - Tls Token Binding Format Base64 - Emit the byte array using Convert.ToBase64(byte[]) Hex - Emit the byte array using BitConverter.ToString(byte[])","title":"Options"},{"location":"AspNet-Request-Tracking-Consent-Layout-Renderer/","text":"ASP.NET Tracking Consent Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-tracking-consent:property=CanTrack} Options Property - Enum Values: CanTrack - Indicates either if consent has been given ( 1 ), or if consent is not required ( 0 ) HasConsent - Indicates if consent was given. IsConsentNeeded - Indicates if consent is required for the given request.","title":"AspNet Request Tracking Consent Layout Renderer"},{"location":"AspNet-Request-Tracking-Consent-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-tracking-consent:property=CanTrack}","title":"Configuration Syntax"},{"location":"AspNet-Request-Tracking-Consent-Layout-Renderer/#options","text":"Property - Enum Values: CanTrack - Indicates either if consent has been given ( 1 ), or if consent is not required ( 0 ) HasConsent - Indicates if consent was given. IsConsentNeeded - Indicates if consent is required for the given request.","title":"Options"},{"location":"AspNet-Request-Trailers-Layout-Renderer/","text":"ASP.NET Request Trailers Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-request-trailersitems=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Options Rendering Options Items - Trailer names to be rendered. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the TrailerNames -option. Exclude - Trailer names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1","title":"AspNet Request Trailers Layout Renderer"},{"location":"AspNet-Request-Trailers-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-trailersitems=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNet-Request-Trailers-Layout-Renderer/#options","text":"","title":"Options"},{"location":"AspNet-Request-Trailers-Layout-Renderer/#rendering-options","text":"Items - Trailer names to be rendered. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the TrailerNames -option. Exclude - Trailer names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2","title":"Rendering Options"},{"location":"AspNet-Request-Trailers-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1","title":"Formatting options"},{"location":"AspNet-Request-WebSocket-Requested-Protocols-Layout-Renderer/","text":"ASP.NET Request HttpContext.WebSockets.WebSocketRequestedProtocols Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 (NET46) Configuration Syntax ${aspnet-request-web-socket-requested-protocols} Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array itemSeparator Separator between items. Default: , . Only applies when OutputFormat is Flat .","title":"AspNet Request WebSocket Requested Protocols Layout Renderer"},{"location":"AspNet-Request-WebSocket-Requested-Protocols-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-web-socket-requested-protocols}","title":"Configuration Syntax"},{"location":"AspNet-Request-WebSocket-Requested-Protocols-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array itemSeparator Separator between items. Default: , . Only applies when OutputFormat is Flat .","title":"Formatting options"},{"location":"AspNet-Request-posted-body-layout-renderer/","text":"Render the posted body, e.g. FORM or Ajax POST Platforms Supported: All Introduced in NLog.Web.AspNetCore v5.1.0 using NLogRequestPostedBodyMiddleware , and in NLog.Web v5.1.0 using NLogRequestPostedBodyModule . \u26a0\ufe0f All versions before NLog.Web.AspNetCore v5.1.0 had incorrect implementation of ${aspnet-request-posted-body} , that caused random failures for the Web-Application. Configuration Syntax ${aspnet-request-posted-body} ASP.NET Core Setup NLog.Web.AspNetCore 5.1.0+ Register NLogRequestPostedBodyMiddleware as middleware in the Configure method of Startup class The middelware will activate EnablesBuffering when matching the criteria. // needed for ${aspnet-request-posted-body} with an API Controller. // The options default to only logging a maximum of 30KB, since above that the ASP.NET Core framework // uses a temporary file on disk instead of a memory buffer. // Also, only content types starting with \u2018text/\u2018, or those ending with \u2018xml\u2019, \u2018html\u2019, \u2018json\u2019, or content types // that have the word \u2018charset\u2019 are logged, since we desire to log strings and not binary content // Those can be overridden in the options if necessary. But typically the default options should be adequate. app.UseMiddleware (new NLog.Web.NLogRequestPostedBodyMiddlewareOptions()); Full Example: public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(\"/Home/Error\"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); // needed for ${aspnet-request-posted-body} with an API Controller. app.UseMiddleware( new NLog.Web.NLogRequestPostedBodyMiddlewareOptions()); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: \"default\", pattern: \"{controller=Home}/{action=Index}/{id?}\"); }); NLogRequestPostedBodyMiddleware Options - int MaxContentLength - The maximum request posted body that will be captured. Defaults to 30 KB. - HttpRequest.EnableBuffer() is documented as using memory buffer until 30 KB, then this will use temp files on disk, which could have a performance impact. IList> AllowContentTypes The Key is the prefix value such as \u2018text\u2019. The Value is the suffix value such as \u2018html\u2019. The default contents of this property are: 'application/', 'json' 'application/', 'xml' 'application/', 'html' 'text/', '' '', 'charset' Predicate ShouldCapture() By default this method returns true if The content length is not null and is <= MaxContentLength The content type must match one of the entries in the AllowContentTypes List. For a match the ContentType must StartsWith the Key, case insensitive, and also have an IndexOf the Value, case insensitive. An empty string for the Key or for the Value acts as a wildcard match. The method has the HttpContext as the parameter, so a user wishing to override this property should have all the properties required to implement an override. See also: HTTP-Request-Logging ASP.NET Setup NLog.Web 5.1.0+ To use this target with NLog.Web, then you need to enable the HttpModule NLogRequestPostedBodyModule : public class MyGlobalApplication : System.Web.HttpApplication { public static IHttpModule NLogRequestPostedBody = new NLog.Web.NLogRequestPostedBodyModule(); public override void Init() { base.Init(); NLogRequestPostedBody.Init(this); } } See also: HTTP-Request-Logging","title":"AspNet Request posted body layout renderer"},{"location":"AspNet-Request-posted-body-layout-renderer/#configuration-syntax","text":"${aspnet-request-posted-body}","title":"Configuration Syntax"},{"location":"AspNet-Request-posted-body-layout-renderer/#aspnet-core-setup","text":"NLog.Web.AspNetCore 5.1.0+ Register NLogRequestPostedBodyMiddleware as middleware in the Configure method of Startup class The middelware will activate EnablesBuffering when matching the criteria. // needed for ${aspnet-request-posted-body} with an API Controller. // The options default to only logging a maximum of 30KB, since above that the ASP.NET Core framework // uses a temporary file on disk instead of a memory buffer. // Also, only content types starting with \u2018text/\u2018, or those ending with \u2018xml\u2019, \u2018html\u2019, \u2018json\u2019, or content types // that have the word \u2018charset\u2019 are logged, since we desire to log strings and not binary content // Those can be overridden in the options if necessary. But typically the default options should be adequate. app.UseMiddleware (new NLog.Web.NLogRequestPostedBodyMiddlewareOptions()); Full Example: public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(\"/Home/Error\"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); // needed for ${aspnet-request-posted-body} with an API Controller. app.UseMiddleware( new NLog.Web.NLogRequestPostedBodyMiddlewareOptions()); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: \"default\", pattern: \"{controller=Home}/{action=Index}/{id?}\"); }); NLogRequestPostedBodyMiddleware Options - int MaxContentLength - The maximum request posted body that will be captured. Defaults to 30 KB. - HttpRequest.EnableBuffer() is documented as using memory buffer until 30 KB, then this will use temp files on disk, which could have a performance impact. IList> AllowContentTypes The Key is the prefix value such as \u2018text\u2019. The Value is the suffix value such as \u2018html\u2019. The default contents of this property are: 'application/', 'json' 'application/', 'xml' 'application/', 'html' 'text/', '' '', 'charset' Predicate ShouldCapture() By default this method returns true if The content length is not null and is <= MaxContentLength The content type must match one of the entries in the AllowContentTypes List. For a match the ContentType must StartsWith the Key, case insensitive, and also have an IndexOf the Value, case insensitive. An empty string for the Key or for the Value acts as a wildcard match. The method has the HttpContext as the parameter, so a user wishing to override this property should have all the properties required to implement an override. See also: HTTP-Request-Logging","title":"ASP.NET Core Setup"},{"location":"AspNet-Request-posted-body-layout-renderer/#aspnet-setup","text":"NLog.Web 5.1.0+ To use this target with NLog.Web, then you need to enable the HttpModule NLogRequestPostedBodyModule : public class MyGlobalApplication : System.Web.HttpApplication { public static IHttpModule NLogRequestPostedBody = new NLog.Web.NLogRequestPostedBodyModule(); public override void Init() { base.Init(); NLogRequestPostedBody.Init(this); } } See also: HTTP-Request-Logging","title":"ASP.NET Setup"},{"location":"AspNet-Response-ContentLength-Layout-Renderer/","text":"ASP.NET Response Header Content-Length (Ex. 1234 ) Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.0.0 and NLog.Web v5.0.0 Configuration Syntax ${aspnet-response-contentlength}","title":"AspNet Response ContentLength Layout Renderer"},{"location":"AspNet-Response-ContentLength-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-contentlength}","title":"Configuration Syntax"},{"location":"AspNet-Response-ContentType-Layout-Renderer/","text":"ASP.NET Response Header Content-Type (Ex. application/json ) Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 Configuration Syntax ${aspnet-response-contenttype}","title":"AspNet Response ContentType Layout Renderer"},{"location":"AspNet-Response-ContentType-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-contenttype}","title":"Configuration Syntax"},{"location":"AspNet-Response-Cookie-Layout-Renderer/","text":"Renders the Cookie Name and Values stored in the ASP.NET Response Cookies collection. Platforms Supported: All Introduced in NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 Configuration Syntax ${aspnet-response-cookie:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Parameters Rendering Options items - Cookie key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the cookieNames -option. exclude - Cookie key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary. itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between key and value. Default: = . Only applies when OutputFormat is Flat . objectSeparator - Separator between object-collections of key-value-pair-items. Default: ; . Only applies when OutputFormat is Flat and Verbose is True . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1 Verbose - Render additional properties of the HttpCookie-object (Domain, Path, Expires, Secure, HttpOnly). Examples In C# code: Request.Cookies[\"key1\"] = \"value1\"; Request.Cookies[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\"; Log single cookie in default Flat output format ${aspnet-response-cookie:CookieNames=key1} Will print: \"key1=value1\" Log multiple cookies in default Flat output format ${aspnet-response-cookie:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\" Log single cookie in JSON output format ${aspnet-response-cookie:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}] Log multiple cookies in JSON output format ${aspnet-response-cookie:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}] Log single cookie as JSON dictionary output format ${aspnet-response-cookie:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"} Log single cookie in Flat output format as value only ${aspnet-response-cookie:items=key1:ValuesOnly=true} Will print: \"value1\" Log single cookie in JSON output format as value only ${aspnet-response-cookie:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"] Log multiple cookies in JSON output format as value only ${aspnet-response-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"AspNet Response Cookie Layout Renderer"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-cookie:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#rendering-options","text":"items - Cookie key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the cookieNames -option. exclude - Cookie key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2","title":"Rendering Options"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary. itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between key and value. Default: = . Only applies when OutputFormat is Flat . objectSeparator - Separator between object-collections of key-value-pair-items. Default: ; . Only applies when OutputFormat is Flat and Verbose is True . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1 Verbose - Render additional properties of the HttpCookie-object (Domain, Path, Expires, Secure, HttpOnly).","title":"Formatting options"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#examples","text":"In C# code: Request.Cookies[\"key1\"] = \"value1\"; Request.Cookies[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\";","title":"Examples"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-single-cookie-in-default-flat-output-format","text":"${aspnet-response-cookie:CookieNames=key1} Will print: \"key1=value1\"","title":"Log single cookie in default Flat output format"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-multiple-cookies-in-default-flat-output-format","text":"${aspnet-response-cookie:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\"","title":"Log multiple cookies in default Flat output format"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-single-cookie-in-json-output-format","text":"${aspnet-response-cookie:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}]","title":"Log single cookie in JSON output format"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-multiple-cookies-in-json-output-format","text":"${aspnet-response-cookie:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}]","title":"Log multiple cookies in JSON output format"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-single-cookie-as-json-dictionary-output-format","text":"${aspnet-response-cookie:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"}","title":"Log single cookie as JSON dictionary output format"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-single-cookie-in-flat-output-format-as-value-only","text":"${aspnet-response-cookie:items=key1:ValuesOnly=true} Will print: \"value1\"","title":"Log single cookie in Flat output format as value only"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-single-cookie-in-json-output-format-as-value-only","text":"${aspnet-response-cookie:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"]","title":"Log single cookie in JSON output format as value only"},{"location":"AspNet-Response-Cookie-Layout-Renderer/#log-multiple-cookies-in-json-output-format-as-value-only","text":"${aspnet-response-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"Log multiple cookies in JSON output format as value only"},{"location":"AspNet-Response-HTTPS-Compression-Layout-Renderer/","text":"ASP.NET Response HTTPS Compression Mode Default (0) - No value has been specified, use the configured defaults. DoNotCompress (1) - Opts out of compression over HTTPS. Enabling compression on HTTPS requests for remotely manipulable content may expose security problems. Compress (2) - Opts into compression over HTTPS. Enabling compression on HTTPS requests for remotely manipulable content may expose security problems. Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-response-https-compression}","title":"AspNet Response HTTPS Compression Layout Renderer"},{"location":"AspNet-Response-HTTPS-Compression-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-https-compression}","title":"Configuration Syntax"},{"location":"AspNet-Response-HasStarted-Layout-Renderer/","text":"ASP.NET Http Response HasStarted (as 0 or 1 ) Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 NET46 Configuration Syntax ${aspnet-response-has-started}","title":"AspNet Response HasStarted Layout Renderer"},{"location":"AspNet-Response-HasStarted-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-has-started}","title":"Configuration Syntax"},{"location":"AspNet-Response-Headers-Layout-Renderer/","text":"ASP.NET Response Headers key/value pairs. Platforms Supported: All Introduced in NLog.Web 5.1.0 and NLog.Web.AspNetCore 5.1.0 Configuration Syntax ${aspnet-response-headers:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Parameters Rendering Options items - Header key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the headerNames -option. exclude - Header key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1 Remarks Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Response Headers collection. Examples In C# code: Response.Headers[\"key1\"] = \"value1\"; Response.Headers[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\"; Log single header in default Flat output format ${aspnet-response-headers:items=key1} Will print: \"key1=value1\" Log multiple headers in default Flat output format ${aspnet-response-headers:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\" Log single header ie in JSON output format ${aspnet-response-headers:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}] Log multiple headers in JSON output format ${aspnet-response-headers:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}] Log single header as JSON dictionary: ${aspnet-response-headers:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"} Log single header in Flat output format as value only ${aspnet-response-headers:items=key1:ValuesOnly=true} Will print: \"value1\" Log single header in JSON output format as value only ${aspnet-response-headers:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"] Log multiple headers in JSON output format as value only ${aspnet-response-headers:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"AspNet Response Headers Layout Renderer"},{"location":"AspNet-Response-Headers-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-headers:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNet-Response-Headers-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNet-Response-Headers-Layout-Renderer/#rendering-options","text":"items - Header key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the headerNames -option. exclude - Header key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2","title":"Rendering Options"},{"location":"AspNet-Response-Headers-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1","title":"Formatting options"},{"location":"AspNet-Response-Headers-Layout-Renderer/#remarks","text":"Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Response Headers collection.","title":"Remarks"},{"location":"AspNet-Response-Headers-Layout-Renderer/#examples","text":"In C# code: Response.Headers[\"key1\"] = \"value1\"; Response.Headers[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\";","title":"Examples"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-single-header-in-default-flat-output-format","text":"${aspnet-response-headers:items=key1} Will print: \"key1=value1\"","title":"Log single header in default Flat output format"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-multiple-headers-in-default-flat-output-format","text":"${aspnet-response-headers:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\"","title":"Log multiple headers in default Flat output format"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-single-header-ie-in-json-output-format","text":"${aspnet-response-headers:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}]","title":"Log single header ie in JSON output format"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-multiple-headers-in-json-output-format","text":"${aspnet-response-headers:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}]","title":"Log multiple headers in JSON output format"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-single-header-as-json-dictionary","text":"${aspnet-response-headers:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"}","title":"Log single header as JSON dictionary:"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-single-header-in-flat-output-format-as-value-only","text":"${aspnet-response-headers:items=key1:ValuesOnly=true} Will print: \"value1\"","title":"Log single header in Flat output format as value only"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-single-header-in-json-output-format-as-value-only","text":"${aspnet-response-headers:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"]","title":"Log single header in JSON output format as value only"},{"location":"AspNet-Response-Headers-Layout-Renderer/#log-multiple-headers-in-json-output-format-as-value-only","text":"${aspnet-response-headers:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"Log multiple headers in JSON output format as value only"},{"location":"AspNet-Response-Trailers-Layout-Renderer/","text":"ASP.NET Response Trailers Platforms Supported: Limited (Only supported in Asp.NetCore ) Introduced with NLog.Web.AspNetCore v5.1.0 Configuration Syntax ${aspnet-response-trailers:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Options Rendering Options Items - Trailer names to be rendered. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the TrailerNames -option. Exclude - Trailer names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1","title":"AspNet Response Trailers Layout Renderer"},{"location":"AspNet-Response-Trailers-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-trailers:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNet-Response-Trailers-Layout-Renderer/#options","text":"","title":"Options"},{"location":"AspNet-Response-Trailers-Layout-Renderer/#rendering-options","text":"Items - Trailer names to be rendered. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the TrailerNames -option. Exclude - Trailer names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2","title":"Rendering Options"},{"location":"AspNet-Response-Trailers-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1","title":"Formatting options"},{"location":"AspNet-User-Claim-Layout-Renderer/","text":"ASP.NET User Claims authorization values. Platforms Supported: All Introduced with NLog.Web.AspNetCore v4.10.0, and with NLog.Web v5.1.0 for NET46 Configuration Syntax ${aspnet-user-claim:ClaimTypes.Name} Parameters ClaimType - default parameter. Key to lookup using ClaimsIdentity.FindFirst(string) with fallback to ClaimsPrincipal.FindFirst(string) . When value is prefixed with ClaimTypes. (Remember dot) then it will lookup in well-known claim types from ClaimTypes -constants. For example ClaimsTypes.Name NLog.Web.AspNetCore v5.3.3 supports outputting all values, when not having specified any ClaimType. Formatting options NLog.Web.AspNetCore v5.3.3 supports the following formatting options, when outputting all value by not specifying any ClaimType: outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Remarks See also ClaimTypes -constants. For Azure Entra Access Tokens then one can resolve the following Entra Claim-values : ${aspnet-user-claim:oid} - Azure AccessToken ObjectId ${aspnet-user-claim:tid} - Azure AccessToken TenantId ${aspnet-user-claim:appid} - Azure AccessToken ApplicationId","title":"AspNet User Claim Layout Renderer"},{"location":"AspNet-User-Claim-Layout-Renderer/#configuration-syntax","text":"${aspnet-user-claim:ClaimTypes.Name}","title":"Configuration Syntax"},{"location":"AspNet-User-Claim-Layout-Renderer/#parameters","text":"ClaimType - default parameter. Key to lookup using ClaimsIdentity.FindFirst(string) with fallback to ClaimsPrincipal.FindFirst(string) . When value is prefixed with ClaimTypes. (Remember dot) then it will lookup in well-known claim types from ClaimTypes -constants. For example ClaimsTypes.Name NLog.Web.AspNetCore v5.3.3 supports outputting all values, when not having specified any ClaimType.","title":"Parameters"},{"location":"AspNet-User-Claim-Layout-Renderer/#formatting-options","text":"NLog.Web.AspNetCore v5.3.3 supports the following formatting options, when outputting all value by not specifying any ClaimType: outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false .","title":"Formatting options"},{"location":"AspNet-User-Claim-Layout-Renderer/#remarks","text":"See also ClaimTypes -constants. For Azure Entra Access Tokens then one can resolve the following Entra Claim-values : ${aspnet-user-claim:oid} - Azure AccessToken ObjectId ${aspnet-user-claim:tid} - Azure AccessToken TenantId ${aspnet-user-claim:appid} - Azure AccessToken ApplicationId","title":"Remarks"},{"location":"AspNet-User-isAuthenticated-Layout-Renderer/","text":"Render if user is authenticated. Renders 0 or 1 . Platforms Supported: All Introduced in NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0 Configuration Syntax ${aspnet-user-isAuthenticated}","title":"AspNet User isAuthenticated Layout Renderer"},{"location":"AspNet-User-isAuthenticated-Layout-Renderer/#configuration-syntax","text":"${aspnet-user-isAuthenticated}","title":"Configuration Syntax"},{"location":"AspNet-WebRootPath-layout-renderer/","text":"ASP.NET WebRootPath (wwwroot) Platforms Supported: All (Supported in Asp.NET and Asp.NetCore ) Introduced with NLog.Web.AspNetCore v4.5.0 and NLog.Web v4.5.2 Configuration Syntax ${aspnet-webrootpath} Remarks The web root (wwwroot) is the root directory from which static content is served, while the content root is also known as application base path .","title":"AspNet WebRootPath layout renderer"},{"location":"AspNet-WebRootPath-layout-renderer/#configuration-syntax","text":"${aspnet-webrootpath}","title":"Configuration Syntax"},{"location":"AspNet-WebRootPath-layout-renderer/#remarks","text":"The web root (wwwroot) is the root directory from which static content is served, while the content root is also known as application base path .","title":"Remarks"},{"location":"AspNetApplication-layout-renderer/","text":"ASP.NET Application Dictionary Value. Platforms Support: Limited (Not supported in ASP.NET Core - ServerVariables are non-existing in ASP.NET Core. ) Configuration Syntax ${aspnet-application:variable=String} Parameters item - Key for lookup in Application-Dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2.1 Remarks Use this layout renderer to output the value of the specified variable stored in the ASP.NET Application dictionary","title":"AspNetApplication layout renderer"},{"location":"AspNetApplication-layout-renderer/#configuration-syntax","text":"${aspnet-application:variable=String}","title":"Configuration Syntax"},{"location":"AspNetApplication-layout-renderer/#parameters","text":"item - Key for lookup in Application-Dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2.1","title":"Parameters"},{"location":"AspNetApplication-layout-renderer/#remarks","text":"Use this layout renderer to output the value of the specified variable stored in the ASP.NET Application dictionary","title":"Remarks"},{"location":"AspNetBufferingWrapper-target/","text":"Buffers log events for the duration of ASP.NET request and sends them down to the wrapped target at the end of a request. Platforms Supported: All Introduced with NLog.Web.AspNetCore v5.2.1 and NLog.Web v4.0 Configuration Syntax Parameters General Options name - Name of the target. Buffering Options bufferSize - Initial capacity for the buffering of log events. Integer Default: 100 bufferGrowLimit - Maximum number of log events that the buffer can keep, when growing beyond the limit and overflows then it will drop the oldest logevents. Integer Default: 0 (Disable growing) growBufferAsNeeded - Indicates whether buffer is allow to grow up to bufferGrowLimit . Boolean Default: True Remarks Typically this target is used in cooperation with PostFilteringTargetWrapper to provide verbose logging for failing requests and normal or no logging for successful requests. We need to make the decision of the final filtering rule to apply after all logs for a page have been generated. ASP.NET Core Setup To use this target with NLog.Web.AspNetCore, then you need to enable the NLogBufferingTargetWrapperMiddleware in the Startup.cs file using NLog.Web; app.UseMiddleware(); where app is an IApplicationBuilder. ASP.NET Setup To use this target with NLog.Web, then you need to update web.config to register NLogHttpModule : ","title":"AspNetBufferingWrapper target"},{"location":"AspNetBufferingWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"AspNetBufferingWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"AspNetBufferingWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"AspNetBufferingWrapper-target/#buffering-options","text":"bufferSize - Initial capacity for the buffering of log events. Integer Default: 100 bufferGrowLimit - Maximum number of log events that the buffer can keep, when growing beyond the limit and overflows then it will drop the oldest logevents. Integer Default: 0 (Disable growing) growBufferAsNeeded - Indicates whether buffer is allow to grow up to bufferGrowLimit . Boolean Default: True","title":"Buffering Options"},{"location":"AspNetBufferingWrapper-target/#remarks","text":"Typically this target is used in cooperation with PostFilteringTargetWrapper to provide verbose logging for failing requests and normal or no logging for successful requests. We need to make the decision of the final filtering rule to apply after all logs for a page have been generated. ","title":"Remarks"},{"location":"AspNetBufferingWrapper-target/#aspnet-core-setup","text":"To use this target with NLog.Web.AspNetCore, then you need to enable the NLogBufferingTargetWrapperMiddleware in the Startup.cs file using NLog.Web; app.UseMiddleware(); where app is an IApplicationBuilder.","title":"ASP.NET Core Setup"},{"location":"AspNetBufferingWrapper-target/#aspnet-setup","text":"To use this target with NLog.Web, then you need to update web.config to register NLogHttpModule : ","title":"ASP.NET Setup"},{"location":"AspNetEnvironment-layout-renderer/","text":"See AspNet-Environment-layout-renderer","title":"AspNetEnvironment layout renderer"},{"location":"AspNetItem-layout-renderer/","text":"ASP.NET Item variable from HttpContext.Items dictionary. Useful for storing state per request basis. Platforms Supported: All Configuration Syntax ${aspnet-item:item=String:objectpath=String:format=String} Parameters Rendering Options item - Key for lookup in Items-dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties -option Examples You can set the value of an ASP.NET Item variable by using the following code: Example usage of ${aspnet-item} HttpContext.Items[\"myvariable\"] = 123; HttpContext.Items[\"stringvariable\"] = \"aaa BBB\"; HttpContext.Items[\"anothervariable\"] = DateTime.Now; ${aspnet-item:variable=myvariable} - produces \"123\" ${aspnet-item:variable=anothervariable} - produces \"01/01/2006 00:00:00\" ${aspnet-item:variable=anothervariable:culture=pl-PL} - produces \"2006-01-01 00:00:00\" ${aspnet-item:variable=myvariable:padding=5} - produces \" 123\" ${aspnet-item:variable=myvariable:padding=-5} - produces \"123 \" ${aspnet-item:variable=stringvariable:upperCase=true} - produces \"AAA BBB\"","title":"AspNetItem layout renderer"},{"location":"AspNetItem-layout-renderer/#configuration-syntax","text":"${aspnet-item:item=String:objectpath=String:format=String}","title":"Configuration Syntax"},{"location":"AspNetItem-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetItem-layout-renderer/#rendering-options","text":"item - Key for lookup in Items-dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties -option","title":"Rendering Options"},{"location":"AspNetItem-layout-renderer/#examples","text":"You can set the value of an ASP.NET Item variable by using the following code: Example usage of ${aspnet-item} HttpContext.Items[\"myvariable\"] = 123; HttpContext.Items[\"stringvariable\"] = \"aaa BBB\"; HttpContext.Items[\"anothervariable\"] = DateTime.Now; ${aspnet-item:variable=myvariable} - produces \"123\" ${aspnet-item:variable=anothervariable} - produces \"01/01/2006 00:00:00\" ${aspnet-item:variable=anothervariable:culture=pl-PL} - produces \"2006-01-01 00:00:00\" ${aspnet-item:variable=myvariable:padding=5} - produces \" 123\" ${aspnet-item:variable=myvariable:padding=-5} - produces \"123 \" ${aspnet-item:variable=stringvariable:upperCase=true} - produces \"AAA BBB\"","title":"Examples"},{"location":"AspNetRequest-Cookie-Layout-Renderer/","text":"ASP.NET Request Cookie key/value pairs. Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-request-cookie:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Parameters Rendering Options items - Cookie key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all). Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the cookieNames -option. With NLog.Web / NLog.Web.AspNetCore v4.9 then all key/value pairs will be rendered, when not specified. * exclude - Cookie key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Introduced with NLog.Web / NLog.Web.AspNetCore v4.9 Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 ValuesOnly Only render the values of the key/value pairs. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v4.6 LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1 Remarks Use this layout renderer to log the value of the specified cookie(s) stored in the ASP.NET Request Cookies collection. Examples In C# code: Request.Cookies[\"key1\"] = \"value1\"; Request.Cookies[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\"; Log single cookie in default Flat output format ${aspnet-request-cookie:items=key1} Will print: \"key1=value1\" Log multiple cookies in default Flat output format ${aspnet-request-cookie:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\" Log single cookie in JSON output format ${aspnet-request-cookie:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}] Log multiple cookies in JSON output format ${aspnet-request-cookie:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}] Log single cookie as JSON dictionary output format ${aspnet-request-cookie:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"} Log single cookie in Flat output format as value only ${aspnet-request-cookie:items=key1:ValuesOnly=true} Will print: \"value1\" Log single cookie in JSON output format as value only ${aspnet-request-cookie:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"] Log multiple cookies in JSON output format as value only ${aspnet-request-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"AspNetRequest Cookie Layout Renderer"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-cookie:items=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#rendering-options","text":"items - Cookie key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all). Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the cookieNames -option. With NLog.Web / NLog.Web.AspNetCore v4.9 then all key/value pairs will be rendered, when not specified. * exclude - Cookie key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Introduced with NLog.Web / NLog.Web.AspNetCore v4.9","title":"Rendering Options"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 ValuesOnly Only render the values of the key/value pairs. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v4.6 LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1","title":"Formatting options"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#remarks","text":"Use this layout renderer to log the value of the specified cookie(s) stored in the ASP.NET Request Cookies collection.","title":"Remarks"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#examples","text":"In C# code: Request.Cookies[\"key1\"] = \"value1\"; Request.Cookies[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\";","title":"Examples"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-single-cookie-in-default-flat-output-format","text":"${aspnet-request-cookie:items=key1} Will print: \"key1=value1\"","title":"Log single cookie in default Flat output format"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-multiple-cookies-in-default-flat-output-format","text":"${aspnet-request-cookie:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\"","title":"Log multiple cookies in default Flat output format"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-single-cookie-in-json-output-format","text":"${aspnet-request-cookie:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}]","title":"Log single cookie in JSON output format"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-multiple-cookies-in-json-output-format","text":"${aspnet-request-cookie:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}]","title":"Log multiple cookies in JSON output format"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-single-cookie-as-json-dictionary-output-format","text":"${aspnet-request-cookie:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"}","title":"Log single cookie as JSON dictionary output format"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-single-cookie-in-flat-output-format-as-value-only","text":"${aspnet-request-cookie:items=key1:ValuesOnly=true} Will print: \"value1\"","title":"Log single cookie in Flat output format as value only"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-single-cookie-in-json-output-format-as-value-only","text":"${aspnet-request-cookie:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"]","title":"Log single cookie in JSON output format as value only"},{"location":"AspNetRequest-Cookie-Layout-Renderer/#log-multiple-cookies-in-json-output-format-as-value-only","text":"${aspnet-request-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"Log multiple cookies in JSON output format as value only"},{"location":"AspNetRequest-Form-Layout-Renderer/","text":"ASP.NET Request Form key/value pairs. Platforms Supported: All Introduced in NLog.Web 4.7 Configuration Syntax ${aspnet-request-form:items=String[]:exclude=String[]:outputFormat=Enum :itemSeparator=Layout:valueSeparator=Layout :valuesOnly=Boolean} Parameters Rendering Options items - Form key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.2, and replaces the include -option. exclude - Form key name(s) to exclude from the output. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 . Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . valuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1 Remarks Use this layout renderer to log the ASP.NET Request Form collection. Examples In C# code: httpContext.Request.Form = new FormCollection(new Dictionary{ { \"id\",\"1\" }, { \"name\",\"Test Person\" }, { \"token\",\"86abe8fe-2237-4f87-81af-0a4e522b4140\" } }); Log all Form data from the Request in default Flat output format ${aspnet-request-form} Will print: \"id=1,name=Test Person,token=86abe8fe-2237-4f87-81af-0a4e522b4140\" Log all Form data from the Request in JSON output format ${aspnet-request-form:OutputFormat=JSON} Will print: [{\"id\":\"1\"},{\"name\":\"Test Person\"},{\"token\":\"86abe8fe-2237-4f87-81af-0a4e522b4140\"}] Log only the specified Form keys from the Request in default Flat output format ${aspnet-request-form:items=id,name} Will print: \"id=1,name=Test Person\" Log all Form data from the Request except for the specified keys in default Flat output format ${aspnet-request-form:Exclude=token} Will print: \"id=1,name=Test Person\" Log all Form data from the Request in Flat output format with each item separated by a new line ${aspnet-request-form:ItemSeparator=${newline}} Will print: \"id=1\\r\\nname=Test Person\\r\\ntoken=86abe8fe-2237-4f87-81af-0a4e522b4140\"","title":"AspNetRequest Form Layout Renderer"},{"location":"AspNetRequest-Form-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-form:items=String[]:exclude=String[]:outputFormat=Enum :itemSeparator=Layout:valueSeparator=Layout :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNetRequest-Form-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetRequest-Form-Layout-Renderer/#rendering-options","text":"items - Form key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.2, and replaces the include -option. exclude - Form key name(s) to exclude from the output. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 .","title":"Rendering Options"},{"location":"AspNetRequest-Form-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . valuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1","title":"Formatting options"},{"location":"AspNetRequest-Form-Layout-Renderer/#remarks","text":"Use this layout renderer to log the ASP.NET Request Form collection.","title":"Remarks"},{"location":"AspNetRequest-Form-Layout-Renderer/#examples","text":"In C# code: httpContext.Request.Form = new FormCollection(new Dictionary{ { \"id\",\"1\" }, { \"name\",\"Test Person\" }, { \"token\",\"86abe8fe-2237-4f87-81af-0a4e522b4140\" } });","title":"Examples"},{"location":"AspNetRequest-Form-Layout-Renderer/#log-all-form-data-from-the-request-in-default-flat-output-format","text":"${aspnet-request-form} Will print: \"id=1,name=Test Person,token=86abe8fe-2237-4f87-81af-0a4e522b4140\"","title":"Log all Form data from the Request in default Flat output format"},{"location":"AspNetRequest-Form-Layout-Renderer/#log-all-form-data-from-the-request-in-json-output-format","text":"${aspnet-request-form:OutputFormat=JSON} Will print: [{\"id\":\"1\"},{\"name\":\"Test Person\"},{\"token\":\"86abe8fe-2237-4f87-81af-0a4e522b4140\"}]","title":"Log all Form data from the Request in JSON output format"},{"location":"AspNetRequest-Form-Layout-Renderer/#log-only-the-specified-form-keys-from-the-request-in-default-flat-output-format","text":"${aspnet-request-form:items=id,name} Will print: \"id=1,name=Test Person\"","title":"Log only the specified Form keys from the Request in default Flat output format"},{"location":"AspNetRequest-Form-Layout-Renderer/#log-all-form-data-from-the-request-except-for-the-specified-keys-in-default-flat-output-format","text":"${aspnet-request-form:Exclude=token} Will print: \"id=1,name=Test Person\"","title":"Log all Form data from the Request except for the specified keys in default Flat output format"},{"location":"AspNetRequest-Form-Layout-Renderer/#log-all-form-data-from-the-request-in-flat-output-format-with-each-item-separated-by-a-new-line","text":"${aspnet-request-form:ItemSeparator=${newline}} Will print: \"id=1\\r\\nname=Test Person\\r\\ntoken=86abe8fe-2237-4f87-81af-0a4e522b4140\"","title":"Log all Form data from the Request in Flat output format with each item separated by a new line"},{"location":"AspNetRequest-Headers-Layout-Renderer/","text":"ASP.NET Request Headers key/value pairs. Platforms Supported: All Introduced in NLog.Web 4.9 and NLog.Web.AspNetCore 4.9 Configuration Syntax ${aspnet-request-headers:headerNames=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Parameters Rendering Options items - Header key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the headerNames -option. exclude - Header key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1 Remarks Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Request Headers collection. Examples In C# code: Request.Headers[\"key1\"] = \"value1\"; Request.Headers[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\"; Log single header in default Flat output format ${aspnet-request-headers:HeaderNames=key1} Will print: \"key1=value1\" Log multiple headers in default Flat output format ${aspnet-request-headers:HeaderNames=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\" Log single header ie in JSON output format ${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}] Log multiple headers in JSON output format ${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}] Log single header as JSON dictionary: ${aspnet-request-headers:HeaderNames=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"} Log single header in Flat output format as value only ${aspnet-request-headers:HeaderNames=key1:ValuesOnly=true} Will print: \"value1\" Log single header in JSON output format as value only ${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"] Log multiple headers in JSON output format as value only ${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"AspNetRequest Headers Layout Renderer"},{"location":"AspNetRequest-Headers-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-headers:headerNames=String[]:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNetRequest-Headers-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetRequest-Headers-Layout-Renderer/#rendering-options","text":"items - Header key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the headerNames -option. exclude - Header key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2","title":"Rendering Options"},{"location":"AspNetRequest-Headers-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1","title":"Formatting options"},{"location":"AspNetRequest-Headers-Layout-Renderer/#remarks","text":"Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Request Headers collection.","title":"Remarks"},{"location":"AspNetRequest-Headers-Layout-Renderer/#examples","text":"In C# code: Request.Headers[\"key1\"] = \"value1\"; Request.Headers[\"id\"] = \"d4b20a34-6231-4201-83a6-c72599e41164\";","title":"Examples"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-single-header-in-default-flat-output-format","text":"${aspnet-request-headers:HeaderNames=key1} Will print: \"key1=value1\"","title":"Log single header in default Flat output format"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-multiple-headers-in-default-flat-output-format","text":"${aspnet-request-headers:HeaderNames=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\"","title":"Log multiple headers in default Flat output format"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-single-header-ie-in-json-output-format","text":"${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}]","title":"Log single header ie in JSON output format"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-multiple-headers-in-json-output-format","text":"${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}]","title":"Log multiple headers in JSON output format"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-single-header-as-json-dictionary","text":"${aspnet-request-headers:HeaderNames=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"}","title":"Log single header as JSON dictionary:"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-single-header-in-flat-output-format-as-value-only","text":"${aspnet-request-headers:HeaderNames=key1:ValuesOnly=true} Will print: \"value1\"","title":"Log single header in Flat output format as value only"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-single-header-in-json-output-format-as-value-only","text":"${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"]","title":"Log single header in JSON output format as value only"},{"location":"AspNetRequest-Headers-Layout-Renderer/#log-multiple-headers-in-json-output-format-as-value-only","text":"${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"Log multiple headers in JSON output format as value only"},{"location":"AspNetRequest-Host-Layout-Renderer/","text":"ASP.NET Request DNS name of the remote client Platforms Supported: All ( ASP.NET Core + ASP.NET ) Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-request-host} Remarks ASP.NET Core returns the Host -Header ASP.NET returns the REMOTE_ADDR -ServerVariable See also AspNet Request IP Layout Renderer","title":"AspNetRequest Host Layout Renderer"},{"location":"AspNetRequest-Host-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-host}","title":"Configuration Syntax"},{"location":"AspNetRequest-Host-Layout-Renderer/#remarks","text":"ASP.NET Core returns the Host -Header ASP.NET returns the REMOTE_ADDR -ServerVariable See also AspNet Request IP Layout Renderer","title":"Remarks"},{"location":"AspNetRequest-Method-Layout-Renderer/","text":"ASP.NET HTTP Method. GET/POST/PUT etc. Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-request-method} Remarks Use this layout renderer to insert the HTTP Request Method.","title":"AspNetRequest Method Layout Renderer"},{"location":"AspNetRequest-Method-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-method}","title":"Configuration Syntax"},{"location":"AspNetRequest-Method-Layout-Renderer/#remarks","text":"Use this layout renderer to insert the HTTP Request Method.","title":"Remarks"},{"location":"AspNetRequest-QueryString-Layout-Renderer/","text":"ASP.NET Request Query String key/value pairs. Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-request-querystring:items=String:outputFormat:Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Parameters Rendering Options items - Query String key(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the queryStringKeys -option. With NLog.Web / NLog.Web.AspNetCore v4.3.1 then all key/value pairs will be rendered, when not specified. exclude - Query String key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Introduced with NLog.Web v5.2.2 Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 ValuesOnly - Only render the values of the key/value pairs. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v4.6 LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1 Remarks Use this layout renderer to insert the value of the specified query string parameters stored in the ASP.NET Query String collection. Examples In C# code: Response.Redirect(\"myPage.aspx?key1=value1&id=d4b20a34-6231-4201-83a6-c72599e41164\"); Log single query string key/value pair in default Flat output format ${aspnet-request-querystring:items=key1} Will print: \"key1=value1\" Log multiple query string key/value pairs in default Flat output format ${aspnet-request-querystring:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\" Log single query string key/value pair in JSON output format ${aspnet-request-querystring:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}] Log multiple query string key/value pairs in JSON output format ${aspnet-request-querystring:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}] Log single query string key/value pair as JSON dictionary: ${aspnet-request-querystring:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"} Log single query string key/value pair in Flat output format as value only ${aspnet-request-querystring:items=key1:ValuesOnly=true} Will print: \"value1\" Log single query string key/value pair in JSON output format as value only ${aspnet-request-querystring:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"] Log multiple query string key/value pairs in JSON output format as value only ${aspnet-request-querystring:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"AspNetRequest QueryString Layout Renderer"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-querystring:items=String:outputFormat:Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#rendering-options","text":"items - Query String key(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the queryStringKeys -option. With NLog.Web / NLog.Web.AspNetCore v4.3.1 then all key/value pairs will be rendered, when not specified. exclude - Query String key names to be excluded. A list of keys can be passed as comma separated values, e.g.: Key1,Key2 Introduced with NLog.Web v5.2.2","title":"Rendering Options"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array (Introduced with NLog 5.0, replaces now obsolete Json ) JsonDictionary - Key-value-pair as JSON-dictionary. (Introduced with NLog 5.0, replaces now obsolete singleAsArray ) itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5 ValuesOnly - Only render the values of the key/value pairs. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v4.6 LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1","title":"Formatting options"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#remarks","text":"Use this layout renderer to insert the value of the specified query string parameters stored in the ASP.NET Query String collection.","title":"Remarks"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#examples","text":"In C# code: Response.Redirect(\"myPage.aspx?key1=value1&id=d4b20a34-6231-4201-83a6-c72599e41164\");","title":"Examples"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-single-query-string-keyvalue-pair-in-default-flat-output-format","text":"${aspnet-request-querystring:items=key1} Will print: \"key1=value1\"","title":"Log single query string key/value pair in default Flat output format"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-multiple-query-string-keyvalue-pairs-in-default-flat-output-format","text":"${aspnet-request-querystring:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\"","title":"Log multiple query string key/value pairs in default Flat output format"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-single-query-string-keyvalue-pair-in-json-output-format","text":"${aspnet-request-querystring:items=key1:OutputFormat=JSON} Will print: [{\"key1\":\"value1\"}]","title":"Log single query string key/value pair in JSON output format"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-multiple-query-string-keyvalue-pairs-in-json-output-format","text":"${aspnet-request-querystring:items=key1,id:OutputFormat=JSON} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}]","title":"Log multiple query string key/value pairs in JSON output format"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-single-query-string-keyvalue-pair-as-json-dictionary","text":"${aspnet-request-querystring:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"}","title":"Log single query string key/value pair as JSON dictionary:"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-single-query-string-keyvalue-pair-in-flat-output-format-as-value-only","text":"${aspnet-request-querystring:items=key1:ValuesOnly=true} Will print: \"value1\"","title":"Log single query string key/value pair in Flat output format as value only"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-single-query-string-keyvalue-pair-in-json-output-format-as-value-only","text":"${aspnet-request-querystring:items=key1:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\"]","title":"Log single query string key/value pair in JSON output format as value only"},{"location":"AspNetRequest-QueryString-Layout-Renderer/#log-multiple-query-string-keyvalue-pairs-in-json-output-format-as-value-only","text":"${aspnet-request-querystring:items=key1,id:OutputFormat=JSON:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"Log multiple query string key/value pairs in JSON output format as value only"},{"location":"AspNetRequest-Referrer-Renderer/","text":"ASP.NET Request HTTP URL Referrer. Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-request-referrer}","title":"AspNetRequest Referrer Renderer"},{"location":"AspNetRequest-Referrer-Renderer/#configuration-syntax","text":"${aspnet-request-referrer}","title":"Configuration Syntax"},{"location":"AspNetRequest-RequestAborted-Layout-Renderer/","text":" Notice request-aborted can be a symptom of slow performance, which can be relevant to investigate if app-performance is important (and not to be swept under the carpet) Introduced in NLog.Web and NLog.Web.AspNetCore 6.3.0","title":"AspNetRequest RequestAborted Layout Renderer"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/","text":"ASP.NET Request RouteParameters key/value pairs. Platforms Supported: All Introduced in NLog.Web 5.0 and NLog.Web.AspNetCore 5.0 Configuration Syntax ${aspnet-request-routeparameters:items=String:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean} Parameters Rendering Options items - RouteParameter key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the RouteParameterKeys -option. Formatting options outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1 Remarks Use this layout renderer to log the value of the specified route-parameter(s) stored in the ASP.NET GetRouteData() Values collection. Examples Log single route-parameter in default Flat output format ${aspnet-request-routeparameters:Items=key1} Will print: \"key1=value1\" Log multiple route-parameters in default Flat output format ${aspnet-request-routeparameters:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\" Log single route-parameter in JSON output format ${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray} Will print: [{\"key1\":\"value1\"}] Log multiple route-parameters in JSON output format ${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}] Log single route-parameter as JSON dictionary: ${aspnet-request-routeparameters:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"} Log single route-parameter in Flat output format as value only ${aspnet-request-routeparameters:items=key1:ValuesOnly=true} Will print: \"value1\" Log single route-parameter in JSON output format as value only ${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray:ValuesOnly=true} Will print: [\"value1\"] Log multiple route-parameters in JSON output format as value only ${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"AspNetRequest RouteParameters Layout Renderer"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-routeparameters:items=String:outputFormat=Enum :itemSeparator=String:valueSeparator=String :valuesOnly=Boolean}","title":"Configuration Syntax"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#rendering-options","text":"items - RouteParameter key name(s). A list of keys can be passed as comma separated values, e.g.: Key1,Key2 (Not specified means all) Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the RouteParameterKeys -option.","title":"Rendering Options"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#formatting-options","text":"outputFormat - Renders as flat string or as JSON. Default: Flat . Flat - Key-value-pair as standard string JsonArray - Key-value-pair in JSON-array JsonDictionary - Key-value-pair as JSON-dictionary itemSeparator - Separator between items. Default: , . Only applies when OutputFormat is Flat . valueSeparator - Separator between value and key. Default: = . Only applies when OutputFormat is Flat . ValuesOnly - Only render the values of the key/value pairs. Default: false . LowerCaseKeys - Convert Keys to lowercase. Default: false . Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1","title":"Formatting options"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#remarks","text":"Use this layout renderer to log the value of the specified route-parameter(s) stored in the ASP.NET GetRouteData() Values collection.","title":"Remarks"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#examples","text":"","title":"Examples"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-single-route-parameter-in-default-flat-output-format","text":"${aspnet-request-routeparameters:Items=key1} Will print: \"key1=value1\"","title":"Log single route-parameter in default Flat output format"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-multiple-route-parameters-in-default-flat-output-format","text":"${aspnet-request-routeparameters:items=key1,id} Will print: \"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164\"","title":"Log multiple route-parameters in default Flat output format"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-single-route-parameter-in-json-output-format","text":"${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray} Will print: [{\"key1\":\"value1\"}]","title":"Log single route-parameter in JSON output format"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-multiple-route-parameters-in-json-output-format","text":"${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray} Will print: [{\"key1\":\"value1\",\"id\":\"d4b20a34-6231-4201-83a6-c72599e41164\"}]","title":"Log multiple route-parameters in JSON output format"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-single-route-parameter-as-json-dictionary","text":"${aspnet-request-routeparameters:items=key1:OutputFormat=JsonDictionary} Will print: {\"key1\":\"value1\"}","title":"Log single route-parameter as JSON dictionary:"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-single-route-parameter-in-flat-output-format-as-value-only","text":"${aspnet-request-routeparameters:items=key1:ValuesOnly=true} Will print: \"value1\"","title":"Log single route-parameter in Flat output format as value only"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-single-route-parameter-in-json-output-format-as-value-only","text":"${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray:ValuesOnly=true} Will print: [\"value1\"]","title":"Log single route-parameter in JSON output format as value only"},{"location":"AspNetRequest-RouteParameters-Layout-Renderer/#log-multiple-route-parameters-in-json-output-format-as-value-only","text":"${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray:ValuesOnly=true} Will print: [\"value1\",\"d4b20a34-6231-4201-83a6-c72599e41164\"]","title":"Log multiple route-parameters in JSON output format as value only"},{"location":"AspNetRequest-Url-Layout-Renderer/","text":"ASP.NET Request URL Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-request-url:IncludeHost=boolean:IncludePort=boolean:IncludeQueryString=boolean:IncludeScheme=boolean} Parameters Properties - Controls what parts of the Url to output. Default = Scheme, Host, Path Introduced with NLog v5.1.1 Property Enum Values: Scheme Host Port Path Query IncludeHost - Include the host name? (Assigns Properties |= Host ). Default is true . IncludePort - Include the port number? (Assigns Properties |= Port ). Default is false . IncludeQueryString - include the querystring. (Assigns Properties |= Query ). Default is false . IncludeScheme - Includes the sheme? (Ex. http:// or https:// ) (Assigns Properties |= Scheme ). Default is true . Introduced in NLog.Web.AspNetCore v4.4.1 and NLog.Web v4.5.1. IncludePath - Include the path? (Assigns Properties |= Path ). Default is true . Introduced in NLog.Web.AspNetCore v5.0 and NLog.Web v5.0. UseRawTarget - Extract the path from IHttpRequestFeature.RawTarget? Default is false . Introduced in NLog.Web.AspNetCore v4.9.2 (Not supported for NLog.Web) Examples ${aspnet-request-url:IncludeQueryString=true} - produces http://www.exmaple.com/?t=1 ${aspnet-request-url:IncludeQueryString=false} - produces http://www.exmaple.com/ ${aspnet-request-url:IncludePort=true} - produces http://www.exmaple.com:80/ ${aspnet-request-url:IncludePort=false} - produces http://www.exmaple.com/ ${aspnet-request-url:IncludePort=true:IncludeQueryString=true} - produces http://www.exmaple.com:80/?t=1 ${aspnet-request-url:IncludeScheme=false} - produces www.exmaple.com","title":"AspNetRequest Url Layout Renderer"},{"location":"AspNetRequest-Url-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-url:IncludeHost=boolean:IncludePort=boolean:IncludeQueryString=boolean:IncludeScheme=boolean}","title":"Configuration Syntax"},{"location":"AspNetRequest-Url-Layout-Renderer/#parameters","text":"Properties - Controls what parts of the Url to output. Default = Scheme, Host, Path Introduced with NLog v5.1.1 Property Enum Values: Scheme Host Port Path Query IncludeHost - Include the host name? (Assigns Properties |= Host ). Default is true . IncludePort - Include the port number? (Assigns Properties |= Port ). Default is false . IncludeQueryString - include the querystring. (Assigns Properties |= Query ). Default is false . IncludeScheme - Includes the sheme? (Ex. http:// or https:// ) (Assigns Properties |= Scheme ). Default is true . Introduced in NLog.Web.AspNetCore v4.4.1 and NLog.Web v4.5.1. IncludePath - Include the path? (Assigns Properties |= Path ). Default is true . Introduced in NLog.Web.AspNetCore v5.0 and NLog.Web v5.0. UseRawTarget - Extract the path from IHttpRequestFeature.RawTarget? Default is false . Introduced in NLog.Web.AspNetCore v4.9.2 (Not supported for NLog.Web)","title":"Parameters"},{"location":"AspNetRequest-Url-Layout-Renderer/#examples","text":"${aspnet-request-url:IncludeQueryString=true} - produces http://www.exmaple.com/?t=1 ${aspnet-request-url:IncludeQueryString=false} - produces http://www.exmaple.com/ ${aspnet-request-url:IncludePort=true} - produces http://www.exmaple.com:80/ ${aspnet-request-url:IncludePort=false} - produces http://www.exmaple.com/ ${aspnet-request-url:IncludePort=true:IncludeQueryString=true} - produces http://www.exmaple.com:80/?t=1 ${aspnet-request-url:IncludeScheme=false} - produces www.exmaple.com","title":"Examples"},{"location":"AspNetRequest-UserAgent-Layout-Renderer/","text":"Renders the ASP.NET UserAgent from HTTP Request. Platforms Supported: All Introduced in NLog.Web 4.3 Configuration Syntax ${aspnet-request-useragent}","title":"AspNetRequest UserAgent Layout Renderer"},{"location":"AspNetRequest-UserAgent-Layout-Renderer/#configuration-syntax","text":"${aspnet-request-useragent}","title":"Configuration Syntax"},{"location":"AspNetRequest-layout-renderer/","text":"ASP.NET Request variable. Platforms Supported: All ASP.NET Core This layout renderer is broken down to separate layout renders who are more ASP.NET Core compatible / future proof: ${aspnet-HttpContext-Item} - ASP.NET HttpContext Item Value. ${aspnet-Request-Cookie} - ASP.NET Request cookie content. ${aspnet-Request-Host} - ASP.NET Request host. ${aspnet-Request-Ip} - ASP.NET Request Client IP address ${aspnet-Request-Method} - ASP.NET Request method (GET, POST etc). ${aspnet-Request-QueryString} - ASP.NET Request querystring. ${aspnet-Request-Referrer} - ASP.NET Request referrer. ${aspnet-Request-UserAgent} - ASP.NET Request useragent. ${aspnet-Request-Url} - ASP.NET Request URL. ${aspnet-Request-Headers} - ASP.NET Request Headers. ${aspnet-Request-ServerVariable} - ASP.NET Server Variable. ${aspnet-User-Identity} - ASP.NET User Identity (Similar to AUTH_USER / REMOTE_USER / LOGON_USER ) And there are many more NLog LayoutRenderers to choose from Configuration Syntax ${aspnet-request:cookie=String:serverVariable=String:queryString=String :item=String:form=String:header=String} Parameters Rendering Options cookie - Cookie to be rendered. header - Request header to be rendered. Introduced in NLog.Web 4.2 serverVariable - ServerVariables item to be rendered. See for possible options: msdn . Not supported on ASP.NET Core until NLog.Web.AspNetCore v5.1 queryString - QueryString variable to be rendered. item - HttpConterxt Item name to be rendered. form - Form variable to be rendered. Note: The Form property is populated when the HTTP request Content-Type value is either \"application/x-www-form-urlencoded\" or \"multipart/form-data\". (see msdn ) Remarks Use this layout renderer to insert the value of the specified parameter of the ASP.NET Request object. This renderer requires the NLog.Web package. Examples Full URL Full URL without domain, eg default.aspx?id=512 ${aspnet-request:serverVariable=HTTP_URL}${aspnet-request:queryString} Referer URL doing the request. Including schema (e.g https:// ) and querystring ${aspnet-request:header=Referer} Content-Type Content-Type like application/json; charset=UTF-8 ${aspnet-request:header=Content-Type} Method Method like PUT, POST, GET etc ${aspnet-request:serverVariable=REQUEST_METHOD} User agent user agent, like Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 ${aspnet-request:serverVariable=HTTP_USER_AGENT}","title":"AspNetRequest layout renderer"},{"location":"AspNetRequest-layout-renderer/#aspnet-core","text":"This layout renderer is broken down to separate layout renders who are more ASP.NET Core compatible / future proof: ${aspnet-HttpContext-Item} - ASP.NET HttpContext Item Value. ${aspnet-Request-Cookie} - ASP.NET Request cookie content. ${aspnet-Request-Host} - ASP.NET Request host. ${aspnet-Request-Ip} - ASP.NET Request Client IP address ${aspnet-Request-Method} - ASP.NET Request method (GET, POST etc). ${aspnet-Request-QueryString} - ASP.NET Request querystring. ${aspnet-Request-Referrer} - ASP.NET Request referrer. ${aspnet-Request-UserAgent} - ASP.NET Request useragent. ${aspnet-Request-Url} - ASP.NET Request URL. ${aspnet-Request-Headers} - ASP.NET Request Headers. ${aspnet-Request-ServerVariable} - ASP.NET Server Variable. ${aspnet-User-Identity} - ASP.NET User Identity (Similar to AUTH_USER / REMOTE_USER / LOGON_USER ) And there are many more NLog LayoutRenderers to choose from","title":"ASP.NET Core"},{"location":"AspNetRequest-layout-renderer/#configuration-syntax","text":"${aspnet-request:cookie=String:serverVariable=String:queryString=String :item=String:form=String:header=String}","title":"Configuration Syntax"},{"location":"AspNetRequest-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetRequest-layout-renderer/#rendering-options","text":"cookie - Cookie to be rendered. header - Request header to be rendered. Introduced in NLog.Web 4.2 serverVariable - ServerVariables item to be rendered. See for possible options: msdn . Not supported on ASP.NET Core until NLog.Web.AspNetCore v5.1 queryString - QueryString variable to be rendered. item - HttpConterxt Item name to be rendered. form - Form variable to be rendered. Note: The Form property is populated when the HTTP request Content-Type value is either \"application/x-www-form-urlencoded\" or \"multipart/form-data\". (see msdn )","title":"Rendering Options"},{"location":"AspNetRequest-layout-renderer/#remarks","text":"Use this layout renderer to insert the value of the specified parameter of the ASP.NET Request object. This renderer requires the NLog.Web package.","title":"Remarks"},{"location":"AspNetRequest-layout-renderer/#examples","text":"","title":"Examples"},{"location":"AspNetRequest-layout-renderer/#full-url","text":"Full URL without domain, eg default.aspx?id=512 ${aspnet-request:serverVariable=HTTP_URL}${aspnet-request:queryString}","title":"Full URL"},{"location":"AspNetRequest-layout-renderer/#referer","text":"URL doing the request. Including schema (e.g https:// ) and querystring ${aspnet-request:header=Referer}","title":"Referer"},{"location":"AspNetRequest-layout-renderer/#content-type","text":"Content-Type like application/json; charset=UTF-8 ${aspnet-request:header=Content-Type}","title":"Content-Type"},{"location":"AspNetRequest-layout-renderer/#method","text":"Method like PUT, POST, GET etc ${aspnet-request:serverVariable=REQUEST_METHOD}","title":"Method"},{"location":"AspNetRequest-layout-renderer/#user-agent","text":"user agent, like Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 ${aspnet-request:serverVariable=HTTP_USER_AGENT}","title":"User agent"},{"location":"AspNetResponse-StatusCode-Layout-Renderer/","text":"ASP.NET Response Status Code. Platforms Supported: All Introduced in NLog.Web 4.9 Configuration Syntax ${aspnet-response-statuscode:format=d} Parameters Format - Enumeration Format string specifier. Ex. G for string-value and D for integer-value. Default: D Introduced with NLog.Web 5.2.2","title":"AspNetResponse StatusCode Layout Renderer"},{"location":"AspNetResponse-StatusCode-Layout-Renderer/#configuration-syntax","text":"${aspnet-response-statuscode:format=d}","title":"Configuration Syntax"},{"location":"AspNetResponse-StatusCode-Layout-Renderer/#parameters","text":"Format - Enumeration Format string specifier. Ex. G for string-value and D for integer-value. Default: D Introduced with NLog.Web 5.2.2","title":"Parameters"},{"location":"AspNetSession-Layout-Renderer/","text":"ASP.NET Item Variable from Session Dictionary Platforms Supported: All Configuration Syntax ${aspnet-session:item=String:objectpath=String:format=String:ValueType=String|Int32} Parameters Rendering Options item - Key for lookup in Session-dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties -option ValueType - Only for ASP.NET Core. Type of the value. String (default) or Int32 . Introduced in NLog.Web.AspNetCore 4.9.3. Please note: you won't get an error when retrieving a int (set with Session.SetInt32(..) ) with valuetype string , but an incorrect value. We can't unfortunately recognize the type of the value inside the ASP.NET Core session. See also Configure session state Examples Log the username in the session. In the C# code: Session[\"username\"] = \"JohnDoe\"; Config: Will print \"JohnDoe\" ObjectPath In the C# code: Session[\"user\"] = new UserInfo { Name= \"JohnDoe\", Id = 100}; Config: Will print nested property-value \"JohnDoe\"","title":"AspNetSession Layout Renderer"},{"location":"AspNetSession-Layout-Renderer/#configuration-syntax","text":"${aspnet-session:item=String:objectpath=String:format=String:ValueType=String|Int32}","title":"Configuration Syntax"},{"location":"AspNetSession-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"AspNetSession-Layout-Renderer/#rendering-options","text":"item - Key for lookup in Session-dictionary (Required) Introduced with NLog.Web v5.1, and replaces the Variable -option format - Format-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 culture - Culture-specifier for converting the value as string (Optional) Introduced with NLog.Web v5.0 objectpath - Property path if the value is an object, also supports nested properties (Optional). Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties -option ValueType - Only for ASP.NET Core. Type of the value. String (default) or Int32 . Introduced in NLog.Web.AspNetCore 4.9.3. Please note: you won't get an error when retrieving a int (set with Session.SetInt32(..) ) with valuetype string , but an incorrect value. We can't unfortunately recognize the type of the value inside the ASP.NET Core session. See also Configure session state","title":"Rendering Options"},{"location":"AspNetSession-Layout-Renderer/#examples","text":"Log the username in the session. In the C# code: Session[\"username\"] = \"JohnDoe\"; Config: Will print \"JohnDoe\"","title":"Examples"},{"location":"AspNetSession-Layout-Renderer/#objectpath","text":"In the C# code: Session[\"user\"] = new UserInfo { Name= \"JohnDoe\", Id = 100}; Config: Will print nested property-value \"JohnDoe\"","title":"ObjectPath"},{"location":"AspNetSessionId-Layout-Renderer/","text":"ASP.NET Session ID. Platforms Supported: All Configuration Syntax ${aspnet-sessionid} Enable sessions in ASP.NET Core Add line to ConfigureServices() in Startup.cs public void ConfigureServices(IServiceCollection services) { ... services.AddMvc(); services.AddSession(); // After AddMvc() services.AddHttpContextAccessor(); ... } Add line to Configure() in Startup.cs public void Configure(IApplicationBuilder app, IHostingEnvironment env) { ... app.UseSession(); // Before UseMvc() app.UseMvc(); ... } See also Configure session state","title":"AspNetSessionId Layout Renderer"},{"location":"AspNetSessionId-Layout-Renderer/#configuration-syntax","text":"${aspnet-sessionid}","title":"Configuration Syntax"},{"location":"AspNetSessionId-Layout-Renderer/#enable-sessions-in-aspnet-core","text":"Add line to ConfigureServices() in Startup.cs public void ConfigureServices(IServiceCollection services) { ... services.AddMvc(); services.AddSession(); // After AddMvc() services.AddHttpContextAccessor(); ... } Add line to Configure() in Startup.cs public void Configure(IApplicationBuilder app, IHostingEnvironment env) { ... app.UseSession(); // Before UseMvc() app.UseMvc(); ... } See also Configure session state","title":"Enable sessions in ASP.NET Core"},{"location":"AspNetTrace-target/","text":"Writes log messages to the ASP.NET Trace using TraceContext from HttpContext. Platforms Supported: Limited - .NET Framework only and requires nuget-package NLog.Web Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target Layout Options layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} Remarks Log entries can then be viewed by navigating to http://server/path/Trace.axd. AspNetTrace uses the HttpContext.Current . Therefore async/buffered writing does not works for AspNetTrace due to different thread. Examples In order to use this target, put the following code in the configuration file such as Web.nlog or NLog.config: You can also configure the target programmatically, by putting the code in Application_Start event handler or similar: using System; using System.Web; using NLog; using NLog.Web.Targets; namespace SomeWebApplication { public class Global : System.Web.HttpApplication { // // this event handler is executed at the very start of the web application // so this is a good place to configure targets programmatically // // alternative you could place this code in a static type constructor // protected void Application_Start(Object sender, EventArgs e) { NLog.Web.Targets.AspNetTraceTarget target = new NLog.Web.Targets.AspNetTraceTarget() { Name = \"AspNetTrace\" }; target.Layout = \"${logger} ${message}\"; NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; } } }","title":"AspNetTrace target"},{"location":"AspNetTrace-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"AspNetTrace-target/#parameters","text":"","title":"Parameters"},{"location":"AspNetTrace-target/#general-options","text":"name - Name of the target","title":"General Options"},{"location":"AspNetTrace-target/#layout-options","text":"layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}","title":"Layout Options"},{"location":"AspNetTrace-target/#remarks","text":"Log entries can then be viewed by navigating to http://server/path/Trace.axd. AspNetTrace uses the HttpContext.Current . Therefore async/buffered writing does not works for AspNetTrace due to different thread.","title":"Remarks"},{"location":"AspNetTrace-target/#examples","text":"In order to use this target, put the following code in the configuration file such as Web.nlog or NLog.config: You can also configure the target programmatically, by putting the code in Application_Start event handler or similar: using System; using System.Web; using NLog; using NLog.Web.Targets; namespace SomeWebApplication { public class Global : System.Web.HttpApplication { // // this event handler is executed at the very start of the web application // so this is a good place to configure targets programmatically // // alternative you could place this code in a static type constructor // protected void Application_Start(Object sender, EventArgs e) { NLog.Web.Targets.AspNetTraceTarget target = new NLog.Web.Targets.AspNetTraceTarget() { Name = \"AspNetTrace\" }; target.Layout = \"${logger} ${message}\"; NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; } } }","title":"Examples"},{"location":"AspNetTraceIdentifier-Layout-Renderer/","text":"ASP.NET Trace Identifier Platforms Supported: All (Supported in ASP.NET Core and ASP.NET ) Introduced in NLog.Web.AspNetCore ver. 4.3.1 and NLog.Web ver. 4.7.1 Configuration Syntax ${aspnet-TraceIdentifier:ignoreActivityId=boolean} Options: ignoreActivityId : Only ASP.NET Core. Use HttpContext.TraceIdentifier instead of System.Diagnostics.Activity.Current.Id Notes Which TraceIdentifier is used? ASP.NET Core 3: by default System.Diagnostics.Activity.Current.Id . ASP.NET Core 1+2: HttpContext.TraceIdentifier ASP.NET: HttpWorkerRequest.RequestTraceIdentifier . Requires IIS ETW feature enabled, see Microsoft docs Alternative could use ${activityid} together with CorrelationManager.ActivityId . See code","title":"AspNetTraceIdentifier Layout Renderer"},{"location":"AspNetTraceIdentifier-Layout-Renderer/#configuration-syntax","text":"${aspnet-TraceIdentifier:ignoreActivityId=boolean}","title":"Configuration Syntax"},{"location":"AspNetTraceIdentifier-Layout-Renderer/#options","text":"ignoreActivityId : Only ASP.NET Core. Use HttpContext.TraceIdentifier instead of System.Diagnostics.Activity.Current.Id","title":"Options:"},{"location":"AspNetTraceIdentifier-Layout-Renderer/#notes","text":"","title":"Notes"},{"location":"AspNetTraceIdentifier-Layout-Renderer/#which-traceidentifier-is-used","text":"ASP.NET Core 3: by default System.Diagnostics.Activity.Current.Id . ASP.NET Core 1+2: HttpContext.TraceIdentifier ASP.NET: HttpWorkerRequest.RequestTraceIdentifier . Requires IIS ETW feature enabled, see Microsoft docs Alternative could use ${activityid} together with CorrelationManager.ActivityId . See code","title":"Which TraceIdentifier is used?"},{"location":"AspNetUserAuthType-Layout-Renderer/","text":"ASP.NET HttpContext User.Identity.AuthenticationType Platforms Supported: All Configuration Syntax ${aspnet-user-authtype}","title":"AspNetUserAuthType Layout Renderer"},{"location":"AspNetUserAuthType-Layout-Renderer/#configuration-syntax","text":"${aspnet-user-authtype}","title":"Configuration Syntax"},{"location":"AspNetUserIdentity-Layout-Renderer/","text":"ASP.NET HttpContext User.Identity.Name Platforms Supported: All Similar to AUTH_USER / REMOTE_USER / LOGON_USER in Server Variables. Configuration Syntax ${aspnet-user-identity} ASP.NET Core Details Adding Identity in ASP.NET Core 2.2 using IServiceCollection in ConfigureServices : services.AddIdentity() .AddRoles() .AddDefaultTokenProviders() .AddDefaultUI(); See also Introduction to Identity on ASP.NET Core (Configuring IdentityOptions ) User Identity Claims For additional details about the user identity, then one can also use ${aspnet-user-claim}","title":"AspNetUserIdentity Layout Renderer"},{"location":"AspNetUserIdentity-Layout-Renderer/#configuration-syntax","text":"${aspnet-user-identity}","title":"Configuration Syntax"},{"location":"AspNetUserIdentity-Layout-Renderer/#aspnet-core-details","text":"Adding Identity in ASP.NET Core 2.2 using IServiceCollection in ConfigureServices : services.AddIdentity() .AddRoles() .AddDefaultTokenProviders() .AddDefaultUI(); See also Introduction to Identity on ASP.NET Core (Configuring IdentityOptions )","title":"ASP.NET Core Details"},{"location":"AspNetUserIdentity-Layout-Renderer/#user-identity-claims","text":"For additional details about the user identity, then one can also use ${aspnet-user-claim}","title":"User Identity Claims"},{"location":"AspRequest-layout-renderer/","text":"Moved to AspNetRequest Layout Renderer","title":"AspRequest layout renderer"},{"location":"AspResponse-target/","text":"Outputs log messages through the ASP Response object. Supported in .NET and Mono Configuration Syntax Read more about using the configuration file . Parameters General Options name - Name of the target Layout Options addComments - Indicates whether to add comments around all written texts. Boolean layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} Examples This target is usable when using classic ASP (not ASP.NET). In order to use this target, put the following code in the configuration file which is loaded into the web server process: ","title":"AspResponse target"},{"location":"AspResponse-target/#configuration-syntax","text":" Read more about using the configuration file .","title":"Configuration Syntax"},{"location":"AspResponse-target/#parameters","text":"","title":"Parameters"},{"location":"AspResponse-target/#general-options","text":"name - Name of the target","title":"General Options"},{"location":"AspResponse-target/#layout-options","text":"addComments - Indicates whether to add comments around all written texts. Boolean layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}","title":"Layout Options"},{"location":"AspResponse-target/#examples","text":"This target is usable when using classic ASP (not ASP.NET). In order to use this target, put the following code in the configuration file which is loaded into the web server process: ","title":"Examples"},{"location":"AspSession-layout-renderer/","text":"ASP Session variable. Supported in .NET and Mono Configuration Syntax ${asp-session:variable=String} Parameters Rendering Options variable - Session variable name. Required.","title":"AspSession layout renderer"},{"location":"AspSession-layout-renderer/#configuration-syntax","text":"${asp-session:variable=String}","title":"Configuration Syntax"},{"location":"AspSession-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"AspSession-layout-renderer/#rendering-options","text":"variable - Session variable name. Required.","title":"Rendering Options"},{"location":"AssemblyVersion-Layout-Renderer/","text":"Renders assembly version information from the entry assembly or a named assembly. Platforms Supported: All Introduced for ASP.NET / ASP.NET Core in NLog.Web 4.5.0 / NLog.Web.AspNetCore 4.4.0. Configuration Syntax ${assembly-version:name=string:type=Enum:format=string} Parameters Name - Display name of the assembly to retrieve a version from, as determined by its FullName property. The assembly will be loaded if needed. If not specified, will use the entry assembly (this did not function correctly for .NET Core until NLog.Web.AspNetCore 4.6). Introduced in NLog 4.3.7. Type - Type of the assembly version value to retrieve. Default: Assembly . Introduced with NLog v4.5. Introduced for ASP.NET with NLog.Web / NLog.Web.AspNetCore v4.6. Possible enum values: * Assembly - Assembly version. Value for AssemblyVersion attribute. Note: UWP earlier than .NET Standard 1.5 uses value for `ApplicationVersion` File - File version. Value for AssemblyFileVersion attribute. Notes: - UWP earlier than .NET Standard 1.5 uses Assembly instead unless a value is given for the name parameter Informational - Product Version extracted from AssemblyInformationalVersion attribute. Notes: - UWP earlier than .NET Standard 1.5 uses Assembly instead unless a value is given for the name parameter Format - Custom format of the assembly version output. Default: major.minor.build.revision Supported placeholders are 'major', 'minor', 'build' and 'revision'. The default .NET template for version numbers is 'major.minor.build.revision'. See https://docs.microsoft.com/en-gb/dotnet/api/system.version?view=netframework-4.7.2#remarks for details. Introduced with NLog 4.6 Default - Custom value to output when assembly version cannot be found, is empty or matches 0.0.0.0 Introduced with NLog 5.0.2 Remarks As this layout renderer uses reflection and version information is unlikely to change during application execution, it is recommended to use it in conjunction with the CachedLayoutRendererWrapper. The entry assembly can't be found in some cases e.g. ASP.NET, unit tests, etc. Examples Retrieve assembly version for entry assembly: ${assembly-version} Retrieve assembly version for assembly name NLogAutloadExtension : ${assembly-version:NLogAutloadExtension} Retrieve file version for entry assembly: ${assembly-version:type=File} Retrieve informational version for assembly name NLogAutloadExtension : ${assembly-version:name=NLogAutloadExtension:type=Informational}","title":"AssemblyVersion Layout Renderer"},{"location":"AssemblyVersion-Layout-Renderer/#configuration-syntax","text":"${assembly-version:name=string:type=Enum:format=string}","title":"Configuration Syntax"},{"location":"AssemblyVersion-Layout-Renderer/#parameters","text":"Name - Display name of the assembly to retrieve a version from, as determined by its FullName property. The assembly will be loaded if needed. If not specified, will use the entry assembly (this did not function correctly for .NET Core until NLog.Web.AspNetCore 4.6). Introduced in NLog 4.3.7. Type - Type of the assembly version value to retrieve. Default: Assembly . Introduced with NLog v4.5. Introduced for ASP.NET with NLog.Web / NLog.Web.AspNetCore v4.6. Possible enum values: * Assembly - Assembly version. Value for AssemblyVersion attribute. Note: UWP earlier than .NET Standard 1.5 uses value for `ApplicationVersion` File - File version. Value for AssemblyFileVersion attribute. Notes: - UWP earlier than .NET Standard 1.5 uses Assembly instead unless a value is given for the name parameter Informational - Product Version extracted from AssemblyInformationalVersion attribute. Notes: - UWP earlier than .NET Standard 1.5 uses Assembly instead unless a value is given for the name parameter Format - Custom format of the assembly version output. Default: major.minor.build.revision Supported placeholders are 'major', 'minor', 'build' and 'revision'. The default .NET template for version numbers is 'major.minor.build.revision'. See https://docs.microsoft.com/en-gb/dotnet/api/system.version?view=netframework-4.7.2#remarks for details. Introduced with NLog 4.6 Default - Custom value to output when assembly version cannot be found, is empty or matches 0.0.0.0 Introduced with NLog 5.0.2","title":"Parameters"},{"location":"AssemblyVersion-Layout-Renderer/#remarks","text":"As this layout renderer uses reflection and version information is unlikely to change during application execution, it is recommended to use it in conjunction with the CachedLayoutRendererWrapper. The entry assembly can't be found in some cases e.g. ASP.NET, unit tests, etc.","title":"Remarks"},{"location":"AssemblyVersion-Layout-Renderer/#examples","text":"Retrieve assembly version for entry assembly: ${assembly-version} Retrieve assembly version for assembly name NLogAutloadExtension : ${assembly-version:NLogAutloadExtension} Retrieve file version for entry assembly: ${assembly-version:type=File} Retrieve informational version for assembly name NLogAutloadExtension : ${assembly-version:name=NLogAutloadExtension:type=Informational}","title":"Examples"},{"location":"AsyncWrapper-target/","text":"Enables asynchronous logging, so the application-thread will have minimal logging overhead, and only needs to capture thread-context if needed (Ex. ${threadid} ). Activates batch-writing of log events for even better performance. Platforms Supported: All Configuration Syntax Parameters General Options name - Name of the target. Buffering Options queueLimit - Limit on the number of requests the background-writer thread can have in the queue. Integer Default: 10000 timeToSleepBetweenBatches - Time in milliseconds to sleep between batches. Integer Default: 1 (NLog 4.6 changed default from 50 to 1 ). When set to '0' or '1', then it will only trigger timer when something is logged (Less timer activity when idle, Faster logging and improved garbage collection behavior). batchSize - Number of log events that should be processed in a batch by the background-writer thread. Integer Default: 100 (NLog 4.4.2 and newer has Default: 200) fullBatchSizeWriteLimit - Max number of consecutive full batchSize writes to perform within the same timer event. Integer Default: 5. Introduced in NLog 4.4.2 overflowAction - Action to be taken when in-memory-queue becomes full (Reached queueLimit ). This means the background-writer is falling behind, and cannot keep up with the application-threads logging. Default: Discard Possible values: Discard - The application-thread will discard logevent to avoid becoming blocked or causing out-of-memory issues. If memory and large-object-heap usage is not an issue, then one can consider increasing queueLimit to 100.000. ( Default ) Block - The application-thread will block until the background-writer-thread has taken the next batch. Avoids loosing important logevents, but can block all application-threads. Consider to throttle active thread count, by limiting number of concurrent inbound requests. Grow - The application-thread will ignore the queueLimit , and will just allocate more memory. Can cause the entire application to experience out-of-memory-issues. ForceLockingQueue - Force thread synchronization with monitor-lock, instead of using .NET ConcurrentQueue. Legacy NetFramework application will by default use monitor-lock (Default=true). .NET Standard 2.0 will by default use of the .NET lock-free ConcurrentQueue for improved concurrency (Default=false). Introduced in NLog 4.6 Remarks Remember to Flush Remember to Flush before application exit, is very important when enabling use of the Asynchronous target wrapper. Async attribute Asynchronous target wrapper allows the logger code to execute more quickly, by queuing messages for processing by background writer-thread. You should wrap targets that spend a non-trivial amount of time in their Write() method with asynchronous target to speed up logging. Because asynchronous logging is quite a common scenario, NLog supports a shorthand notation for wrapping all targets with AsyncWrapper. Just add async=\"true\" to the element in the configuration file. Example: ... your targets go here ... Async attribute will discard by default The async attribute is a shorthand for: xsi:type=\"AsyncWrapper overflowAction=\"Discard\" queueLimit=\"10000\" batchSize=\"200\" timeToSleepBetweenBatches=\"1\" So if you write a lot of messages (more then 10000) in a short time, it's possible that messages will be lost. This is intended behavior as keeping all the messages or waiting for all the messages to be written, could have impact on the performance of your program. If you need all the log messages, then you can change from to using : ... your targets go here ... AsyncWrapper and When using the AsyncWrapper , do write to the wrapper in your section! In the following example: do write to \"target2\". If the is writing to \"target1\", the messages are not written asynchronously! Asynchronously writing and custom targets When messages are written asynchronously, then writing is performed by the background-writer-thread. There can be custom NLog targets that requires writing to happen on the application-thread for proper context capture. When used together with AsyncWrapper then asynchronous writing is used and context information can be lost. By default all standard NLog targets supports use of AsyncWrapper. Custom NLog targets that inherits from TargetWithContext should also by default work correctly with AsyncWrapper. BufferingWrapper and Async The BufferingWrapper can also be asynchronously when having configured FlushTimeout . AsyncWrapper is intended for improving performance, where BufferingWrapper is intended for throttling or even discarding LogEvents. AsyncWrapper has an internal buffer optimized to handle many concurrent threads.","title":"AsyncWrapper target"},{"location":"AsyncWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"AsyncWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"AsyncWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"AsyncWrapper-target/#buffering-options","text":"queueLimit - Limit on the number of requests the background-writer thread can have in the queue. Integer Default: 10000 timeToSleepBetweenBatches - Time in milliseconds to sleep between batches. Integer Default: 1 (NLog 4.6 changed default from 50 to 1 ). When set to '0' or '1', then it will only trigger timer when something is logged (Less timer activity when idle, Faster logging and improved garbage collection behavior). batchSize - Number of log events that should be processed in a batch by the background-writer thread. Integer Default: 100 (NLog 4.4.2 and newer has Default: 200) fullBatchSizeWriteLimit - Max number of consecutive full batchSize writes to perform within the same timer event. Integer Default: 5. Introduced in NLog 4.4.2 overflowAction - Action to be taken when in-memory-queue becomes full (Reached queueLimit ). This means the background-writer is falling behind, and cannot keep up with the application-threads logging. Default: Discard Possible values: Discard - The application-thread will discard logevent to avoid becoming blocked or causing out-of-memory issues. If memory and large-object-heap usage is not an issue, then one can consider increasing queueLimit to 100.000. ( Default ) Block - The application-thread will block until the background-writer-thread has taken the next batch. Avoids loosing important logevents, but can block all application-threads. Consider to throttle active thread count, by limiting number of concurrent inbound requests. Grow - The application-thread will ignore the queueLimit , and will just allocate more memory. Can cause the entire application to experience out-of-memory-issues. ForceLockingQueue - Force thread synchronization with monitor-lock, instead of using .NET ConcurrentQueue. Legacy NetFramework application will by default use monitor-lock (Default=true). .NET Standard 2.0 will by default use of the .NET lock-free ConcurrentQueue for improved concurrency (Default=false). Introduced in NLog 4.6","title":"Buffering Options"},{"location":"AsyncWrapper-target/#remarks","text":"","title":"Remarks"},{"location":"AsyncWrapper-target/#remember-to-flush","text":"Remember to Flush before application exit, is very important when enabling use of the Asynchronous target wrapper.","title":"Remember to Flush"},{"location":"AsyncWrapper-target/#async-attribute","text":"Asynchronous target wrapper allows the logger code to execute more quickly, by queuing messages for processing by background writer-thread. You should wrap targets that spend a non-trivial amount of time in their Write() method with asynchronous target to speed up logging. Because asynchronous logging is quite a common scenario, NLog supports a shorthand notation for wrapping all targets with AsyncWrapper. Just add async=\"true\" to the element in the configuration file. Example: ... your targets go here ... ","title":"Async attribute"},{"location":"AsyncWrapper-target/#async-attribute-will-discard-by-default","text":"The async attribute is a shorthand for: xsi:type=\"AsyncWrapper overflowAction=\"Discard\" queueLimit=\"10000\" batchSize=\"200\" timeToSleepBetweenBatches=\"1\" So if you write a lot of messages (more then 10000) in a short time, it's possible that messages will be lost. This is intended behavior as keeping all the messages or waiting for all the messages to be written, could have impact on the performance of your program. If you need all the log messages, then you can change from to using : ... your targets go here ... ","title":"Async attribute will discard by default"},{"location":"AsyncWrapper-target/#asyncwrapper-and-rules","text":"When using the AsyncWrapper , do write to the wrapper in your section! In the following example: do write to \"target2\". If the is writing to \"target1\", the messages are not written asynchronously! ","title":"AsyncWrapper and <rules>"},{"location":"AsyncWrapper-target/#asynchronously-writing-and-custom-targets","text":"When messages are written asynchronously, then writing is performed by the background-writer-thread. There can be custom NLog targets that requires writing to happen on the application-thread for proper context capture. When used together with AsyncWrapper then asynchronous writing is used and context information can be lost. By default all standard NLog targets supports use of AsyncWrapper. Custom NLog targets that inherits from TargetWithContext should also by default work correctly with AsyncWrapper.","title":"Asynchronously writing and custom targets"},{"location":"AsyncWrapper-target/#bufferingwrapper-and-async","text":"The BufferingWrapper can also be asynchronously when having configured FlushTimeout . AsyncWrapper is intended for improving performance, where BufferingWrapper is intended for throttling or even discarding LogEvents. AsyncWrapper has an internal buffer optimized to handle many concurrent threads.","title":"BufferingWrapper and Async"},{"location":"Atomic-File-Target/","text":"Writes LogEvents to file using operating system API for atomic file appending ( O_APPEND ), so multiple processes can write concurrently to the same file, by extending the standard NLog File Target . Platforms Supported: NET8 or .NET Framework - Requires nuget-package NLog.Targets.AtomicFile Configuration Syntax Parameters fileName - Name of the file to write to. Layout Required. layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} concurrentWrites - Whether to enable atomic file appends. Default: true keepFileOpen - Disables atomic file appends when configured to false . Default: true Also inherits all parameters from the standard File-Target . Linux Support Uses libc open() with O_APPEND flag, which is supported on Linux and other Unix-like operating systems.","title":"Atomic File Target"},{"location":"Atomic-File-Target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"Atomic-File-Target/#parameters","text":"fileName - Name of the file to write to. Layout Required. layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} concurrentWrites - Whether to enable atomic file appends. Default: true keepFileOpen - Disables atomic file appends when configured to false . Default: true Also inherits all parameters from the standard File-Target .","title":"Parameters"},{"location":"Atomic-File-Target/#linux-support","text":"Uses libc open() with O_APPEND flag, which is supported on Linux and other Unix-like operating systems.","title":"Linux Support"},{"location":"AutoFlushWrapper-target/","text":"Causes a flush on a wrapped target if LogEvent satisfies provided condition. If condition isn't set, a flush will occur after each successful write. Platforms Supported: All Configuration Syntax Parameters General Options name - Name of the target. condition - Condition is expression used to determine if flush must be executed. Introduced in NLog 4.4 asyncFlush - Delay the flush until the LogEvent has been confirmed as written. Default true . Introduced in NLog 4.4.6 where BufferingWrapper-target defaults to false , to avoid waiting long time (forever) to flush NLog 4.7 implements same behavior for AsyncTaskTarget so it defaults to false , to reduce waiting time for flush. flushOnConditionOnly - Ignores explicit flush operations caused by calling NLog.LogManager.Flush() or NLog.LogManager.Shutdown() . Useful when combined with BufferingWrapper and overflowAction=Discard . Introduced in NLog 4.6.6 Examples Flush into target on each write Flush into target, if LogEvent level >= Warn ( introduced in NLog 4.4 ) = LogLevel.Warn\"> ","title":"AutoFlushWrapper target"},{"location":"AutoFlushWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"AutoFlushWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"AutoFlushWrapper-target/#general-options","text":"name - Name of the target. condition - Condition is expression used to determine if flush must be executed. Introduced in NLog 4.4 asyncFlush - Delay the flush until the LogEvent has been confirmed as written. Default true . Introduced in NLog 4.4.6 where BufferingWrapper-target defaults to false , to avoid waiting long time (forever) to flush NLog 4.7 implements same behavior for AsyncTaskTarget so it defaults to false , to reduce waiting time for flush. flushOnConditionOnly - Ignores explicit flush operations caused by calling NLog.LogManager.Flush() or NLog.LogManager.Shutdown() . Useful when combined with BufferingWrapper and overflowAction=Discard . Introduced in NLog 4.6.6","title":"General Options"},{"location":"AutoFlushWrapper-target/#examples","text":"Flush into target on each write Flush into target, if LogEvent level >= Warn ( introduced in NLog 4.4 ) = LogLevel.Warn\"> ","title":"Examples"},{"location":"Basedir-layout-renderer/","text":"The current application AppDomain.BaseDirectory , and usually the location of application-binaries. Platforms Supported: All See also ${processdir} , ${specialfolder} , ${currentdir} , ${tempdir} Configuration Syntax ${basedir:dir=String:file=String:processDir=boolean} Parameters Advanced Options dir - Name of the directory to be Path.Combine()'d with the base directory. file - Name of the file to be Path.Combine()'d with the base directory. processDir - Introduced in NLog 4.4.2. Render the base directory of the current process? Default false . Alternative one can use the ${processdir} introduced with NLog v4.7.1 fixTempDir - Enable automatic fallback to processDir when detecting AppDomain.BaseDirectory is temp-directory. Workaround for single-file-publish on NetCore 3.1, and no longer needed with .NET 6. Introduced with NLog v4.6.8 See also: FileTarget FileName Directory","title":"Basedir layout renderer"},{"location":"Basedir-layout-renderer/#configuration-syntax","text":"${basedir:dir=String:file=String:processDir=boolean}","title":"Configuration Syntax"},{"location":"Basedir-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Basedir-layout-renderer/#advanced-options","text":"dir - Name of the directory to be Path.Combine()'d with the base directory. file - Name of the file to be Path.Combine()'d with the base directory. processDir - Introduced in NLog 4.4.2. Render the base directory of the current process? Default false . Alternative one can use the ${processdir} introduced with NLog v4.7.1 fixTempDir - Enable automatic fallback to processDir when detecting AppDomain.BaseDirectory is temp-directory. Workaround for single-file-publish on NetCore 3.1, and no longer needed with .NET 6. Introduced with NLog v4.6.8 See also: FileTarget FileName Directory","title":"Advanced Options"},{"location":"BufferingWrapper-target/","text":"A target that buffers log events and sends them in batches to the wrapped target. This wrapper is mostly to help throttle and filter log events. For high-performance logging use AsyncWrapper-target . Platforms Supported: All Configuration Syntax Parameters General Options name - Name of the target. Buffering Options bufferSize - Number of log events to be buffered. When the limit is reached, then a synchronous flush is performed. Integer Default: 100 flushTimeout - Timeout (in milliseconds) after a write, until the entire buffer is asynchronously flushed. Use -1 to disable timed flushes. Integer Default: -1 slidingTimeout - Indicates whether to use sliding flushTimeout . Boolean Default: True This value determines how the inactivity period is determined. If sliding timeout is enabled, the inactivity timer is reset after each write, if it is disabled - inactivity timer will count from the first event written to the buffer. overflowAction - Action to be taken when the buffer exceeds the set bufferSize . Enum Default: Flush . Introduced in NLog 4.5 Possible values: Flush - All the log events in the buffer will be written in the wrapped target. Discard - The oldest log event will be removed from the buffer. If this setting is used, the Flush action will need to be triggered manually using another wrapper like the AutoFlushWrapper or by using the flushTimeout option. Remarks Buffering and custom targets When messages are written into the BufferingWrapper, then LogEvents are queued for writing at a later stage. There can be custom NLog targets that requires writing to happen on the main thread for proper context capture (without being queued). When used together with BufferingWrapper then context information can be lost. By default all standard NLog targets supports use of BufferingWrapper. Custom NLog targets that inherits from TargetWithContext should also by default work correctly with BufferingWrapper. Buffer and asynchronously writing If flushTimeout is larger than 0 , then the messages are written asynchronously. If the buffer is filled before the flushTimeout fires and triggers the asynchronous flush, then the logging thread will be performing the flush, and be blocked by the operation. Because the BufferingWrapper is not intended for performance optimization, but for throttling or even discarding LogEvents. Then it can be a good idea to make use of the async attribute or the AsyncWrapper . Send batch when triggered by event This will send the last 50 messages to the myTargetType , when an Error occurs: = LogLevel.Error\" flushOnConditionOnly=\"true\"> ","title":"BufferingWrapper target"},{"location":"BufferingWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"BufferingWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"BufferingWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"BufferingWrapper-target/#buffering-options","text":"bufferSize - Number of log events to be buffered. When the limit is reached, then a synchronous flush is performed. Integer Default: 100 flushTimeout - Timeout (in milliseconds) after a write, until the entire buffer is asynchronously flushed. Use -1 to disable timed flushes. Integer Default: -1 slidingTimeout - Indicates whether to use sliding flushTimeout . Boolean Default: True This value determines how the inactivity period is determined. If sliding timeout is enabled, the inactivity timer is reset after each write, if it is disabled - inactivity timer will count from the first event written to the buffer. overflowAction - Action to be taken when the buffer exceeds the set bufferSize . Enum Default: Flush . Introduced in NLog 4.5 Possible values: Flush - All the log events in the buffer will be written in the wrapped target. Discard - The oldest log event will be removed from the buffer. If this setting is used, the Flush action will need to be triggered manually using another wrapper like the AutoFlushWrapper or by using the flushTimeout option.","title":"Buffering Options"},{"location":"BufferingWrapper-target/#remarks","text":"","title":"Remarks"},{"location":"BufferingWrapper-target/#buffering-and-custom-targets","text":"When messages are written into the BufferingWrapper, then LogEvents are queued for writing at a later stage. There can be custom NLog targets that requires writing to happen on the main thread for proper context capture (without being queued). When used together with BufferingWrapper then context information can be lost. By default all standard NLog targets supports use of BufferingWrapper. Custom NLog targets that inherits from TargetWithContext should also by default work correctly with BufferingWrapper.","title":"Buffering and custom targets"},{"location":"BufferingWrapper-target/#buffer-and-asynchronously-writing","text":"If flushTimeout is larger than 0 , then the messages are written asynchronously. If the buffer is filled before the flushTimeout fires and triggers the asynchronous flush, then the logging thread will be performing the flush, and be blocked by the operation. Because the BufferingWrapper is not intended for performance optimization, but for throttling or even discarding LogEvents. Then it can be a good idea to make use of the async attribute or the AsyncWrapper .","title":"Buffer and asynchronously writing"},{"location":"BufferingWrapper-target/#send-batch-when-triggered-by-event","text":"This will send the last 50 messages to the myTargetType , when an Error occurs: = LogLevel.Error\" flushOnConditionOnly=\"true\"> ","title":"Send batch when triggered by event"},{"location":"Cached-Layout-Renderer/","text":"Applies caching to another layout output. Platforms Supported: All Configuration Syntax ${cached:cached=Boolean:clearCache=ClearCacheOption:inner=Layout:cacheKey=Layout} or by using ambient property to modify output of other layout renderer: ${other:cached=Boolean} Parameters Caching Options cached - Indicates whether this CachedLayoutRendererWrapper is enabled. Boolean Default: True clearCache - Indicates when the cache is cleared. Possible options: None, OnInit, Onclose . ClearCacheOption Default: OnInit, OnClose . Introduced in NLog 4.2. cacheKey - the layout to be checked if the cache is still valid. For example, the current day. Default: null . Introduced in NLog 4.3.9 cachedSeconds - Cached value will expire after timeout. Default: infinite Introduced in NLog 4.6.8 Transformation Options inner - Wrapped layout. Layout Examples ${cached:cached=true:clearCache=OnInit,OnClose:inner=l} : The value of l is cached and the cache will be cleared when the layout renderer is initialized or when it is closed. This is the same as ${cached:cached=true:inner=l} . ${cached:cached=true:clearCache=None:inner=l} : The value of l is cached and the cache will not be cleared. filename=\"${cached:cached=true:Inner=${date:format=yyyy-MM-dd hh.mm.ss}:CacheKey=${shortdate}}.log\" - Use the first logtime and day in the file name, only one file per day. Remarks The value of the inner layout will be rendered only once and reused subsequently.","title":"Cached Layout Renderer"},{"location":"Cached-Layout-Renderer/#configuration-syntax","text":"${cached:cached=Boolean:clearCache=ClearCacheOption:inner=Layout:cacheKey=Layout} or by using ambient property to modify output of other layout renderer: ${other:cached=Boolean}","title":"Configuration Syntax"},{"location":"Cached-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Cached-Layout-Renderer/#caching-options","text":"cached - Indicates whether this CachedLayoutRendererWrapper is enabled. Boolean Default: True clearCache - Indicates when the cache is cleared. Possible options: None, OnInit, Onclose . ClearCacheOption Default: OnInit, OnClose . Introduced in NLog 4.2. cacheKey - the layout to be checked if the cache is still valid. For example, the current day. Default: null . Introduced in NLog 4.3.9 cachedSeconds - Cached value will expire after timeout. Default: infinite Introduced in NLog 4.6.8","title":"Caching Options"},{"location":"Cached-Layout-Renderer/#transformation-options","text":"inner - Wrapped layout. Layout","title":"Transformation Options"},{"location":"Cached-Layout-Renderer/#examples","text":"${cached:cached=true:clearCache=OnInit,OnClose:inner=l} : The value of l is cached and the cache will be cleared when the layout renderer is initialized or when it is closed. This is the same as ${cached:cached=true:inner=l} . ${cached:cached=true:clearCache=None:inner=l} : The value of l is cached and the cache will not be cleared. filename=\"${cached:cached=true:Inner=${date:format=yyyy-MM-dd hh.mm.ss}:CacheKey=${shortdate}}.log\" - Use the first logtime and day in the file name, only one file per day.","title":"Examples"},{"location":"Cached-Layout-Renderer/#remarks","text":"The value of the inner layout will be rendered only once and reused subsequently.","title":"Remarks"},{"location":"Callsite-file-name-layout-renderer/","text":"The call site source file name. For full callsite use CallSiteLayoutRenderer Introduced in NLog v4.5 Supported in .NET and Mono. Configuration Syntax ${callsite-filename:includeSourcePath=Boolean:skipFrames=Integer} Parameters Rendering Options includeSourcePath - Shows the full path of the source file. Boolean Default: True skipFrames - The number of frames to skip. Integer Default: 0 captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1 Notes Please also note that this infers heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message.","title":"Callsite file name layout renderer"},{"location":"Callsite-file-name-layout-renderer/#configuration-syntax","text":"${callsite-filename:includeSourcePath=Boolean:skipFrames=Integer}","title":"Configuration Syntax"},{"location":"Callsite-file-name-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Callsite-file-name-layout-renderer/#rendering-options","text":"includeSourcePath - Shows the full path of the source file. Boolean Default: True skipFrames - The number of frames to skip. Integer Default: 0 captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1","title":"Rendering Options"},{"location":"Callsite-file-name-layout-renderer/#notes","text":"Please also note that this infers heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message.","title":"Notes"},{"location":"Callsite-layout-renderer/","text":"CallSite outputs the source-file-name and source-line-number where a LogEvent occurred. NLog scans the callstack and output the method-stackframe just before the NLog Logger takes over. Platforms Supported: All Configuration Syntax ${callsite:className=Boolean:fileName=Boolean:includeSourcePath=Boolean:methodName=Boolean} Parameters Rendering Options className - Indicates whether to render the class name. Boolean Default: True includeNamespace - Include namespace in class name. Boolean Default: True Introduced with NLog v4.4 fileName - Indicates whether to render the source file name and line number.Boolean Default: False includeSourcePath - Indicates whether to include source file path.Boolean Default: True methodName - Indicates whether to render the method name.Boolean Default: True cleanNamesOfAnonymousDelegates - Indicates whether the method name will be cleaned up if it is detected as an anonymous delegate. Boolean Default: True Introduced with NLog v4.3.9. Before NLog 5.0 the default value was False . cleanNamesOfAsyncContinuations - Indicates whether the method and class names will be cleaned up if it is detected as an async continuation. Boolean Default: True Introduced with NLog v4.5. Before NLog 5.0 the default value was False . skipFrames - The number of frames to skip. Integer Default: 0 captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1 Notes The Callsite-LayoutRenderer infers a heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message. NLog 5.0 makes it possible to skip the StackTrace-capture, when using LogEventInfo.SetCallerInfo(...) with input from Caller Information -attributes. NLog 5.0 provides Fluent-Logger-API for easy capture of caller-information, and provides fast logging when using ${callsite:captureStackTrace=false} : _logger.ForInfoEvent() .Message(\"This is a fluent message {0}\", \"test\") .Property(\"PropertyName\", \"PropertyValue\") .Log(); If using Custom wrapper for NLog Logger , then make sure to provide the typeof(OwnWrapper) as input, when calling NLog Logger: Logger.Log(Type wrapperType, LogEventInfo logEvent) Alternative if the custom Logger-wrapper comes from its own dedicated Assembly, then one can exclude the entire Assembly: NLog.LogManager.AddHiddenAssembly(typeof(OwnWrapper).Assembly); If symbol information is not available, then it will not be able to output source-code filename or line-number. Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause \"unexpected\" line-numbers. If using Deterministic builds then it will generate symbol information with relative paths: true $(SolutionDir)=./ true ","title":"Callsite layout renderer"},{"location":"Callsite-layout-renderer/#configuration-syntax","text":"${callsite:className=Boolean:fileName=Boolean:includeSourcePath=Boolean:methodName=Boolean}","title":"Configuration Syntax"},{"location":"Callsite-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Callsite-layout-renderer/#rendering-options","text":"className - Indicates whether to render the class name. Boolean Default: True includeNamespace - Include namespace in class name. Boolean Default: True Introduced with NLog v4.4 fileName - Indicates whether to render the source file name and line number.Boolean Default: False includeSourcePath - Indicates whether to include source file path.Boolean Default: True methodName - Indicates whether to render the method name.Boolean Default: True cleanNamesOfAnonymousDelegates - Indicates whether the method name will be cleaned up if it is detected as an anonymous delegate. Boolean Default: True Introduced with NLog v4.3.9. Before NLog 5.0 the default value was False . cleanNamesOfAsyncContinuations - Indicates whether the method and class names will be cleaned up if it is detected as an async continuation. Boolean Default: True Introduced with NLog v4.5. Before NLog 5.0 the default value was False . skipFrames - The number of frames to skip. Integer Default: 0 captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1","title":"Rendering Options"},{"location":"Callsite-layout-renderer/#notes","text":"The Callsite-LayoutRenderer infers a heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message. NLog 5.0 makes it possible to skip the StackTrace-capture, when using LogEventInfo.SetCallerInfo(...) with input from Caller Information -attributes. NLog 5.0 provides Fluent-Logger-API for easy capture of caller-information, and provides fast logging when using ${callsite:captureStackTrace=false} : _logger.ForInfoEvent() .Message(\"This is a fluent message {0}\", \"test\") .Property(\"PropertyName\", \"PropertyValue\") .Log(); If using Custom wrapper for NLog Logger , then make sure to provide the typeof(OwnWrapper) as input, when calling NLog Logger: Logger.Log(Type wrapperType, LogEventInfo logEvent) Alternative if the custom Logger-wrapper comes from its own dedicated Assembly, then one can exclude the entire Assembly: NLog.LogManager.AddHiddenAssembly(typeof(OwnWrapper).Assembly); If symbol information is not available, then it will not be able to output source-code filename or line-number. Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause \"unexpected\" line-numbers. If using Deterministic builds then it will generate symbol information with relative paths: true $(SolutionDir)=./ true ","title":"Notes"},{"location":"Callsite-line-number-layout-renderer/","text":"The call site source-code line-number. For full callsite use ${callsite} Platforms Supported: All Introduced in NLog v4.1 Configuration Syntax ${callsite-linenumber:skipFrames=Integer} Parameters Rendering Options skipFrames - The number of frames to skip. Integer Default: 0 captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1 Notes Please also note that this infers heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message. If symbol symbol information is not available, then it will only output source-code line-number 0 . Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause \"unexpected\" line-numbers.","title":"Callsite line number layout renderer"},{"location":"Callsite-line-number-layout-renderer/#configuration-syntax","text":"${callsite-linenumber:skipFrames=Integer}","title":"Configuration Syntax"},{"location":"Callsite-line-number-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Callsite-line-number-layout-renderer/#rendering-options","text":"skipFrames - The number of frames to skip. Integer Default: 0 captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1","title":"Rendering Options"},{"location":"Callsite-line-number-layout-renderer/#notes","text":"Please also note that this infers heavy performance hit when doing lots of logging, as it has to capture full StackTrace for every log message. If symbol symbol information is not available, then it will only output source-code line-number 0 . Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause \"unexpected\" line-numbers.","title":"Notes"},{"location":"Chainsaw-target/","text":"Sends log messages to the remote instance of Log4J XML Viewer applications (Like Chainsaw). Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6 This target inherits from the Network Target , and so it has also all the properties of the Network Target available. Using the Log4JXmlEventLayout to produce Log4J XML output. \u2139\ufe0f NLog v6 has merged NLogViewer-Target and ChainSaw-Target into Log4JXml-Target Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Introduced in 4.3.8. Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default) Connection Options connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb For SOAP-based webservice support over HTTP use WebService target. keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . Introduced with NLog v4.2.1. Default became 16 with NLog v4.5 (Before 0 ) onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Introduced with NLog v4.2.1. Default became Block with NLog v4.5 (Before AllowNewConnnection ) Possible enum values: * Discard - Discard new messages when reaching limit (Default) (Before NLog 5.0 it was enum value DiscardMessage ) * Grow - Send message and ignore limit (Before NLog 5.0 it was enum value AllowNewConnnection ) * Block - Block until pending connections has beeen freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 (Before NLog 5.0 the default was 0) NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. NLog 5.0.0 enabled queue-support for UDP. onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Introduced with NLog 5.0 Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. Payload Options IncludeEventProperties - Include all events properties of a logevent? Default: true . Before NLog 5.0 option was named IncludeAllProperties and had default false . IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 4.5 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 parameter - Additional context properties that should be included. name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required. Example Available Log4J-XML viewers (See also LogViewer Tools ) - Sentinel - Avoid using TCP since not complete. - Log2Console - Logazmic - Loginator - Logbert - LogViewer - Lilith - OtrosLogViewer Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this: ","title":"Chainsaw target"},{"location":"Chainsaw-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Chainsaw-target/#parameters","text":"","title":"Parameters"},{"location":"Chainsaw-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Chainsaw-target/#layout-options","text":"layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Introduced in 4.3.8. Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default)","title":"Layout Options"},{"location":"Chainsaw-target/#connection-options","text":"connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb For SOAP-based webservice support over HTTP use WebService target. keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . Introduced with NLog v4.2.1. Default became 16 with NLog v4.5 (Before 0 ) onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Introduced with NLog v4.2.1. Default became Block with NLog v4.5 (Before AllowNewConnnection ) Possible enum values: * Discard - Discard new messages when reaching limit (Default) (Before NLog 5.0 it was enum value DiscardMessage ) * Grow - Send message and ignore limit (Before NLog 5.0 it was enum value AllowNewConnnection ) * Block - Block until pending connections has beeen freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 (Before NLog 5.0 the default was 0) NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. NLog 5.0.0 enabled queue-support for UDP. onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Introduced with NLog 5.0 Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit.","title":"Connection Options"},{"location":"Chainsaw-target/#payload-options","text":"IncludeEventProperties - Include all events properties of a logevent? Default: true . Before NLog 5.0 option was named IncludeAllProperties and had default false . IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 4.5 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 parameter - Additional context properties that should be included. name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required.","title":"Payload Options"},{"location":"Chainsaw-target/#example","text":" Available Log4J-XML viewers (See also LogViewer Tools ) - Sentinel - Avoid using TCP since not complete. - Log2Console - Logazmic - Loginator - Logbert - LogViewer - Lilith - OtrosLogViewer Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this: ","title":"Example"},{"location":"ColoredConsole-target/","text":"Writes log messages to the console with customizable coloring. Platforms Supported: All There is also the simple Console-Target without any overhead from coloring. Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. encoding - File encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Defaults to Encoding.Default . Introduced with NLog 4.0 Layout Options layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message} header - Header. Layout footer - Footer. Layout Output Options StdErr - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). Layout Default: False Before NLog v5.0 the property was named errorStream . NLog 6.0 changed property from boolean to NLog Layout detectConsoleAvailable - Indicates whether the console target should disable itself when no console detected. Boolean Default: false Introduced in NLog 4.3.10 with default: true , then NLog 4.4 changed default to false . detectOutputRedirected - Indicates whether the console target should disable coloring when it detects that Console.IsOutputRedirected = true (Skip coloring when pipe to file) Introduced in NLog 4.6.7 noColor - Incicates whether console target should disable coloring when detecting environment-variable NO_COLOR=1 Introduced with NLog v5.4 enableAnsiOutput - Enables output using ANSI Color Codes. Needed for e.g. Visual Studio Code. Boolean Default: false Introduced in NLog 4.6 autoFlush - Performs explicit flush after every console write. Useful if having redirected to custom console-stream that doesn't has autoflush enabled. Boolean. Default = False. Introduced in NLog 4.6.3 Highlighting Rules useDefaultRowHighlightingRules - Indicates whether to use default row highlighting rules. Boolean Default: True NLog v6 changed the default rules not use yellow for Error and maganta for Warn Colors : Condition Foreground Color Background Color level == LogLevel.Fatal Red NoChange level == LogLevel.Error Red NoChange level == LogLevel.Warn Yellow NoChange level == LogLevel.Info White NoChange level == LogLevel.Debug Gray NoChange level == LogLevel.Trace Gray NoChange rowHighlightingRules - The row highlighting rules. Collection Each collection item is represented by \\ element with the following attributes: backgroundColor - Background color. Color Enum Default: NoChange foregroundColor - Foreground color. Color Enum Default: NoChange condition - Condition that must be met in order to set the specified foreground and background color. Condition Required. wordHighlightingRules - The word highlighting rules. Collection Each collection item is represented by \\ element with the following attributes: backgroundColor - Background color. Color Enum Default: NoChange foregroundColor - Foreground color. Color Enum Default: NoChange text - Text to be matched. You must specify either text or regex. words - Comma-separated list of words to be matched (Make sure to remove leading/trailing spaces) > Introduced with NLog v6.0.3 ignoreCase - Indicates whether to ignore case when comparing texts. Boolean Default: false wholeWords - Indicates whether to match whole words only. Boolean Default: false > Enhanced with NLog v6.0.4 so text can include special characters for matching, but only highlight letter-/digit-part. condition - Condition that must be met before scanning for words to highlight. Condition . > Introduced with NLog 4.7.1. RegEx not supported NLog v6 no longer supports word-highlight using Regular Expressions (RegEx) and removed these options: regex - Regular expression to be matched. You must specify either text or regex. compileRegex - Introduced in NLog 4.3. Compiles the Regex. If false , the regex cache is used. Setting this to true can improve performance, but costs memory. Default: false Colors Color Enum Description HEX Code ANSI Foreground ANSI Background NoChange Don't change the color Black Black Color #000000 \\x1B[30m \\x1B[40m Blue Blue Color #0000FF \\x1B[94m \\x1B[104m Cyan Cyan Color #00FFFF \\x1B[96m \\x1B[106m DarkBlue Dark Blue Color #000080 \\x1B[34m \\x1B[44m DarkCyan Dark Cyan Color #008080 \\x1B[36m \\x1B[46m DarkGray Dark Gray Color #808080 \\x1B[90m \\x1B[100m DarkGreen Dark Green Color #008000 \\x1B[32m \\x1B[42m DarkMagenta Dark Magenta Color #800080 \\x1B[35m \\x1B[45m DarkRed Dark Red Color #800000 \\x1B[31m \\x1B[41m DarkYellow Dark Yellow Color #808000 \\x1B[33m \\x1B[43m Gray Gray Color #C0C0C0 \\x1B[37m \\x1B[47m Green Green Color #00FF00 \\x1B[92m \\x1B[102m Magenta Magenta Color #FF00FF \\x1B[95m \\x1B[105m Red Red Color #FF0000 \\x1B[91m \\x1B[101m White White Color #FFFFFF \\x1b[97m \\x1B[107m Yellow Yellow Color #FFFF00 \\x1B[93m \\x1B[103m Programmatic example var consoleTarget = new ColoredConsoleTarget(); var highlightRule = new ConsoleRowHighlightingRule(); highlightRule.Condition = ConditionParser.ParseExpression(\"level == LogLevel.Info\"); highlightRule.ForegroundColor = ConsoleOutputColor.Green; consoleTarget.RowHighlightingRules.Add(highlightRule); Microsoft Extension Logging AddConsole The NLog Layout of the ColoredConsole-Target can be configured to match the output of the default MEL AddConsole(). See also NLog Console and AddConsole Visual Studio Output window The Visual Studio \"Output Window\" is bit tricky with colors. It is not a real console window - it just displays the console output from the application. You could get colors by prefixing the message in your config (Ex. Layout=\"${level:format=FulleName}: ${message}\" ) \"Error: \" - for errors - red \"Warning: \" - for warnings - orange See Stackoverflow Or use The Visual Studio extension VSColorOutput (VS2015-2019). Then you could also use the regular Console target . Missing colors for dotnet watch run When running application using dotnet watch run then one might experience that console colors are missing. This can be fixed by changing launchSettings.json and removing the entry launchBrowser and the colors should return. See also: https://github.com/dotnet/aspnetcore/issues/25317","title":"ColoredConsole target"},{"location":"ColoredConsole-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"ColoredConsole-target/#parameters","text":"","title":"Parameters"},{"location":"ColoredConsole-target/#general-options","text":"name - Name of the target. encoding - File encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Defaults to Encoding.Default . Introduced with NLog 4.0","title":"General Options"},{"location":"ColoredConsole-target/#layout-options","text":"layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message} header - Header. Layout footer - Footer. Layout","title":"Layout Options"},{"location":"ColoredConsole-target/#output-options","text":"StdErr - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). Layout Default: False Before NLog v5.0 the property was named errorStream . NLog 6.0 changed property from boolean to NLog Layout detectConsoleAvailable - Indicates whether the console target should disable itself when no console detected. Boolean Default: false Introduced in NLog 4.3.10 with default: true , then NLog 4.4 changed default to false . detectOutputRedirected - Indicates whether the console target should disable coloring when it detects that Console.IsOutputRedirected = true (Skip coloring when pipe to file) Introduced in NLog 4.6.7 noColor - Incicates whether console target should disable coloring when detecting environment-variable NO_COLOR=1 Introduced with NLog v5.4 enableAnsiOutput - Enables output using ANSI Color Codes. Needed for e.g. Visual Studio Code. Boolean Default: false Introduced in NLog 4.6 autoFlush - Performs explicit flush after every console write. Useful if having redirected to custom console-stream that doesn't has autoflush enabled. Boolean. Default = False. Introduced in NLog 4.6.3","title":"Output Options"},{"location":"ColoredConsole-target/#highlighting-rules","text":"useDefaultRowHighlightingRules - Indicates whether to use default row highlighting rules. Boolean Default: True NLog v6 changed the default rules not use yellow for Error and maganta for Warn Colors : Condition Foreground Color Background Color level == LogLevel.Fatal Red NoChange level == LogLevel.Error Red NoChange level == LogLevel.Warn Yellow NoChange level == LogLevel.Info White NoChange level == LogLevel.Debug Gray NoChange level == LogLevel.Trace Gray NoChange rowHighlightingRules - The row highlighting rules. Collection Each collection item is represented by \\ element with the following attributes: backgroundColor - Background color. Color Enum Default: NoChange foregroundColor - Foreground color. Color Enum Default: NoChange condition - Condition that must be met in order to set the specified foreground and background color. Condition Required. wordHighlightingRules - The word highlighting rules. Collection Each collection item is represented by \\ element with the following attributes: backgroundColor - Background color. Color Enum Default: NoChange foregroundColor - Foreground color. Color Enum Default: NoChange text - Text to be matched. You must specify either text or regex. words - Comma-separated list of words to be matched (Make sure to remove leading/trailing spaces) > Introduced with NLog v6.0.3 ignoreCase - Indicates whether to ignore case when comparing texts. Boolean Default: false wholeWords - Indicates whether to match whole words only. Boolean Default: false > Enhanced with NLog v6.0.4 so text can include special characters for matching, but only highlight letter-/digit-part. condition - Condition that must be met before scanning for words to highlight. Condition . > Introduced with NLog 4.7.1.","title":"Highlighting Rules"},{"location":"ColoredConsole-target/#regex-not-supported","text":"NLog v6 no longer supports word-highlight using Regular Expressions (RegEx) and removed these options: regex - Regular expression to be matched. You must specify either text or regex. compileRegex - Introduced in NLog 4.3. Compiles the Regex. If false , the regex cache is used. Setting this to true can improve performance, but costs memory. Default: false","title":"RegEx not supported"},{"location":"ColoredConsole-target/#colors","text":"Color Enum Description HEX Code ANSI Foreground ANSI Background NoChange Don't change the color Black Black Color #000000 \\x1B[30m \\x1B[40m Blue Blue Color #0000FF \\x1B[94m \\x1B[104m Cyan Cyan Color #00FFFF \\x1B[96m \\x1B[106m DarkBlue Dark Blue Color #000080 \\x1B[34m \\x1B[44m DarkCyan Dark Cyan Color #008080 \\x1B[36m \\x1B[46m DarkGray Dark Gray Color #808080 \\x1B[90m \\x1B[100m DarkGreen Dark Green Color #008000 \\x1B[32m \\x1B[42m DarkMagenta Dark Magenta Color #800080 \\x1B[35m \\x1B[45m DarkRed Dark Red Color #800000 \\x1B[31m \\x1B[41m DarkYellow Dark Yellow Color #808000 \\x1B[33m \\x1B[43m Gray Gray Color #C0C0C0 \\x1B[37m \\x1B[47m Green Green Color #00FF00 \\x1B[92m \\x1B[102m Magenta Magenta Color #FF00FF \\x1B[95m \\x1B[105m Red Red Color #FF0000 \\x1B[91m \\x1B[101m White White Color #FFFFFF \\x1b[97m \\x1B[107m Yellow Yellow Color #FFFF00 \\x1B[93m \\x1B[103m","title":"Colors"},{"location":"ColoredConsole-target/#programmatic-example","text":"var consoleTarget = new ColoredConsoleTarget(); var highlightRule = new ConsoleRowHighlightingRule(); highlightRule.Condition = ConditionParser.ParseExpression(\"level == LogLevel.Info\"); highlightRule.ForegroundColor = ConsoleOutputColor.Green; consoleTarget.RowHighlightingRules.Add(highlightRule);","title":"Programmatic example"},{"location":"ColoredConsole-target/#microsoft-extension-logging-addconsole","text":"The NLog Layout of the ColoredConsole-Target can be configured to match the output of the default MEL AddConsole(). See also NLog Console and AddConsole","title":"Microsoft Extension Logging AddConsole"},{"location":"ColoredConsole-target/#visual-studio-output-window","text":"The Visual Studio \"Output Window\" is bit tricky with colors. It is not a real console window - it just displays the console output from the application. You could get colors by prefixing the message in your config (Ex. Layout=\"${level:format=FulleName}: ${message}\" ) \"Error: \" - for errors - red \"Warning: \" - for warnings - orange See Stackoverflow Or use The Visual Studio extension VSColorOutput (VS2015-2019). Then you could also use the regular Console target .","title":"Visual Studio Output window"},{"location":"ColoredConsole-target/#missing-colors-for-dotnet-watch-run","text":"When running application using dotnet watch run then one might experience that console colors are missing. This can be fixed by changing launchSettings.json and removing the entry launchBrowser and the colors should return. See also: https://github.com/dotnet/aspnetcore/issues/25317","title":"Missing colors for dotnet watch run"},{"location":"Combine-XML-config-with-C%23-config/","text":"Combining XML config with C# config is tricky, as autoreload/load of the XML file could overwrite the C# config. To combine both, the ConfigurationChanged event is needed Example We use the nlog.config and We add the console target and rules in C# using System; using NLog; using NLog.Config; using NLog.Targets; class Program { // Define a static logger variable so that it references the logger instanced named \"Scribe\" private static readonly Logger log = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { ExtendNLogConfig(); LogManager.ConfigurationChanged += LogManager_ConfigurationChanged; log.Info(\"Entering Application.\"); Console.WriteLine(\"Press any key to exit ...\"); Console.Read(); } private static void LogManager_ConfigurationChanged(object sender, LoggingConfigurationChangedEventArgs e) { if (e.ActivatedConfiguration != null) { ExtendNLogConfig(); } } /// /// Extend the logging rules in the nlog.config with programmically rules. /// private static void ExtendNLogConfig() { // Do NOT set LogManager.Configuration because that will cause recursion and stackoverflow var consoleTarget = new ColoredConsoleTarget(); consoleTarget.Name = \"console\"; LogManager.Configuration.AddTarget(\"console\", consoleTarget); consoleTarget.Layout = @\"${date:format=HH\\:mm\\:ss} ${logger} ${message} ${exception} ${event-properties:item=MyValue}\"; var rule1 = new LoggingRule(\"*\", LogLevel.Debug, consoleTarget); LogManager.Configuration.LoggingRules.Add(rule1); LogManager.ReconfigExistingLoggers(); } }","title":"Combine XML config with C# config"},{"location":"Combine-XML-config-with-C%23-config/#example","text":"We use the nlog.config and We add the console target and rules in C# using System; using NLog; using NLog.Config; using NLog.Targets; class Program { // Define a static logger variable so that it references the logger instanced named \"Scribe\" private static readonly Logger log = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { ExtendNLogConfig(); LogManager.ConfigurationChanged += LogManager_ConfigurationChanged; log.Info(\"Entering Application.\"); Console.WriteLine(\"Press any key to exit ...\"); Console.Read(); } private static void LogManager_ConfigurationChanged(object sender, LoggingConfigurationChangedEventArgs e) { if (e.ActivatedConfiguration != null) { ExtendNLogConfig(); } } /// /// Extend the logging rules in the nlog.config with programmically rules. /// private static void ExtendNLogConfig() { // Do NOT set LogManager.Configuration because that will cause recursion and stackoverflow var consoleTarget = new ColoredConsoleTarget(); consoleTarget.Name = \"console\"; LogManager.Configuration.AddTarget(\"console\", consoleTarget); consoleTarget.Layout = @\"${date:format=HH\\:mm\\:ss} ${logger} ${message} ${exception} ${event-properties:item=MyValue}\"; var rule1 = new LoggingRule(\"*\", LogLevel.Debug, consoleTarget); LogManager.Configuration.LoggingRules.Add(rule1); LogManager.ReconfigExistingLoggers(); } }","title":"Example"},{"location":"CompoundLayout/","text":"Concatenate multiple layouts, so they become a single layout. Platforms Supported: All Introduced in NLog 4.3.6 text1 - text2 Advanced examples From code var compoundLayout = new CompoundLayout { Layouts = { new SimpleLayout(\"myAmazingText: \"), new JsonLayout { Attributes = { new JsonAttribute(\"time\", \"${longdate}\"), new JsonAttribute(\"level\", \"${level:upperCase=true}\"), } } } }; myAmazingText: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"INFO\" } From XML myAmazingText: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"INFO\" }","title":"CompoundLayout"},{"location":"CompoundLayout/#advanced-examples","text":"","title":"Advanced examples"},{"location":"CompoundLayout/#from-code","text":"var compoundLayout = new CompoundLayout { Layouts = { new SimpleLayout(\"myAmazingText: \"), new JsonLayout { Attributes = { new JsonAttribute(\"time\", \"${longdate}\"), new JsonAttribute(\"level\", \"${level:upperCase=true}\"), } } } }; myAmazingText: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"INFO\" }","title":"From code"},{"location":"CompoundLayout/#from-xml","text":" myAmazingText: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"INFO\" }","title":"From XML"},{"location":"Conditions/","text":"See https://github.com/NLog/NLog/wiki/When-Filter#conditions","title":"Conditions"},{"location":"ConfigSetting-Layout-Renderer/","text":"Lookup value from the appsettings.json or appsettings.Production.json and other configuration sources/overrides. Introduced with NLog.Extensions.Logging 1.4.0 and NLog.Web.AspNetCore 4.8.0 Configuration Syntax ${configsetting:item=String:default=String} Parameters Rendering Options item - Key in the config. Required. Use . for nested objects. Default - Default value if not present. Optional. Setup ConfigSetting ${configsetting} depends on Microsoft.Extensions.Configuration being loaded and available, so if using UseNLog() or AddNLog() on HostBuilder then everything will work out-of-the-box. But if needing to load NLog configuration early before HostBuilder is ready, then ${configsetting} will not resolve the expected values, which might cause NLog Targets not using the expected configuration values. It is possible to setup ${configsetting} manually for these situations. NLog Fluent Setup using LoadConfigurationFromAppSettings() from NLog.Web.AspNetCore nuget-package: var logger = LogManager.Setup() .LoadConfigurationFromAppSettings() .GetCurrentClassLogger(); NLog Fluent Setup using LoadConfigurationFromSection(() from NLog.Extensions.Logging nuget-package: IConfigurationRoot config = new ConfigurationBuilder() .AddJsonFile(path: \"AppSettings.json\").Build(); var logger = LogManager.Setup() .LoadConfigurationFromSection(config) .GetCurrentClassLogger(); NLog v4 can perform manual registration like this with NLog.Extensions.Logging nuget-package: IConfigurationRoot config = new ConfigurationBuilder() .AddJsonFile(path: \"AppSettings.json\").Build(); NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration = config; Examples Example: appsettings.json: { \"Mode\":\"Prod\", \"Options\":{ \"StorageConnectionString\":\"UseDevelopmentStorage=true\", } } Config Setting Lookup: ${configsetting:item=Mode} // renders \"Prod\" ${configsetting:item=Options.StorageConnectionString} // renders \"UseDevelopmentStorage=true\" ${configsetting:item=Options.TableName:default=MyTable} // renders \"MyTable\" Config Setting Lookup Cached: ${configsetting:cached=True:item=Mode} Notice appsettings.json gives the ability to make environment-specific overrides (Ex. appsettings.Production.json ). See also Environment-specific-NLog-Logging-Configuration","title":"ConfigSetting Layout Renderer"},{"location":"ConfigSetting-Layout-Renderer/#configuration-syntax","text":"${configsetting:item=String:default=String}","title":"Configuration Syntax"},{"location":"ConfigSetting-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"ConfigSetting-Layout-Renderer/#rendering-options","text":"item - Key in the config. Required. Use . for nested objects. Default - Default value if not present. Optional.","title":"Rendering Options"},{"location":"ConfigSetting-Layout-Renderer/#setup-configsetting","text":"${configsetting} depends on Microsoft.Extensions.Configuration being loaded and available, so if using UseNLog() or AddNLog() on HostBuilder then everything will work out-of-the-box. But if needing to load NLog configuration early before HostBuilder is ready, then ${configsetting} will not resolve the expected values, which might cause NLog Targets not using the expected configuration values. It is possible to setup ${configsetting} manually for these situations. NLog Fluent Setup using LoadConfigurationFromAppSettings() from NLog.Web.AspNetCore nuget-package: var logger = LogManager.Setup() .LoadConfigurationFromAppSettings() .GetCurrentClassLogger(); NLog Fluent Setup using LoadConfigurationFromSection(() from NLog.Extensions.Logging nuget-package: IConfigurationRoot config = new ConfigurationBuilder() .AddJsonFile(path: \"AppSettings.json\").Build(); var logger = LogManager.Setup() .LoadConfigurationFromSection(config) .GetCurrentClassLogger(); NLog v4 can perform manual registration like this with NLog.Extensions.Logging nuget-package: IConfigurationRoot config = new ConfigurationBuilder() .AddJsonFile(path: \"AppSettings.json\").Build(); NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration = config;","title":"Setup ConfigSetting"},{"location":"ConfigSetting-Layout-Renderer/#examples","text":"Example: appsettings.json: { \"Mode\":\"Prod\", \"Options\":{ \"StorageConnectionString\":\"UseDevelopmentStorage=true\", } } Config Setting Lookup: ${configsetting:item=Mode} // renders \"Prod\" ${configsetting:item=Options.StorageConnectionString} // renders \"UseDevelopmentStorage=true\" ${configsetting:item=Options.TableName:default=MyTable} // renders \"MyTable\" Config Setting Lookup Cached: ${configsetting:cached=True:item=Mode} Notice appsettings.json gives the ability to make environment-specific overrides (Ex. appsettings.Production.json ). See also Environment-specific-NLog-Logging-Configuration","title":"Examples"},{"location":"Configuration-API/","text":"moved here: https://github.com/NLog/NLog/wiki/Configure-from-code","title":"Configuration API"},{"location":"Configuration-file/","text":"NLog will only produce output if having configured one (or more) NLog targets. NLog can be configured using XML by adding a NLog.config, that will be described in the page. Everything that can be configured from XML file, can be also be configured in code. See also How to configure from code . Notice instead of using XML configuration file, then it is also possible to load NLog LoggingConfiguration from the appsettings.json file with help from NLog.Extensions.Logging . Contents NLog config XML File locations Top-level elements Targets Log levels Rules Variables Layouts and layout renderers Asynchronous processing and wrapper targets Default wrappers Default target parameters Extensions Automatic reconfiguration Include files Content escaping Troubleshooting logging NLog config XML Example XML for a stand-alone NLog.config that can be added to Visual Studio Project (Remember to configure File Properties: Copy If newer ): The NLog configuration can also be embedded into the .NET Framework application configuration file (app.config or web.config). This is done by adding an nlog section element under configSections and then use the nlog element. For example:
... The use of an XML namespace is optional, but enables Intellisense in Visual Studio. NLog config XML is case-insensitive for Xml-Nodes and Xml-Attributes, when not using a namespace and is case-sensitive when using a namespace. File locations At startup, NLog searches for its configuration in various files as described below. It loads the first nlog configuration found. Search ends when the first nlog configuration is found. NLog will not perform any logging if configuration is not found. For a stand-alone *.exe application, files are searched as follows: * standard application configuration file app.config (Ex. applicationname.exe.config) * applicationname.exe.nlog in application\u2019s directory * NLog.config in application\u2019s directory * NLog.dll.nlog in a directory where NLog.dll is located (only if NLog isn't installed in the GAC) For an ASP.NET application, files are searched as follows: * standard web application configuration file web.config * web.nlog located in the same directory as web.config * NLog.config in application\u2019s directory * NLog.dll.nlog in a directory where NLog.dll is located (only if NLog isn't installed in the GAC) See also Explicit NLog configuration loading (Includes details about assets -folder for Xamarin Android). Top-level elements You can use the following elements as children to nlog . targets and rules are required in any configuration The others are optional and can be useful in advanced scenarios. * targets \u2013 defines log targets/outputs * rules \u2013 defines log routing rules * extensions \u2013 loads NLog extensions from the *.dll file * include \u2013 includes external configuration file * variable \u2013 sets the value of a configuration variable The simplest configuration consists of one target and one rule ( logger ) that routes messages to the target. Targets The targets section defines log Targets . Each target is represented by a target element. There are two attributes required for each target: * name \u2013 target name * type \u2013 target type \u2013 such as \"File\", \"Database\", \"Mail\". When using namespaces this attribute is named xsi:type . In addition to these attributes, targets usually accept other parameters, which impact the way diagnostic traces are written. Each target has a different set of parameters, they are described in detail on project\u2019s homepage and they are context-sensitive. Intellisense is also available in Visual Studio. For example \u2013 the File target accepts the fileName parameter which defines output file name and the Console target has the error parameter which determines whether the diagnostic traces are written to standard error (stderr) instead of standard output (stdout) of the process. This example demonstrates a targets section which defines multiple targets: two files, one network target and OutputDebugString target: NLog provides many predefined Targets . It\u2019s actually very easy to create your own target - see How to write a custom Target . Log levels Each log entry has a level. And each logger is configured to include or ignore certain levels. A common configuration is to specify the minimum level where that level and higher levels are included. For example, if the minimum level is Info, then Info, Warn, Error and Fatal are logged, but Debug and Trace are ignored. The log levels ordered by severity: LogLevel Ordinal Severity Typical Use Trace 0 Most verbose level. Used for development and seldom enabled in production. Ex. Request-payload, Response-payload, Begin-method-X or End-method-X Debug 1 Debugging the application behavior from internal events of interest. Ex. Executed query, User authenticated, Session expired Info 2 Information about application lifetime events like starting/stopping and configuration changes. Warn 3 Warnings about validation issues or temporary failures that can be recovered. Error 4 Errors where functionality has failed or Exception have been caught. Fatal 5 Most critical level. Application is about to abort. Off 6 Artificial level for disabling logger output The special loglevel Off has the highest ordinal value. It is not used for LogEvents, but can be used for filtering in logging rules . Rules The rules section controls how LogEvents from the Logger-objects are redirected to output targets . Where logger-name and log levels can be used for filtering. When creating a NLog Logger-object then one must provide a logger-name like NLog.LogManager.GetLogger(\"my logger name\") . The logger-name can also be extracted from class-context by using NLog.LogManager.GetCurrentClassLogger() where logger-name becomes \"NameSpace.ClassName\". A single rule is defined with a logger element that filters what Logger-objects to match: name \u2013 Match logger-name of the Logger-object - may include wildcard characters (* and ?) minlevel \u2013 minimum level to log (matches the specified level and levels above) maxlevel \u2013 maximum level to log (matches the specified level and levels below) level \u2013 single level to log. levels - comma separated list of levels to log writeTo \u2013 comma separated list of targets to write to final \u2013 no rules are processed after a final rule matches enabled - set to false to discard the logging rule completely, and reload is required to re-enable. Please note only literal true or false values can be used here; variables cannot be used to set this property. ruleName - rule identifier to allow rule lookup with Configuration.FindRuleByName and Configuration.RemoveRuleByName . Introduced in NLog 4.6.4 finalMinLevel - Loggers matching will be restricted to specified minimum level for following rules. Introduced in NLog 5.0 The example below shows 2 rules that matches ALL Logger-objects independent of their logger-name because of name=\"*\" : - First rule will match LogEvents with minimum LogLevel = Debug (or more severe), and matching LogEvents will be written to the file-target. - Second rule will only match LogEvents with minimum LogLevel = Info (or more severe) and redirect to the console-target. This means a LogEvent with LogLevel = Info will match both rules and be written to both targets. Rules are processed in sequential order. Multiple rules may apply to a logger. Use final to stop processing rules after a match is found. If wanting to dynamically enable / disable a logger-rule at runtime with Layout-support. Then it is recommended not to use enabled , but instead use minLevel and use minLevel=\"Off\" to disable output. See also Semi Dynamic Routing Rules Note: Although a rule is named logger , it does not define a logger. It references one or more loggers based on the name-pattern. Logger Name Filter A rule is mapped to a logger by matching the rule name pattern to a logger name. A rule name attribute may include wildcard characters (* and ?) to match logger names by wildcard matching. * * - matches 0 or more characters * ? - matches exactly 1 character When using NLog.LogManager.GetCurrentClassLogger() then the logger name will have the format \"NameSpace.ClassName\". This makes it very convenient to setup filtering for all classes within a namespace: By using logger-name filtering then one can also redirect output for a single ClassName-logger: One can also reduce the logging from a single ClassName-logger: One can also completely block a single ClassName-logger: Before NLog 4.6 then one could only use wildcards (*) at the beginning and/or at the end of the pattern: Since NLog 4.6, wildcards (* and ?) are allowed in any position. Logger Level Filter A rule defines which log entry level(s) are matched. Entries with other levels will not match this rule. A commonly used specifier is minlevel . The other specifiers allow for more advanced configuration. If a rule contains more than one level-declaring attribute ( level , levels , minlevel and maxlevel ) only the first level-declaring attribute or set is used and the rest are ignored. The level-declaring attributes are processed in the following order: level levels minlevel and maxlevel (these have the same priority) none (all levels are logged) For example: if minlevel=\"Warn\" level=\"Info\" is used, the rule will only use Info In case a rule is marked as final and contains any level-declaring attributes, the final attribute applies only to the specified levels. Dynamic Logger Level Filter The logging rules provides high performance because of their static nature. The options for configuration has been very limited. But recent changes has now been made to improve this: NLog 4.6 added support for using NLog Config Variables to configure level attributes. ( level , minlevel etc): NLog 4.6.4 added support for lookup of Logging Rules using RuleName using Configuration API NLog 4.6.7 added support for using NLog Layout like ${gdc:globalLevel} to dynamically change level attributes at runtime. See also Semi Dynamic Routing Rules Variables NLog Config Variables allows you to simplify configuration by reducing repeated text. Variable can be used to give a human name to a NLog Layout that is commonly used (or is long and complex). This makes it easier to organize and structure the NLog config. Define a custom variable as follows: The value of a variable can be inserted into an attribute value via the ${varname} syntax. A variable value can even be used to define the value of another variable. The following example shows using a pre-defined variable shortdate and defining and using a custom variable logDirectory . With this syntax, a variable must be defined before use. Otherwise configuration initialization will fail. Note ${gdc} can be used used as an alternative to configuration variables, as they work independent of loading / unloading / reloading different NLog configurations. NLog Config variables can operate in two modes: Constant mode - ${varName} Dynamic mode - ${var:varName} (Introduced with NLog 4.1) Constant mode (or static mode) works for all types of properties independent of their type, but they will not react to runtime changes. Dynamic mode only works for properties of the type NLog Layout , and provides the following abilities: Variables can be changed, deleted and created from the Configuration API A default value can be configured for a variable, e.g. ${var:password:default=unknown} By default all variables assigned at runtime are kept even after configuration reloads. Unless having configured keepVariablesOnReload=\"false\" . NLog 4.4 introduced keepVariablesOnReload and before NLog 5.0 the default value was false NLog 5.0 extends NLog config variables to also handle complex Layout types like JsonLayout + CsvLayout. Ex: Layouts and layout renderers One of NLog\u2019s strongest assets is the ability to use layouts . In the simplest form, layouts are texts with embedded tags delimited by ${ and } . The tags are called Layout Renderers and can be used to insert pieces of contextual information into the text. Layouts can be used in many places, for example they can control the format of information written on the screen or sent to a file, but also to control the file names themselves. This is very powerful, which we\u2019ll see in a moment. Let\u2019s assume, that we want to annotate each message written to the console with: * current date and time * name of the class and method that emitted the log message * log level * message text This is very easy: We can make each messages for each logger go to a separate file, as in the following example: As you can see, the ${logger} layout renderer was used in the fileName attribute, which causes each log message to be written to the file whose name includes the logger name. The above example will create the following files: * Name.Space.Class1.txt * Name.Space.Class2.txt * Name.Space.Class3.txt * Other.Name.Space.Class1.txt * Other.Name.Space.Class2.txt * Other.Name.Space.Class3.txt Asynchronous processing and wrapper targets NLog provides wrapper and compound targets which modify other targets\u2019 behavior by adding features like: * asynchronous processing (wrapped target runs in a separate thread) * retry-on-error * load balancing * buffering * filtering * failover (failover) To define a wrapper in the configuration file, simply nest a target node within another target node. You can even wrap a wrapper target - there are no limits on depth. For example, to add asynchronous logging with retry-on-error functionality add this to your configuration file: Because asynchronous processing is a common scenario, NLog supports a shorthand notation to enable it for all targets without the need to specify explicit wrappers. You can simply set async=\"true\" on targets element and all your targets within that element will be wrapped with the AsyncWrapper target. Remember to Flush is very important, when using asynchronous background writing. It ensures all logging is written before application exit. Default wrappers Sometimes we require ALL targets to be wrapped in the same way, for example to add buffering and/or retrying. NLog provides syntax for that. You simply put this element in the section and all your targets will be automatically wrapped with the specified wrapper. Note that applies to the single section only and you can have multiple sections so you can define groups of targets that are wrapped in a similar manner. In the above example we\u2019ve defined two buffered File targets and three asynchronous and retrying Network targets. Default target parameters Similar to default wrappers, NLog provides which enables you to specify default values of target parameters. For example, if you don\u2019t want files to be kept open, you can either add keepFileOpen=\"false\" to each target, as in the following example: Alternatively you can specify a single that applies to all targets in the section. Default parameters are defined on a per-type basis and are applied BEFORE the actual attributes defined in the XML file: Extensions Extensions can be configured to include additional NLog packages or custom ones: Just reference the DLL in the config in the as shown below. The name should not include the .dll Configuration file example: With NLog 5.0 it is also possible to specify fully qualified type-name, instead of needing to update -section. This makes the snippets more isolated: NLog 5.0 no longer automatically scans and loads extensions from assemblies with NLog-prefix. Because it introduced overhead during startup, and failed to work with . See also Register-your-custom-component Automatic reconfiguration The configuration file is read automatically at program startup. In a long running process (such as a Windows service or an ASP.NET application) it\u2019s sometimes desirable to temporarily increase the log level without stopping the application. NLog can monitor logging configuration files and re-read them each time they are modified. To enable this mechanism, you simply add autoReload=\"true\" parameter to the configuration file. ... Note that automatic reconfiguration supports include files, so each time one of the included files is changed, the entire configuration gets reloaded. Just to make it explicit, automatic reloading will NOT stop/recycle the IIS Application Pool. Include files NLog provides an include file feature so that configuration can be stored in multiple files. Like most attributes in NLog config, the file attribute may reference variables. The following example includes a file named the same as the machine that nlog is running on. Setting the attribute ignoreErrors to true prevents a startup failure if the include file cannot be loaded -- file not found, invalid XML, .... Use the Troubleshooting logging section to log errors. This attribute is optional and defaults to false . Since NLog 4.4.2, wildcards ( * ) are allowed. E.g. A larger example can be found here: XML config example Content escaping In the configuration file some characters needs to be escaped. Because it XML file, the < and > brackets should be escaped with < and > . This also holds for the attribute values, like a condition. Inside a layout we need to escape the } bracket and the colon : should be escaped because: : is the value separator. } is the end of the layout Nested layout renderers doesn't need escaping. Also the backslash doesn't need an escape. Examples: ${appdomain:format={1\\}{0\\}} (escape of } ) ${rot13:inner=${scopenested:topFrames=3:separator=x}} (no escaping needed) ${when:when=1 == 1:Inner=Test\\: Hello} (escape of : ) Troubleshooting logging If log output is missing, the issue may be related to configuration loading, logging rules, target initialization, filesystem permissions, deployment configuration, or application execution. NLog provides several settings that can help diagnose logging issues: \u2014 Enables NLog InternalLogger output. Internal logging is often the most useful diagnostic tool when troubleshooting configuration loading, log routing, and target-writing issues. \u2014 Causes configuration-loading errors to be surfaced as exceptions instead of being silently ignored. This setting is recommended during troubleshooting and is often appropriate in production environments where successful loading of the logging configuration is required. \u2014 Causes runtime logging exceptions to be propagated to the calling application instead of being handled internally. This setting is intended only for troubleshooting and unit testing. Do not enable it in production environments because logging failures may cause application errors or crashes. For systematic troubleshooting steps, examples, and common causes of missing log output, see Logging-troubleshooting .","title":"Configuration file"},{"location":"Configuration-file/#contents","text":"NLog config XML File locations Top-level elements Targets Log levels Rules Variables Layouts and layout renderers Asynchronous processing and wrapper targets Default wrappers Default target parameters Extensions Automatic reconfiguration Include files Content escaping Troubleshooting logging","title":"Contents"},{"location":"Configuration-file/#nlog-config-xml","text":"Example XML for a stand-alone NLog.config that can be added to Visual Studio Project (Remember to configure File Properties: Copy If newer ): The NLog configuration can also be embedded into the .NET Framework application configuration file (app.config or web.config). This is done by adding an nlog section element under configSections and then use the nlog element. For example:
... The use of an XML namespace is optional, but enables Intellisense in Visual Studio. NLog config XML is case-insensitive for Xml-Nodes and Xml-Attributes, when not using a namespace and is case-sensitive when using a namespace.","title":"NLog config XML"},{"location":"Configuration-file/#file-locations","text":"At startup, NLog searches for its configuration in various files as described below. It loads the first nlog configuration found. Search ends when the first nlog configuration is found. NLog will not perform any logging if configuration is not found. For a stand-alone *.exe application, files are searched as follows: * standard application configuration file app.config (Ex. applicationname.exe.config) * applicationname.exe.nlog in application\u2019s directory * NLog.config in application\u2019s directory * NLog.dll.nlog in a directory where NLog.dll is located (only if NLog isn't installed in the GAC) For an ASP.NET application, files are searched as follows: * standard web application configuration file web.config * web.nlog located in the same directory as web.config * NLog.config in application\u2019s directory * NLog.dll.nlog in a directory where NLog.dll is located (only if NLog isn't installed in the GAC) See also Explicit NLog configuration loading (Includes details about assets -folder for Xamarin Android).","title":"File locations"},{"location":"Configuration-file/#top-level-elements","text":"You can use the following elements as children to nlog . targets and rules are required in any configuration The others are optional and can be useful in advanced scenarios. * targets \u2013 defines log targets/outputs * rules \u2013 defines log routing rules * extensions \u2013 loads NLog extensions from the *.dll file * include \u2013 includes external configuration file * variable \u2013 sets the value of a configuration variable The simplest configuration consists of one target and one rule ( logger ) that routes messages to the target.","title":"Top-level elements"},{"location":"Configuration-file/#targets","text":"The targets section defines log Targets . Each target is represented by a target element. There are two attributes required for each target: * name \u2013 target name * type \u2013 target type \u2013 such as \"File\", \"Database\", \"Mail\". When using namespaces this attribute is named xsi:type . In addition to these attributes, targets usually accept other parameters, which impact the way diagnostic traces are written. Each target has a different set of parameters, they are described in detail on project\u2019s homepage and they are context-sensitive. Intellisense is also available in Visual Studio. For example \u2013 the File target accepts the fileName parameter which defines output file name and the Console target has the error parameter which determines whether the diagnostic traces are written to standard error (stderr) instead of standard output (stdout) of the process. This example demonstrates a targets section which defines multiple targets: two files, one network target and OutputDebugString target: NLog provides many predefined Targets . It\u2019s actually very easy to create your own target - see How to write a custom Target .","title":"Targets"},{"location":"Configuration-file/#log-levels","text":"Each log entry has a level. And each logger is configured to include or ignore certain levels. A common configuration is to specify the minimum level where that level and higher levels are included. For example, if the minimum level is Info, then Info, Warn, Error and Fatal are logged, but Debug and Trace are ignored. The log levels ordered by severity: LogLevel Ordinal Severity Typical Use Trace 0 Most verbose level. Used for development and seldom enabled in production. Ex. Request-payload, Response-payload, Begin-method-X or End-method-X Debug 1 Debugging the application behavior from internal events of interest. Ex. Executed query, User authenticated, Session expired Info 2 Information about application lifetime events like starting/stopping and configuration changes. Warn 3 Warnings about validation issues or temporary failures that can be recovered. Error 4 Errors where functionality has failed or Exception have been caught. Fatal 5 Most critical level. Application is about to abort. Off 6 Artificial level for disabling logger output The special loglevel Off has the highest ordinal value. It is not used for LogEvents, but can be used for filtering in logging rules .","title":"Log levels"},{"location":"Configuration-file/#rules","text":"The rules section controls how LogEvents from the Logger-objects are redirected to output targets . Where logger-name and log levels can be used for filtering. When creating a NLog Logger-object then one must provide a logger-name like NLog.LogManager.GetLogger(\"my logger name\") . The logger-name can also be extracted from class-context by using NLog.LogManager.GetCurrentClassLogger() where logger-name becomes \"NameSpace.ClassName\". A single rule is defined with a logger element that filters what Logger-objects to match: name \u2013 Match logger-name of the Logger-object - may include wildcard characters (* and ?) minlevel \u2013 minimum level to log (matches the specified level and levels above) maxlevel \u2013 maximum level to log (matches the specified level and levels below) level \u2013 single level to log. levels - comma separated list of levels to log writeTo \u2013 comma separated list of targets to write to final \u2013 no rules are processed after a final rule matches enabled - set to false to discard the logging rule completely, and reload is required to re-enable. Please note only literal true or false values can be used here; variables cannot be used to set this property. ruleName - rule identifier to allow rule lookup with Configuration.FindRuleByName and Configuration.RemoveRuleByName . Introduced in NLog 4.6.4 finalMinLevel - Loggers matching will be restricted to specified minimum level for following rules. Introduced in NLog 5.0 The example below shows 2 rules that matches ALL Logger-objects independent of their logger-name because of name=\"*\" : - First rule will match LogEvents with minimum LogLevel = Debug (or more severe), and matching LogEvents will be written to the file-target. - Second rule will only match LogEvents with minimum LogLevel = Info (or more severe) and redirect to the console-target. This means a LogEvent with LogLevel = Info will match both rules and be written to both targets. Rules are processed in sequential order. Multiple rules may apply to a logger. Use final to stop processing rules after a match is found. If wanting to dynamically enable / disable a logger-rule at runtime with Layout-support. Then it is recommended not to use enabled , but instead use minLevel and use minLevel=\"Off\" to disable output. See also Semi Dynamic Routing Rules Note: Although a rule is named logger , it does not define a logger. It references one or more loggers based on the name-pattern.","title":"Rules"},{"location":"Configuration-file/#logger-name-filter","text":"A rule is mapped to a logger by matching the rule name pattern to a logger name. A rule name attribute may include wildcard characters (* and ?) to match logger names by wildcard matching. * * - matches 0 or more characters * ? - matches exactly 1 character When using NLog.LogManager.GetCurrentClassLogger() then the logger name will have the format \"NameSpace.ClassName\". This makes it very convenient to setup filtering for all classes within a namespace: By using logger-name filtering then one can also redirect output for a single ClassName-logger: One can also reduce the logging from a single ClassName-logger: One can also completely block a single ClassName-logger: Before NLog 4.6 then one could only use wildcards (*) at the beginning and/or at the end of the pattern: Since NLog 4.6, wildcards (* and ?) are allowed in any position. ","title":"Logger Name Filter"},{"location":"Configuration-file/#logger-level-filter","text":"A rule defines which log entry level(s) are matched. Entries with other levels will not match this rule. A commonly used specifier is minlevel . The other specifiers allow for more advanced configuration. If a rule contains more than one level-declaring attribute ( level , levels , minlevel and maxlevel ) only the first level-declaring attribute or set is used and the rest are ignored. The level-declaring attributes are processed in the following order: level levels minlevel and maxlevel (these have the same priority) none (all levels are logged) For example: if minlevel=\"Warn\" level=\"Info\" is used, the rule will only use Info In case a rule is marked as final and contains any level-declaring attributes, the final attribute applies only to the specified levels.","title":"Logger Level Filter"},{"location":"Configuration-file/#dynamic-logger-level-filter","text":"The logging rules provides high performance because of their static nature. The options for configuration has been very limited. But recent changes has now been made to improve this: NLog 4.6 added support for using NLog Config Variables to configure level attributes. ( level , minlevel etc): NLog 4.6.4 added support for lookup of Logging Rules using RuleName using Configuration API NLog 4.6.7 added support for using NLog Layout like ${gdc:globalLevel} to dynamically change level attributes at runtime. See also Semi Dynamic Routing Rules","title":"Dynamic Logger Level Filter"},{"location":"Configuration-file/#variables","text":"NLog Config Variables allows you to simplify configuration by reducing repeated text. Variable can be used to give a human name to a NLog Layout that is commonly used (or is long and complex). This makes it easier to organize and structure the NLog config. Define a custom variable as follows: The value of a variable can be inserted into an attribute value via the ${varname} syntax. A variable value can even be used to define the value of another variable. The following example shows using a pre-defined variable shortdate and defining and using a custom variable logDirectory . With this syntax, a variable must be defined before use. Otherwise configuration initialization will fail. Note ${gdc} can be used used as an alternative to configuration variables, as they work independent of loading / unloading / reloading different NLog configurations. NLog Config variables can operate in two modes: Constant mode - ${varName} Dynamic mode - ${var:varName} (Introduced with NLog 4.1) Constant mode (or static mode) works for all types of properties independent of their type, but they will not react to runtime changes. Dynamic mode only works for properties of the type NLog Layout , and provides the following abilities: Variables can be changed, deleted and created from the Configuration API A default value can be configured for a variable, e.g. ${var:password:default=unknown} By default all variables assigned at runtime are kept even after configuration reloads. Unless having configured keepVariablesOnReload=\"false\" . NLog 4.4 introduced keepVariablesOnReload and before NLog 5.0 the default value was false NLog 5.0 extends NLog config variables to also handle complex Layout types like JsonLayout + CsvLayout. Ex: ","title":"Variables"},{"location":"Configuration-file/#layouts-and-layout-renderers","text":"One of NLog\u2019s strongest assets is the ability to use layouts . In the simplest form, layouts are texts with embedded tags delimited by ${ and } . The tags are called Layout Renderers and can be used to insert pieces of contextual information into the text. Layouts can be used in many places, for example they can control the format of information written on the screen or sent to a file, but also to control the file names themselves. This is very powerful, which we\u2019ll see in a moment. Let\u2019s assume, that we want to annotate each message written to the console with: * current date and time * name of the class and method that emitted the log message * log level * message text This is very easy: We can make each messages for each logger go to a separate file, as in the following example: As you can see, the ${logger} layout renderer was used in the fileName attribute, which causes each log message to be written to the file whose name includes the logger name. The above example will create the following files: * Name.Space.Class1.txt * Name.Space.Class2.txt * Name.Space.Class3.txt * Other.Name.Space.Class1.txt * Other.Name.Space.Class2.txt * Other.Name.Space.Class3.txt","title":"Layouts and layout renderers"},{"location":"Configuration-file/#asynchronous-processing-and-wrapper-targets","text":"NLog provides wrapper and compound targets which modify other targets\u2019 behavior by adding features like: * asynchronous processing (wrapped target runs in a separate thread) * retry-on-error * load balancing * buffering * filtering * failover (failover) To define a wrapper in the configuration file, simply nest a target node within another target node. You can even wrap a wrapper target - there are no limits on depth. For example, to add asynchronous logging with retry-on-error functionality add this to your configuration file: Because asynchronous processing is a common scenario, NLog supports a shorthand notation to enable it for all targets without the need to specify explicit wrappers. You can simply set async=\"true\" on targets element and all your targets within that element will be wrapped with the AsyncWrapper target. Remember to Flush is very important, when using asynchronous background writing. It ensures all logging is written before application exit.","title":"Asynchronous processing and wrapper targets"},{"location":"Configuration-file/#default-wrappers","text":"Sometimes we require ALL targets to be wrapped in the same way, for example to add buffering and/or retrying. NLog provides syntax for that. You simply put this element in the section and all your targets will be automatically wrapped with the specified wrapper. Note that applies to the single section only and you can have multiple sections so you can define groups of targets that are wrapped in a similar manner. In the above example we\u2019ve defined two buffered File targets and three asynchronous and retrying Network targets.","title":"Default wrappers"},{"location":"Configuration-file/#default-target-parameters","text":"Similar to default wrappers, NLog provides which enables you to specify default values of target parameters. For example, if you don\u2019t want files to be kept open, you can either add keepFileOpen=\"false\" to each target, as in the following example: Alternatively you can specify a single that applies to all targets in the section. Default parameters are defined on a per-type basis and are applied BEFORE the actual attributes defined in the XML file: ","title":"Default target parameters"},{"location":"Configuration-file/#extensions","text":"Extensions can be configured to include additional NLog packages or custom ones: Just reference the DLL in the config in the as shown below. The name should not include the .dll Configuration file example: With NLog 5.0 it is also possible to specify fully qualified type-name, instead of needing to update -section. This makes the snippets more isolated: NLog 5.0 no longer automatically scans and loads extensions from assemblies with NLog-prefix. Because it introduced overhead during startup, and failed to work with . See also Register-your-custom-component","title":"Extensions"},{"location":"Configuration-file/#automatic-reconfiguration","text":"The configuration file is read automatically at program startup. In a long running process (such as a Windows service or an ASP.NET application) it\u2019s sometimes desirable to temporarily increase the log level without stopping the application. NLog can monitor logging configuration files and re-read them each time they are modified. To enable this mechanism, you simply add autoReload=\"true\" parameter to the configuration file. ... Note that automatic reconfiguration supports include files, so each time one of the included files is changed, the entire configuration gets reloaded. Just to make it explicit, automatic reloading will NOT stop/recycle the IIS Application Pool.","title":"Automatic reconfiguration"},{"location":"Configuration-file/#include-files","text":"NLog provides an include file feature so that configuration can be stored in multiple files. Like most attributes in NLog config, the file attribute may reference variables. The following example includes a file named the same as the machine that nlog is running on. Setting the attribute ignoreErrors to true prevents a startup failure if the include file cannot be loaded -- file not found, invalid XML, .... Use the Troubleshooting logging section to log errors. This attribute is optional and defaults to false . Since NLog 4.4.2, wildcards ( * ) are allowed. E.g. A larger example can be found here: XML config example","title":"Include files"},{"location":"Configuration-file/#content-escaping","text":"In the configuration file some characters needs to be escaped. Because it XML file, the < and > brackets should be escaped with < and > . This also holds for the attribute values, like a condition. Inside a layout we need to escape the } bracket and the colon : should be escaped because: : is the value separator. } is the end of the layout Nested layout renderers doesn't need escaping. Also the backslash doesn't need an escape. Examples: ${appdomain:format={1\\}{0\\}} (escape of } ) ${rot13:inner=${scopenested:topFrames=3:separator=x}} (no escaping needed) ${when:when=1 == 1:Inner=Test\\: Hello} (escape of : )","title":"Content escaping"},{"location":"Configuration-file/#troubleshooting-logging","text":"If log output is missing, the issue may be related to configuration loading, logging rules, target initialization, filesystem permissions, deployment configuration, or application execution. NLog provides several settings that can help diagnose logging issues: \u2014 Enables NLog InternalLogger output. Internal logging is often the most useful diagnostic tool when troubleshooting configuration loading, log routing, and target-writing issues. \u2014 Causes configuration-loading errors to be surfaced as exceptions instead of being silently ignored. This setting is recommended during troubleshooting and is often appropriate in production environments where successful loading of the logging configuration is required. \u2014 Causes runtime logging exceptions to be propagated to the calling application instead of being handled internally. This setting is intended only for troubleshooting and unit testing. Do not enable it in production environments because logging failures may cause application errors or crashes. For systematic troubleshooting steps, examples, and common causes of missing log output, see Logging-troubleshooting .","title":"Troubleshooting logging"},{"location":"Configure-NLog/","text":"Moved here https://github.com/NLog/NLog/wiki/Configuration-file","title":"Configure NLog"},{"location":"Configure-component-logging/","text":"The default approach for managing Loggers via the global singleton LogManager class in NLog. It works well for homogeneous applications where the main application and all the extension components are configured via a single configuration file. By including the component class-namespace in the Logger-name (Happens automatically when using NLog.LogManager.GetCurrentClassLogger() ), then it is easy to configure NLog Logging-Rules to route to the wanted destination-target for the plugin (Ex. filename=\"Plugin-${logger}.log\" ). Isolated Logger Property If the component is complex and uses many Logger-instances, then one can consider to also imbue the component Logger-instance with a common LogEvent-PropertyName: var pluginLogger = NLog.LogManager.GetLogger(componentName).WithProperty(\"ComponentName\", componentName); Then it is possible to include the component-identifier in the target output. Ex ${event-properties:ComponentName:whenEmpty=Core} See also ${event-properties} Isolated LogFactory But sometimes you want to create a separate logging configuration, just for a particular component, plugin or extension. Instead of using LogManager (which is global to an application) then one can use isolated LogFactory object-instance that is local to your component/plugin. It allows you to have multiple LogFactory -instances, where each have their own isolated logging configuration. When creating LogFactory you need to explicitly pass the configuration (either from a file or by programmatically constructing targets and rules) as in the following example: internal class MyLogManager { // A Logger dispenser for the current assembly (Remember to call Flush on application exit) public static LogFactory Instance { get { return _instance.Value; } } private static Lazy _instance = new Lazy(BuildLogFactory); // // Use a config file located next to our current assembly dll // eg, if the running assembly is c:\\path\\to\\MyComponent.dll // the config filepath will be c:\\path\\to\\MyComponent.nlog // // WARNING: This will not be appropriate for assemblies in the GAC // private static LogFactory BuildLogFactory() { // Use name of current assembly to construct NLog config filename Assembly thisAssembly = Assembly.GetExecutingAssembly(); string configFilePath = Path.ChangeExtension(thisAssembly.Location, \".nlog\"); LogFactory logFactory = new LogFactory(); logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory); return logFactory; } } Then all you need to do is to create loggers with: Logger logger = MyLogManager.Instance.GetLogger(\"name\"); or Logger logger = MyLogManager.Instance.GetCurrentClassLogger(); If you want multiple assemblies to share this MyLogManager \u2013 just make it a public class and get others to use it. NLog LogFactory will attempt to automatically shutdown together with the AppDomain / ProcessExit. But it is recommended to shutdown the isolate LogFactory in the plugin-dispose-stage by calling LogFactory.Shutdown() . See Also: Explicit NLog configuration loading","title":"Configure component logging"},{"location":"Configure-component-logging/#isolated-logger-property","text":"If the component is complex and uses many Logger-instances, then one can consider to also imbue the component Logger-instance with a common LogEvent-PropertyName: var pluginLogger = NLog.LogManager.GetLogger(componentName).WithProperty(\"ComponentName\", componentName); Then it is possible to include the component-identifier in the target output. Ex ${event-properties:ComponentName:whenEmpty=Core} See also ${event-properties}","title":"Isolated Logger Property"},{"location":"Configure-component-logging/#isolated-logfactory","text":"But sometimes you want to create a separate logging configuration, just for a particular component, plugin or extension. Instead of using LogManager (which is global to an application) then one can use isolated LogFactory object-instance that is local to your component/plugin. It allows you to have multiple LogFactory -instances, where each have their own isolated logging configuration. When creating LogFactory you need to explicitly pass the configuration (either from a file or by programmatically constructing targets and rules) as in the following example: internal class MyLogManager { // A Logger dispenser for the current assembly (Remember to call Flush on application exit) public static LogFactory Instance { get { return _instance.Value; } } private static Lazy _instance = new Lazy(BuildLogFactory); // // Use a config file located next to our current assembly dll // eg, if the running assembly is c:\\path\\to\\MyComponent.dll // the config filepath will be c:\\path\\to\\MyComponent.nlog // // WARNING: This will not be appropriate for assemblies in the GAC // private static LogFactory BuildLogFactory() { // Use name of current assembly to construct NLog config filename Assembly thisAssembly = Assembly.GetExecutingAssembly(); string configFilePath = Path.ChangeExtension(thisAssembly.Location, \".nlog\"); LogFactory logFactory = new LogFactory(); logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory); return logFactory; } } Then all you need to do is to create loggers with: Logger logger = MyLogManager.Instance.GetLogger(\"name\"); or Logger logger = MyLogManager.Instance.GetCurrentClassLogger(); If you want multiple assemblies to share this MyLogManager \u2013 just make it a public class and get others to use it. NLog LogFactory will attempt to automatically shutdown together with the AppDomain / ProcessExit. But it is recommended to shutdown the isolate LogFactory in the plugin-dispose-stage by calling LogFactory.Shutdown() . See Also: Explicit NLog configuration loading","title":"Isolated LogFactory"},{"location":"Configure-from-code/","text":"NLog can be also configured programmatically. All options match with the attribute names in the XML config, so for all config options you could check https://nlog-project.org/config/ There is also a SHFB docs, see https://nlog-project.org/documentation/ Fluent API Example NLog 5.0 introduces a Fluent-Configuration-API so you can do this instead: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: \"file.txt\"); }); Old Style Example var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget(\"logfile\") { FileName = \"file.txt\" }; var logconsole = new NLog.Targets.ConsoleTarget(\"logconsole\"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; Extended Features Passing Custom Values There are many ways to capture current Context and output it to the final target. Simple example: logger.Info(\"Message with {myProperty}\", \"myValue\"); Render with ${event-properties:myProperty} Add this to Layout, e.g. var fileTarget = new FileTarget(\"target2\") { FileName = \"${basedir}/file.txt\", Layout = \"${longdate} ${level} ${message} ${exception} ${event-properties:myProperty}\" }; For many more examples, see ${event-properties} layout renderer. Creating dynamic Layouts NLog Layout will implicitly convert from string-objects. It will automatically parse the string and compile it into the recognized Layout-Renderers . NLog will perform validation when parsing, but errors detected will be swallowed unless having enabled LogManager.ThrowConfigExceptions . But one can also force NLog to throw parsing error no matter what: var layout = NLog.Layouts.Layout.FromString(\"${evil}\", throwConfigExceptions: true); // will throw NLog 4.7 also allows you to generate a Layout from a simple lambda-method: var unixTime = NLog.Layouts.Layout.FromMethod(logEvent => ((DateTimeOffset)logEvent.TimeStamp).ToUnixTimeSeconds().ToString()); var jsonLayout = NLog.Layouts.JsonLayout() { Attributes = { new NLog.Layouts.JsonAttribute(\"unixtime\", unixTime) { Encode = false } } }; !! NOTICE !! Ensure that custom method given to Layout.FromMethod is very simple. Deadlock or StackOverflow can occur if performing complex logic that triggers new logevents or acquiring locks. Update config in code It is possible to dive into the NLog LoggingConfiguration and assign properties directly. But NLog is much happier about using NLog Layout logic when possible. Example: Then in code one can just update the GDC -item, and it will take effect right away: NLog.GlobalDiagnosticsContext.Set(\"CompanyName\", \"SuperPower\"); This removes the need to know the exact NLog-target names in the NLog.config, so it decouples the logic even further and makes it more resilient. This will also work excellent together with autoReload=\"true\" , as you don't have to re-apply the same settings again, as it will happen automatically. This can also be used for adjusting logging rules dynamically at runtime. But if you really want to get your hands dirty, then here you go: var configuration = LogManager.Configuration; // Update single target var myFileTarget = configuration.FindTargetByName(\"myTargetName\"); if (myFileTarget != null) myFileTarget.FileName = \"SuperPower\" + \"_${shortdate}.log\"; LogManager.Configuration = configuration; // re-init // Update all targets foreach (var fileTarget = configuration.AllTargets.OfType()) { fileTarget.FileName = \"SuperPower\" + \"_${shortdate}.log\"; } LogManager.Configuration = configuration; // re-init Combine nlog.config and config from code Please note that combining the config file (nlog.config) and changing it in code, the reload of nlog.config could undo your changes. If you combine both, then reapply the changes on the reload event. E.g. // On start of your program UpdateConfig(); LogManager.ConfigurationChanged += (sender, e) => { if (e.ActivatedConfiguration != null) { //Re apply if config reloaded UpdateConfig(); } }; Where UpdateConfig is public void UpdateConfig() { // Do NOT set LogManager.Configuration because that will cause recursion and stackoverflow var fileTarget = LogManager.Configuration.FindTargetByName(\"myTargetName\"); fileTarget.FileName = \"${basedir}/file.log\"; LogManager.ReconfigExistingLoggers(); // Soft refresh } Instead of trying to perform patching of NLog-configuration, then it is recommended to make use of NLog Layouts for Target- and LoggingRule -configuration forexample using ${gdc}","title":"Configure from code"},{"location":"Configure-from-code/#fluent-api-example","text":"NLog 5.0 introduces a Fluent-Configuration-API so you can do this instead: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: \"file.txt\"); });","title":"Fluent API Example"},{"location":"Configure-from-code/#old-style-example","text":"var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget(\"logfile\") { FileName = \"file.txt\" }; var logconsole = new NLog.Targets.ConsoleTarget(\"logconsole\"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config;","title":"Old Style Example"},{"location":"Configure-from-code/#extended-features","text":"","title":"Extended Features"},{"location":"Configure-from-code/#passing-custom-values","text":"There are many ways to capture current Context and output it to the final target. Simple example: logger.Info(\"Message with {myProperty}\", \"myValue\"); Render with ${event-properties:myProperty} Add this to Layout, e.g. var fileTarget = new FileTarget(\"target2\") { FileName = \"${basedir}/file.txt\", Layout = \"${longdate} ${level} ${message} ${exception} ${event-properties:myProperty}\" }; For many more examples, see ${event-properties} layout renderer.","title":"Passing Custom Values"},{"location":"Configure-from-code/#creating-dynamic-layouts","text":"NLog Layout will implicitly convert from string-objects. It will automatically parse the string and compile it into the recognized Layout-Renderers . NLog will perform validation when parsing, but errors detected will be swallowed unless having enabled LogManager.ThrowConfigExceptions . But one can also force NLog to throw parsing error no matter what: var layout = NLog.Layouts.Layout.FromString(\"${evil}\", throwConfigExceptions: true); // will throw NLog 4.7 also allows you to generate a Layout from a simple lambda-method: var unixTime = NLog.Layouts.Layout.FromMethod(logEvent => ((DateTimeOffset)logEvent.TimeStamp).ToUnixTimeSeconds().ToString()); var jsonLayout = NLog.Layouts.JsonLayout() { Attributes = { new NLog.Layouts.JsonAttribute(\"unixtime\", unixTime) { Encode = false } } }; !! NOTICE !! Ensure that custom method given to Layout.FromMethod is very simple. Deadlock or StackOverflow can occur if performing complex logic that triggers new logevents or acquiring locks.","title":"Creating dynamic Layouts"},{"location":"Configure-from-code/#update-config-in-code","text":"It is possible to dive into the NLog LoggingConfiguration and assign properties directly. But NLog is much happier about using NLog Layout logic when possible. Example: Then in code one can just update the GDC -item, and it will take effect right away: NLog.GlobalDiagnosticsContext.Set(\"CompanyName\", \"SuperPower\"); This removes the need to know the exact NLog-target names in the NLog.config, so it decouples the logic even further and makes it more resilient. This will also work excellent together with autoReload=\"true\" , as you don't have to re-apply the same settings again, as it will happen automatically. This can also be used for adjusting logging rules dynamically at runtime. But if you really want to get your hands dirty, then here you go: var configuration = LogManager.Configuration; // Update single target var myFileTarget = configuration.FindTargetByName(\"myTargetName\"); if (myFileTarget != null) myFileTarget.FileName = \"SuperPower\" + \"_${shortdate}.log\"; LogManager.Configuration = configuration; // re-init // Update all targets foreach (var fileTarget = configuration.AllTargets.OfType()) { fileTarget.FileName = \"SuperPower\" + \"_${shortdate}.log\"; } LogManager.Configuration = configuration; // re-init","title":"Update config in code"},{"location":"Configure-from-code/#combine-nlogconfig-and-config-from-code","text":"Please note that combining the config file (nlog.config) and changing it in code, the reload of nlog.config could undo your changes. If you combine both, then reapply the changes on the reload event. E.g. // On start of your program UpdateConfig(); LogManager.ConfigurationChanged += (sender, e) => { if (e.ActivatedConfiguration != null) { //Re apply if config reloaded UpdateConfig(); } }; Where UpdateConfig is public void UpdateConfig() { // Do NOT set LogManager.Configuration because that will cause recursion and stackoverflow var fileTarget = LogManager.Configuration.FindTargetByName(\"myTargetName\"); fileTarget.FileName = \"${basedir}/file.log\"; LogManager.ReconfigExistingLoggers(); // Soft refresh } Instead of trying to perform patching of NLog-configuration, then it is recommended to make use of NLog Layouts for Target- and LoggingRule -configuration forexample using ${gdc}","title":"Combine nlog.config and config from code"},{"location":"Console-target/","text":"Writes log messages to the console. Platforms Supported: All There is also the colorful ColoredConsole-Target that can highlight single words or color entire rows. Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} footer - Footer. Layout header - Header. Layout Console Options encoding - File encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Defaults to Encoding.Default . Introduced in NLog 4.0. StdErr - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). Layout Default: false Before NLog v5.0 the property was named error . Before NLog v6.0 the property was boolean instead of NLog Layout detectConsoleAvailable - Indicates whether the console target should disable itself when no console detected. Boolean Default: false Introduced in NLog 4.3.10 with default: true , then NLog 4.4 changed default to false . autoFlush - Performs explicit flush after every console write. Useful if having redirected to custom console-stream that doesn't has autoflush enabled. Boolean. Default = False. Introduced in NLog 4.6.3 ForceWriteLine - Call Console.WriteLine instead of writing directly to buffer using Console.Write . Available if doing console-redirection that requires Console.WriteLine . Default: False . Before NLog v6.0 the property was named WriteBuffer which was introduced with v4.6.8. Example ","title":"Console target"},{"location":"Console-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Console-target/#parameters","text":"","title":"Parameters"},{"location":"Console-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Console-target/#layout-options","text":"layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} footer - Footer. Layout header - Header. Layout","title":"Layout Options"},{"location":"Console-target/#console-options","text":"encoding - File encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Defaults to Encoding.Default . Introduced in NLog 4.0. StdErr - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). Layout Default: false Before NLog v5.0 the property was named error . Before NLog v6.0 the property was boolean instead of NLog Layout detectConsoleAvailable - Indicates whether the console target should disable itself when no console detected. Boolean Default: false Introduced in NLog 4.3.10 with default: true , then NLog 4.4 changed default to false . autoFlush - Performs explicit flush after every console write. Useful if having redirected to custom console-stream that doesn't has autoflush enabled. Boolean. Default = False. Introduced in NLog 4.6.3 ForceWriteLine - Call Console.WriteLine instead of writing directly to buffer using Console.Write . Available if doing console-redirection that requires Console.WriteLine . Default: False . Before NLog v6.0 the property was named WriteBuffer which was introduced with v4.6.8.","title":"Console Options"},{"location":"Console-target/#example","text":"","title":"Example"},{"location":"Context/","text":"Besides the information included with the log message, then there are several options for capturing additional local context state with the LogEvent: ${logger} - Name of the Logger-object used for writing LogEvent. ${level} - LogEvent Level of importance / severity. ${exception} - Exception object included with the LogEvent. ${event-properties} - LogEvent Properties - From Structured logging or explicity added to LogEventInfo.Properties . ${gdc} - Global Diagnostic Context for application-wide static context assigned at startup. ${scopeproperty} - Provide context properties for the current thread with async Task-support Replaces the legacy ${mdlc} and ${mdc} from before NLog 5.0 ${scopenested} - Provide nested scope details for the current thread with async Task-support Replaces the legacy ${ndlc} and ${ndc} from before NLog 5.0 ${activity:TraceId} - Using System.Diagnostics.Activity.Current for OpenTelemetry TraceId / SpanId. ${aspnet-item} - ASP.NET Item variable from HttpContext.Items dictionary. More LayoutRenderers LogEvent Properties See Structured logging for more details of using the log-message to inject additional properties: logger.Info(\"Say hello to {myProperty}\", \"myValue\"); One can also use the Fluent-Logger-API : logger.ForInfoEvent().Message(\"Hello\").Property(\"myProperty\", \"myValue\").Log(); Or explicitly create the LogEvent: var logEvent = LogEventInfo() { Level = LogLevel.Info }; logEvent.Properties[\"myProperty\"] = \"myValue\"; logger.Log(logEvent); It is also possible to inject properties into the Logger-object, so they are always added: logger.WithProperty(\"myProperty\", \"myValue\").Info(\"Hello\"); // NLog 4.6.3+ LogEvent Properties can be rendered with ${event-properties:item=myProperty} , ${all-event-properties} or JsonLayout . ScopeContext Properties Handles thread context properties for a scope. Ex. assigning RequestId for the method-call-scope: using (NLog.ScopeContext.PushProperty(\"myRequestId\", Guid.NewGuid())) { logger.Info(\"myLogEvent\"); } Thread Context Properties can be rendered with ${scopeproperty:item=myRequestId} or JsonLayout with IncludeScopeProperties=true . Note when using Microsoft Extension Logging ILogger.BeginScope with NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided properties. ScopeContext Nested States Handles thread context naming of a scope. Ex. assigning MethodName for the method-call-scope: using (NLog.ScopeContext.PushNestedState(\"myMethodName\")) { logger.Info(\"myLogEvent\"); } Thread Scope names can be rendered with ${scopenested} . Note when using Microsoft Extension Logging ILogger.BeginScope with NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided scope-name. .NET Core logging When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : using (_logger.BeginScope(new[] { new KeyValuePair(\"userid\", request.UserId) })) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output } NLog.Extensions.Logging v5.3.7 adds support for using ValueTuple for single scope-property (better performance): using (_logger.BeginScope((\"userid\", request.UserId))) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output } Context for Code or HttpContext Need other context from code or from the HttpContext (ASP.NET or ASP.NET Core). You could write a custom layout renderer with a single line, see How to write a custom layout renderer .","title":"Context"},{"location":"Context/#logevent-properties","text":"See Structured logging for more details of using the log-message to inject additional properties: logger.Info(\"Say hello to {myProperty}\", \"myValue\"); One can also use the Fluent-Logger-API : logger.ForInfoEvent().Message(\"Hello\").Property(\"myProperty\", \"myValue\").Log(); Or explicitly create the LogEvent: var logEvent = LogEventInfo() { Level = LogLevel.Info }; logEvent.Properties[\"myProperty\"] = \"myValue\"; logger.Log(logEvent); It is also possible to inject properties into the Logger-object, so they are always added: logger.WithProperty(\"myProperty\", \"myValue\").Info(\"Hello\"); // NLog 4.6.3+ LogEvent Properties can be rendered with ${event-properties:item=myProperty} , ${all-event-properties} or JsonLayout .","title":"LogEvent Properties"},{"location":"Context/#scopecontext-properties","text":"Handles thread context properties for a scope. Ex. assigning RequestId for the method-call-scope: using (NLog.ScopeContext.PushProperty(\"myRequestId\", Guid.NewGuid())) { logger.Info(\"myLogEvent\"); } Thread Context Properties can be rendered with ${scopeproperty:item=myRequestId} or JsonLayout with IncludeScopeProperties=true . Note when using Microsoft Extension Logging ILogger.BeginScope with NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided properties.","title":"ScopeContext Properties"},{"location":"Context/#scopecontext-nested-states","text":"Handles thread context naming of a scope. Ex. assigning MethodName for the method-call-scope: using (NLog.ScopeContext.PushNestedState(\"myMethodName\")) { logger.Info(\"myLogEvent\"); } Thread Scope names can be rendered with ${scopenested} . Note when using Microsoft Extension Logging ILogger.BeginScope with NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided scope-name.","title":"ScopeContext Nested States"},{"location":"Context/#net-core-logging","text":"When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : using (_logger.BeginScope(new[] { new KeyValuePair(\"userid\", request.UserId) })) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output } NLog.Extensions.Logging v5.3.7 adds support for using ValueTuple for single scope-property (better performance): using (_logger.BeginScope((\"userid\", request.UserId))) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output }","title":".NET Core logging"},{"location":"Context/#context-for-code-or-httpcontext","text":"Need other context from code or from the HttpContext (ASP.NET or ASP.NET Core). You could write a custom layout renderer with a single line, see How to write a custom layout renderer .","title":"Context for Code or HttpContext"},{"location":"Counter-layout-renderer/","text":"A counter value (increases on each layout rendering). Platforms Supported: All Configuration Syntax Starting in NLog v4.0 the sequence options have been changed from String to layout ${counter:increment=Integer:sequence=Layout:value=Integer} The syntax for versions below NLog v4.0 is: ${counter:increment=Integer:sequence=String:value=Integer} Parameters Counter Options increment - Value to be added to the counter after each layout rendering. Integer Default: 1 sequence - Name of the sequence. Different named sequences can have individual values. value - Initial value of the counter. Integer Default: 1","title":"Counter layout renderer"},{"location":"Counter-layout-renderer/#configuration-syntax","text":"Starting in NLog v4.0 the sequence options have been changed from String to layout ${counter:increment=Integer:sequence=Layout:value=Integer} The syntax for versions below NLog v4.0 is: ${counter:increment=Integer:sequence=String:value=Integer}","title":"Configuration Syntax"},{"location":"Counter-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Counter-layout-renderer/#counter-options","text":"increment - Value to be added to the counter after each layout rendering. Integer Default: 1 sequence - Name of the sequence. Different named sequences can have individual values. value - Initial value of the counter. Integer Default: 1","title":"Counter Options"},{"location":"CsvLayout/","text":"A specialized layout that renders CSV-formatted events. Platforms Supported: All Configuration Syntax Enum String Boolean String Enum Parameters Columns Array-collection where each item is represented by element with the following attributes: * name - Name of the column (Becomes part of the Header for the CSV-output) * layout - Layout for the column value. Layout Required. * quoting - Column specific override of the default column quoting (Ex. for column with multiline exception-output) > Introduced with NLog 4.6 CSV Options quoting - Default Quoting mode for columns to ensure valid CSV output. Default: Auto Possible values: Auto - Only add quotes when detecting value contains the quote symbol, the separator or newlines (Slow) All - Add quotes for all values. Useful for data known to be multiline such as Exception-ToString (Fast) Nothing - Quote nothing, but make sure not to include newlines or quote-delimiter in output (Very Fast) quoteChar - Quote Character. Default: \" withHeader - Indicates whether CSV should include header. Boolean . Default true customColumnDelimiter - Custom column delimiter value (valid when delimiter is set to Custom ). delimiter - Column delimiter. Default: Auto Possible values: Auto - Automatically detect from regional settings. Comma - Comma , character (ASCII 44). Custom - Custom string, specified by the CustomColumnDelimiter . Pipe - Pipe | character (ASCII 124). Semicolon - Semicolon ; character (ASCII 59). Space - Space character (ASCII 32). Tab - Tab character (ASCII 9). Example Performance NLog 4.6 introduces the ability to override quoting from automatic to the faster Nothing or All . This will skip the overhead of the automatic quoting logic for individual columns. This example shows how to override quoting for individual columns for better performance: From code Layout = new CsvLayout() { Columns = { new CsvColumn(\"time\", \"${longdate}\"), new CsvColumn(\"level\", \"${level:upperCase=true}\"), new CsvColumn(\"message\", \"${message}\"), new CsvColumn(\"exception\", \"${exception:format=ToString}\"), new CsvColumn(\"property1\", \"${event-properties:property1}\"), } }","title":"CsvLayout"},{"location":"CsvLayout/#configuration-syntax","text":" Enum String Boolean String Enum ","title":"Configuration Syntax"},{"location":"CsvLayout/#parameters","text":"","title":"Parameters"},{"location":"CsvLayout/#columns","text":"Array-collection where each item is represented by element with the following attributes: * name - Name of the column (Becomes part of the Header for the CSV-output) * layout - Layout for the column value. Layout Required. * quoting - Column specific override of the default column quoting (Ex. for column with multiline exception-output) > Introduced with NLog 4.6","title":"Columns"},{"location":"CsvLayout/#csv-options","text":"quoting - Default Quoting mode for columns to ensure valid CSV output. Default: Auto Possible values: Auto - Only add quotes when detecting value contains the quote symbol, the separator or newlines (Slow) All - Add quotes for all values. Useful for data known to be multiline such as Exception-ToString (Fast) Nothing - Quote nothing, but make sure not to include newlines or quote-delimiter in output (Very Fast) quoteChar - Quote Character. Default: \" withHeader - Indicates whether CSV should include header. Boolean . Default true customColumnDelimiter - Custom column delimiter value (valid when delimiter is set to Custom ). delimiter - Column delimiter. Default: Auto Possible values: Auto - Automatically detect from regional settings. Comma - Comma , character (ASCII 44). Custom - Custom string, specified by the CustomColumnDelimiter . Pipe - Pipe | character (ASCII 124). Semicolon - Semicolon ; character (ASCII 59). Space - Space character (ASCII 32). Tab - Tab character (ASCII 9).","title":"CSV Options"},{"location":"CsvLayout/#example","text":" ","title":"Example"},{"location":"CsvLayout/#performance","text":"NLog 4.6 introduces the ability to override quoting from automatic to the faster Nothing or All . This will skip the overhead of the automatic quoting logic for individual columns. This example shows how to override quoting for individual columns for better performance: ","title":"Performance"},{"location":"CsvLayout/#from-code","text":"Layout = new CsvLayout() { Columns = { new CsvColumn(\"time\", \"${longdate}\"), new CsvColumn(\"level\", \"${level:upperCase=true}\"), new CsvColumn(\"message\", \"${message}\"), new CsvColumn(\"exception\", \"${exception:format=ToString}\"), new CsvColumn(\"property1\", \"${event-properties:property1}\"), } }","title":"From code"},{"location":"CurrentDir-Layout-Renderer/","text":"The current working directory of the application. Platforms Supported: All Introduced in NLog v4.5. See also ${basedir} , ${specialfolder} , ${processdir} , ${tempdir} Configuration Syntax ${currentdir:dir=String:file=String} Parameters Advanced Options dir: Name of the directory to be Path.Combine()'d with the current directory. file: Name of the file to be Path.Combine()'d with the current directory. Notes Applications can change their current directory , so NLog resolves the current directory without caching. If not expecting current directory to be changed, then enabling caching will improve performance: ${currentdir:cached=true} See also: FileTarget FileName Directory","title":"CurrentDir Layout Renderer"},{"location":"CurrentDir-Layout-Renderer/#configuration-syntax","text":"${currentdir:dir=String:file=String}","title":"Configuration Syntax"},{"location":"CurrentDir-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"CurrentDir-Layout-Renderer/#advanced-options","text":"dir: Name of the directory to be Path.Combine()'d with the current directory. file: Name of the file to be Path.Combine()'d with the current directory.","title":"Advanced Options"},{"location":"CurrentDir-Layout-Renderer/#notes","text":"Applications can change their current directory , so NLog resolves the current directory without caching. If not expecting current directory to be changed, then enabling caching will improve performance: ${currentdir:cached=true} See also: FileTarget FileName Directory","title":"Notes"},{"location":"Custom-extension-of-Logger-interface/","text":"Introduction There can be different reasons for extending the NLog logging interface: Extend logging interface to automatically add relevant context when logging. Create an abstract interface to avoid direct NLog dependency in source-code. Abstract Interface Libraries There already exists several libraries that provides an abstract interface: Microsoft.Extensions.Logging Microsoft.System.Diagnostics.Trace ( Setup NLogTraceListener ) Common Logging (But seems obsolete) LibLog - Useful for shared libraries (But have become obsolete) Extended logging interface There are two ways to extend the NLog Logger. Inherit from the NLog Logger and add your own custom extensions. Create a custom wrapper around the NLog Logger and forward the logevents to the NLog Logger. Custom Wrapper and callsite NLog has a special Callsite feature, that allows it to automatically capture the location in source code that performed the logging. This feature has a huge overhead (logging becomes 20 times slower, together with lots of bonus allocations), because the capture of StackTrace and scanning for source location is expensive. When creating a custom wrapper around the NLog Logger-interface (or extension methods), then the callsite logic will think the custom wrapper is the origin of the log-statement. This can be solved by using Logger.Log(Type wrapperType, LogEventInfo logEvent) -method when writing the LogEvent, and providing the typeof(MyCustomWrapper) as first parameter. public class MyLogger { private readonly NLog.Logger Logger; public MyLogger(string name) { Logger = NLog.LogManager.GetLogger(name); } public void WriteMessage(string message) { NLog.LogEventInfo logEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Info, null, message); Logger.Log(typeof(MyLogger), logEvent); } } When the custom wrapper provides its own Type as wrapperType, then the callsite logic will not see the custom wrapper as being the origin of the log-statement. If extending the NLog Logger-interface without providing the correct wrapperType , then Callsite will stop working. Note NLog 5.0 adds full support for using Caller Information -attributes that was introduced with .NET 4.5. When having called LogEventInfo.SetCallerInfo(...) then StackTrace capture is not needed for the Callsite feature. public class MyLogger { private readonly NLog.Logger Logger; public MyLogger(string name) { Logger = NLog.LogManager.GetLogger(name); } public void WriteMessage(string message, [CallerMemberName] string callerMemberName = \"\", [CallerFilePath] string callerFilePath = \"\", [CallerLineNumber] int callerLineNumber = 0) { NLog.LogEventInfo logEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Info, null, message); logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber); Logger.Log(typeof(MyLogger), logEvent); } }","title":"Custom extension of Logger interface"},{"location":"Custom-extension-of-Logger-interface/#introduction","text":"There can be different reasons for extending the NLog logging interface: Extend logging interface to automatically add relevant context when logging. Create an abstract interface to avoid direct NLog dependency in source-code.","title":"Introduction"},{"location":"Custom-extension-of-Logger-interface/#abstract-interface-libraries","text":"There already exists several libraries that provides an abstract interface: Microsoft.Extensions.Logging Microsoft.System.Diagnostics.Trace ( Setup NLogTraceListener ) Common Logging (But seems obsolete) LibLog - Useful for shared libraries (But have become obsolete)","title":"Abstract Interface Libraries"},{"location":"Custom-extension-of-Logger-interface/#extended-logging-interface","text":"There are two ways to extend the NLog Logger. Inherit from the NLog Logger and add your own custom extensions. Create a custom wrapper around the NLog Logger and forward the logevents to the NLog Logger.","title":"Extended logging interface"},{"location":"Custom-extension-of-Logger-interface/#custom-wrapper-and-callsite","text":"NLog has a special Callsite feature, that allows it to automatically capture the location in source code that performed the logging. This feature has a huge overhead (logging becomes 20 times slower, together with lots of bonus allocations), because the capture of StackTrace and scanning for source location is expensive. When creating a custom wrapper around the NLog Logger-interface (or extension methods), then the callsite logic will think the custom wrapper is the origin of the log-statement. This can be solved by using Logger.Log(Type wrapperType, LogEventInfo logEvent) -method when writing the LogEvent, and providing the typeof(MyCustomWrapper) as first parameter. public class MyLogger { private readonly NLog.Logger Logger; public MyLogger(string name) { Logger = NLog.LogManager.GetLogger(name); } public void WriteMessage(string message) { NLog.LogEventInfo logEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Info, null, message); Logger.Log(typeof(MyLogger), logEvent); } } When the custom wrapper provides its own Type as wrapperType, then the callsite logic will not see the custom wrapper as being the origin of the log-statement. If extending the NLog Logger-interface without providing the correct wrapperType , then Callsite will stop working. Note NLog 5.0 adds full support for using Caller Information -attributes that was introduced with .NET 4.5. When having called LogEventInfo.SetCallerInfo(...) then StackTrace capture is not needed for the Callsite feature. public class MyLogger { private readonly NLog.Logger Logger; public MyLogger(string name) { Logger = NLog.LogManager.GetLogger(name); } public void WriteMessage(string message, [CallerMemberName] string callerMemberName = \"\", [CallerFilePath] string callerFilePath = \"\", [CallerLineNumber] int callerLineNumber = 0) { NLog.LogEventInfo logEvent = NLog.LogEventInfo.Create(NLog.LogLevel.Info, null, message); logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber); Logger.Log(typeof(MyLogger), logEvent); } }","title":"Custom Wrapper and callsite"},{"location":"DB-null-layout-renderer/","text":"DB null for a database Platforms Supported: All Introduced in NLog 4.6. Most usefull for the Database target Configuration Syntax ${db-null} Render a DbNull value for the database parameter","title":"DB null layout renderer"},{"location":"DB-null-layout-renderer/#configuration-syntax","text":"${db-null} Render a DbNull value for the database parameter","title":"Configuration Syntax"},{"location":"Data-types/","text":"The data types used in NLog Layout : The layout created with Layout-Renderers Boolean : true or false in the XML. Integer : 4 bytes integral number. Long : 8 bytes integral number. Encoding : An encoding name. Possible values are listed in the Name column of the table that appears in the Encoding class topic.","title":"Data types"},{"location":"Database-target/","text":"Writes log messages to the database using an ADO.NET provider. The database operation is always executed outside of a transaction. Platforms Supported: All - Requires nuget-package NLog.Database since NLog 5.0 You can use this target with various DB providers, e.g. System.Data, Microsoft.Data, PostgreSQL, Oracle, MySql, SqlLite etc. see Providers examples \u2139\ufe0f Don't forget to install the needed nuget-package for your DB provider! Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Connection Options dbProvider - Name of the database provider. Required. Default: sqlserver Following values are recognized by default: sqlserver, mssql, microsoft or msde - Resolves to System.Data.SqlClient Data Provider odbc - ODBC Data Provider (Not recognized on NetCore) oledb - OLEDB Data Provider (Not recognized on NetCore) Note for .NET Core one should install the Nuget-package for the DbProvider (Ex. System.Data.SqlClient), and instead use the fully qualified name of the provider connection type (class implementing IDbConnection). See also DbProvider Examples If you get the following error in Internal-Logging then you might have to use the fully qualified name. Error during initialization of DatabaseTarget(Name=db). Could not load type '' from assembly connectionString - Connection string. When provided, it overrides the values specified in DBHost, DBUserName, DBPassword, DBDatabase and DBProvider. Layout connectionStringName - Name of the connection string to lookup in app.config. The ProviderName of the connectionstring will be used to determine the SQL type. Since NLog 4.3 this ProviderName attribute isn't required anymore and the dbProvider will be used as fallback. Not supported on NetCore as app.config has been replaced with appsettings.json. Use ${configsetting} in connectionString instead keepConnection - Indicates whether to keep the database connection open between the log events. Boolean Default: false isolationLevel - Activates transactions where multiple rows are written in a single transaction. This can improve performance when using batching (Ex. ). Recommended to assign ReadCommitted for enabling transactional writing. Consider adding ;ENLIST=FALSE to ConnectionString to disable auto-enlist. Default: Not set Introduced with NLog 4.7 dbDatabase - Database name. If the ConnectionString is not provided this value will be used to construct the \"Database=\" part of the connection string. Layout dbUserName - Database user name. If the ConnectionString is not provided this value will be used to construct the \"User ID=\" part of the connection string. Layout dbPassword - Database password. If the ConnectionString is not provided this value will be used to construct the \"Password=\" part of the connection string. Layout dbHost - Database host name. If the ConnectionString is not provided this value will be used to construct the \"Server=\" part of the connection string. Layout useTransactions - This option was removed in NLog 4.0 because the logging code always runs outside of transaction. This ensures that the log gets written to the database if you rollback the main transaction because of an error and want to log the error. SQL Statement commandType - Type of the command. Required. Default: text Possible values: StoredProcedure - The commandText is the stored procedure name. TableDirect - Text - regular query commandText - Text of the SQL command to be run on each log level. Layout Required. Typically this is a SQL INSERT statement or a stored procedure call. It should use the database-specific parameters (marked as @parameter for SQL server or :parameter for Oracle, other data providers have their own notation) and not the layout renderers, because the latter is prone to SQL injection attacks. The layout renderers should be specified as \\ elements instead. parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection Each collection item is represented by \\ element with the following attributes: layout - Layout that should be use to calcuate the value for the parameter. Layout Required. Note: there is also ${db-null} name - Database parameter name. Required. precision - Database parameter precision. Byte Default: 0 scale - Database parameter scale. Byte Default: 0 size - Database parameter size. Integer Default: 0 dbType - One of the values of DbType (e.g. \"Int32\", \"Decimal\", \"DateTime\"), or a value of DBType like prefixed with the property name, e.g. \"SqlDbType.NChar\" will set the property \"SqlDbType\" on \"NChar\". Another example: \"NpgsqlDbType.Json\" with NpgsqlParameter. Introduced in NLog 4.6. Since NLog 4.7 not case-sensitive any more parameterType - Optional parametertype (System.Type), Will be automatically mapped for common DbType-values. When using special DbType like SqlDbType.SmallInt, then one can specify parameterType=\"System.Int16\" to help - This will skip the overhead of first rendering to string, and parsing the string into the expected type. Introduced in NLog 4.6 format - format for parsing the value when not using the rawValue, of if the rawValue conversion to has been failed. Introduced in NLog 4.6 culture - culture for parsing the value, analogous as \"format\". Introduced in NLog 4.6 allowDbNull - empty value will be translate into DbNull. Requires database column to allow NULL values. Introduced in NLog 4.7.4. Empty values are null for nullable types and null and '' for strings. Installation Options See Installing targets . installConnectionString - Connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. Layout InstallDdlCommands - The installation DDL commands. Collection . Each collection item is represented by \\ element with the following attributes: commandType - Type of the command. Required. Default: text Possible values: StoredProcedure - The command-text is the stored procedure name. TableDirect - Text - regular query Text - The command-text (Or stored procedure name) parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection Each collection item is represented by element with the following attributes: layout - Layout that should be use to calcuate the value for the parameter. Layout Required. name - Database parameter name. Required. precision - Database parameter precision. Byte Default: 0 scale - Database parameter scale. Byte Default: 0 size - Database parameter size. Integer Default: 0 text - Command text. Layout Required. connectionString - Connection string to run the command against. If not provided, connection string from the target is used. Layout ignoreFailures - Indicates whether to ignore failures. Boolean uninstallDdlCommands - The uninstallation DDL commands. Collection Each collection item is represented by \\ element with the following attributes: commandType - Type of the command. Required. Default: text Possible values: StoredProcedure - The command-text is the stored procedure name. TableDirect - Text - regular query Text - The command-text (Or stored procedure name) parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection Each collection item is represented by \\ element with the following attributes: layout - Layout that should be use to calcuate the value for the parameter. Layout Required. name - Database parameter name. Required. precision - Database parameter precision. Byte Default: 0 scale - Database parameter scale. Byte Default: 0 size - Database parameter size. Integer Default: 0 text - Command text. Layout Required. connectionString - Connection string to run the command against. If not provided, connection string from the target is used. Layout ignoreFailures - Indicates whether to ignore failures. Boolean Command and connection properties Introduced in NLog 4.7, you could add properties to the connection (e.g. SqlConnection, OracleConnection) and the Command (e.g. SqlCommand, OracleCommand). this could be useful for the Azure Access Token Examples Full example: About DbType and IRawValue The DbType works as follows - NLog tries first if the Layout Renderer support IRawValue to get the non-string type. Then it will use the IPropertyTypeConverter for converting to the desired dbType. - If that fails, NLog will render the layout render to string and then parse it (with usage of the optional format option). Then it will also use the IPropertyTypeConverter for converting to the desired dbType. - NoRawValue layout renderer could be use for forcing to use the string value. About allowDbNull example Where null and empty string-value is converted to DbNull-value: Example Configurations NLog and SQL Server Example Configuration server=localhost;Database=*****;user id=****;password=***** insert into dbo.Log ( MachineName, Logged, Level, Message, Logger, Exception ) values ( @MachineName, @Logged, @Level, @Message, @Logger, @Exception ); NLog and SQL Server using a stored procedure This approach keeps the NLog.config file simpler, and helps confine database logic to the database. NLog target configuration SQL scripts to set up the database objects Remember to grant permissions on the database objects so that the website can execute the stored procedure. CREATE TABLE [dbo].[NLog] ( [ID] [int] IDENTITY(1,1) NOT NULL, [MachineName] [nvarchar](200) NULL, [Logged] [datetime] NOT NULL, [Level] [varchar](5) NOT NULL, [Message] [nvarchar](max) NOT NULL, [Logger] [nvarchar](300) NULL, [Properties] [nvarchar](max) NULL, [Exception] [nvarchar](max) NULL, CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([ID] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]; GO CREATE PROCEDURE [dbo].[NLog_AddEntry_p] ( @machineName nvarchar(200), @logged datetime, @level varchar(5), @message nvarchar(max), @logger nvarchar(300), @properties nvarchar(max), @exception nvarchar(max) ) AS BEGIN INSERT INTO [dbo].[NLog] ( [MachineName], [Logged], [Level], [Message], [Logger], [Properties], [Exception] ) VALUES ( @machineName, @logged, @level, @message, @logger, @properties, @exception ); END Example: log with custom properties, not all in the message This combines structured logging and WithProperty . You need at least NLog 4.6.3 for this. Logger call: logger.WithProperty(\"Property2\", \"value2\") .Info(\"my info message {Property1}\", \"value1\"); config: INSERT INTO Table (message, machinename, property1, property2) VALUES (@message, @machinenameParam, @propertyParam2) This will create a log record in the database with my info message with \"Value1\" , the machine name and the custom properties \"value1\" and \"value2\" Note, now \"value1\" is in the message and \"value2\" isn't. AOT Example AOT-builds does not support usage of DbProvider -option for doing type-reflection, instead one can create instance of DatabaseTarget with DbConnectionFactory -delegate: var databaseTarget = new NLog.Targets.DatabaseTarget(() => new Npgsql.NpgsqlConnection()); NLog.LogManager.Setup().LoadConfiguration(cfg => cfg.ForLogger().WriteTo(databaseTarget)); For Database-Parameters then one can use DbTypeEnum -property, and if needing custom DbType, then one can create instance of DatabaseParameterInfo with delegate: var databaseParameter = new DatabaseParameterInfo(\"@context\", \"${all-event-properties}\", (p) => ((NpgsqlParameter)p).NpgsqlDbType = NpgsqlDbType.VarChar); databaseTarget.Parameters.Add(databaseParameter); DbProvider Examples Microsoft.Data.SqlClient Install package: https://www.nuget.org/packages/Microsoft.Data.SqlClient/ dbProvider=\"Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient\" MySql Install package: https://www.nuget.org/packages/MySql.Data/ dbProvider=\"MySql.Data.MySqlClient.MySqlConnection, MySql.Data\" or if using packages: https://www.nuget.org/packages/MySqlConnector/ and https://www.nuget.org/packages/MySqlConnector.Logging.NLog/ dbProvider=\"MySqlConnector.MySqlConnection, MySqlConnector\" System.Data.SQLite Install package: https://www.nuget.org/packages/System.Data.SQLite dbProvider=\"System.Data.SQLite.SQLiteConnection, System.Data.SQLite\" Microsoft.Data.Sqlite Install package: https://www.nuget.org/packages/Microsoft.Data.SQLite/ dbProvider=\"Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite\" PostgreSQL Npgsql Install package: https://www.nuget.org/packages/Npgsql/ dbProvider=\"Npgsql.NpgsqlConnection, Npgsql\" Oracle.ManagedDataAccess dbProvider=\"Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess\" Mono.Data.Sqlite and .NET dbProvider=\"Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite\" Microsoft Access ...","title":"Database target"},{"location":"Database-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Database-target/#parameters","text":"","title":"Parameters"},{"location":"Database-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Database-target/#connection-options","text":"dbProvider - Name of the database provider. Required. Default: sqlserver Following values are recognized by default: sqlserver, mssql, microsoft or msde - Resolves to System.Data.SqlClient Data Provider odbc - ODBC Data Provider (Not recognized on NetCore) oledb - OLEDB Data Provider (Not recognized on NetCore) Note for .NET Core one should install the Nuget-package for the DbProvider (Ex. System.Data.SqlClient), and instead use the fully qualified name of the provider connection type (class implementing IDbConnection). See also DbProvider Examples If you get the following error in Internal-Logging then you might have to use the fully qualified name. Error during initialization of DatabaseTarget(Name=db). Could not load type '' from assembly connectionString - Connection string. When provided, it overrides the values specified in DBHost, DBUserName, DBPassword, DBDatabase and DBProvider. Layout connectionStringName - Name of the connection string to lookup in app.config. The ProviderName of the connectionstring will be used to determine the SQL type. Since NLog 4.3 this ProviderName attribute isn't required anymore and the dbProvider will be used as fallback. Not supported on NetCore as app.config has been replaced with appsettings.json. Use ${configsetting} in connectionString instead keepConnection - Indicates whether to keep the database connection open between the log events. Boolean Default: false isolationLevel - Activates transactions where multiple rows are written in a single transaction. This can improve performance when using batching (Ex. ). Recommended to assign ReadCommitted for enabling transactional writing. Consider adding ;ENLIST=FALSE to ConnectionString to disable auto-enlist. Default: Not set Introduced with NLog 4.7 dbDatabase - Database name. If the ConnectionString is not provided this value will be used to construct the \"Database=\" part of the connection string. Layout dbUserName - Database user name. If the ConnectionString is not provided this value will be used to construct the \"User ID=\" part of the connection string. Layout dbPassword - Database password. If the ConnectionString is not provided this value will be used to construct the \"Password=\" part of the connection string. Layout dbHost - Database host name. If the ConnectionString is not provided this value will be used to construct the \"Server=\" part of the connection string. Layout useTransactions - This option was removed in NLog 4.0 because the logging code always runs outside of transaction. This ensures that the log gets written to the database if you rollback the main transaction because of an error and want to log the error.","title":"Connection Options"},{"location":"Database-target/#sql-statement","text":"commandType - Type of the command. Required. Default: text Possible values: StoredProcedure - The commandText is the stored procedure name. TableDirect - Text - regular query commandText - Text of the SQL command to be run on each log level. Layout Required. Typically this is a SQL INSERT statement or a stored procedure call. It should use the database-specific parameters (marked as @parameter for SQL server or :parameter for Oracle, other data providers have their own notation) and not the layout renderers, because the latter is prone to SQL injection attacks. The layout renderers should be specified as \\ elements instead. parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection Each collection item is represented by \\ element with the following attributes: layout - Layout that should be use to calcuate the value for the parameter. Layout Required. Note: there is also ${db-null} name - Database parameter name. Required. precision - Database parameter precision. Byte Default: 0 scale - Database parameter scale. Byte Default: 0 size - Database parameter size. Integer Default: 0 dbType - One of the values of DbType (e.g. \"Int32\", \"Decimal\", \"DateTime\"), or a value of DBType like prefixed with the property name, e.g. \"SqlDbType.NChar\" will set the property \"SqlDbType\" on \"NChar\". Another example: \"NpgsqlDbType.Json\" with NpgsqlParameter. Introduced in NLog 4.6. Since NLog 4.7 not case-sensitive any more parameterType - Optional parametertype (System.Type), Will be automatically mapped for common DbType-values. When using special DbType like SqlDbType.SmallInt, then one can specify parameterType=\"System.Int16\" to help - This will skip the overhead of first rendering to string, and parsing the string into the expected type. Introduced in NLog 4.6 format - format for parsing the value when not using the rawValue, of if the rawValue conversion to has been failed. Introduced in NLog 4.6 culture - culture for parsing the value, analogous as \"format\". Introduced in NLog 4.6 allowDbNull - empty value will be translate into DbNull. Requires database column to allow NULL values. Introduced in NLog 4.7.4. Empty values are null for nullable types and null and '' for strings.","title":"SQL Statement"},{"location":"Database-target/#installation-options","text":"See Installing targets . installConnectionString - Connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. Layout InstallDdlCommands - The installation DDL commands. Collection . Each collection item is represented by \\ element with the following attributes: commandType - Type of the command. Required. Default: text Possible values: StoredProcedure - The command-text is the stored procedure name. TableDirect - Text - regular query Text - The command-text (Or stored procedure name) parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection Each collection item is represented by element with the following attributes: layout - Layout that should be use to calcuate the value for the parameter. Layout Required. name - Database parameter name. Required. precision - Database parameter precision. Byte Default: 0 scale - Database parameter scale. Byte Default: 0 size - Database parameter size. Integer Default: 0 text - Command text. Layout Required. connectionString - Connection string to run the command against. If not provided, connection string from the target is used. Layout ignoreFailures - Indicates whether to ignore failures. Boolean uninstallDdlCommands - The uninstallation DDL commands. Collection Each collection item is represented by \\ element with the following attributes: commandType - Type of the command. Required. Default: text Possible values: StoredProcedure - The command-text is the stored procedure name. TableDirect - Text - regular query Text - The command-text (Or stored procedure name) parameters - The collection of parameters. Each parameter contains a mapping between NLog layout and a database named or positional parameter. Collection Each collection item is represented by \\ element with the following attributes: layout - Layout that should be use to calcuate the value for the parameter. Layout Required. name - Database parameter name. Required. precision - Database parameter precision. Byte Default: 0 scale - Database parameter scale. Byte Default: 0 size - Database parameter size. Integer Default: 0 text - Command text. Layout Required. connectionString - Connection string to run the command against. If not provided, connection string from the target is used. Layout ignoreFailures - Indicates whether to ignore failures. Boolean","title":"Installation Options"},{"location":"Database-target/#command-and-connection-properties","text":"Introduced in NLog 4.7, you could add properties to the connection (e.g. SqlConnection, OracleConnection) and the Command (e.g. SqlCommand, OracleCommand). this could be useful for the Azure Access Token","title":"Command and connection properties"},{"location":"Database-target/#examples","text":" Full example: ","title":"Examples"},{"location":"Database-target/#about-dbtype-and-irawvalue","text":"The DbType works as follows - NLog tries first if the Layout Renderer support IRawValue to get the non-string type. Then it will use the IPropertyTypeConverter for converting to the desired dbType. - If that fails, NLog will render the layout render to string and then parse it (with usage of the optional format option). Then it will also use the IPropertyTypeConverter for converting to the desired dbType. - NoRawValue layout renderer could be use for forcing to use the string value.","title":"About DbType and IRawValue"},{"location":"Database-target/#about-allowdbnull-example","text":"Where null and empty string-value is converted to DbNull-value: ","title":"About allowDbNull example"},{"location":"Database-target/#example-configurations","text":"","title":"Example Configurations"},{"location":"Database-target/#nlog-and-sql-server-example-configuration","text":" server=localhost;Database=*****;user id=****;password=***** insert into dbo.Log ( MachineName, Logged, Level, Message, Logger, Exception ) values ( @MachineName, @Logged, @Level, @Message, @Logger, @Exception ); ","title":"NLog and SQL Server Example Configuration"},{"location":"Database-target/#nlog-and-sql-server-using-a-stored-procedure","text":"This approach keeps the NLog.config file simpler, and helps confine database logic to the database.","title":"NLog and SQL Server using a stored procedure"},{"location":"Database-target/#nlog-target-configuration","text":" ","title":"NLog target configuration"},{"location":"Database-target/#sql-scripts-to-set-up-the-database-objects","text":"Remember to grant permissions on the database objects so that the website can execute the stored procedure. CREATE TABLE [dbo].[NLog] ( [ID] [int] IDENTITY(1,1) NOT NULL, [MachineName] [nvarchar](200) NULL, [Logged] [datetime] NOT NULL, [Level] [varchar](5) NOT NULL, [Message] [nvarchar](max) NOT NULL, [Logger] [nvarchar](300) NULL, [Properties] [nvarchar](max) NULL, [Exception] [nvarchar](max) NULL, CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([ID] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]; GO CREATE PROCEDURE [dbo].[NLog_AddEntry_p] ( @machineName nvarchar(200), @logged datetime, @level varchar(5), @message nvarchar(max), @logger nvarchar(300), @properties nvarchar(max), @exception nvarchar(max) ) AS BEGIN INSERT INTO [dbo].[NLog] ( [MachineName], [Logged], [Level], [Message], [Logger], [Properties], [Exception] ) VALUES ( @machineName, @logged, @level, @message, @logger, @properties, @exception ); END","title":"SQL scripts to set up the database objects"},{"location":"Database-target/#example-log-with-custom-properties-not-all-in-the-message","text":"This combines structured logging and WithProperty . You need at least NLog 4.6.3 for this. Logger call: logger.WithProperty(\"Property2\", \"value2\") .Info(\"my info message {Property1}\", \"value1\"); config: INSERT INTO Table (message, machinename, property1, property2) VALUES (@message, @machinenameParam, @propertyParam2) This will create a log record in the database with my info message with \"Value1\" , the machine name and the custom properties \"value1\" and \"value2\" Note, now \"value1\" is in the message and \"value2\" isn't.","title":"Example: log with custom properties, not all in the message"},{"location":"Database-target/#aot-example","text":"AOT-builds does not support usage of DbProvider -option for doing type-reflection, instead one can create instance of DatabaseTarget with DbConnectionFactory -delegate: var databaseTarget = new NLog.Targets.DatabaseTarget(() => new Npgsql.NpgsqlConnection()); NLog.LogManager.Setup().LoadConfiguration(cfg => cfg.ForLogger().WriteTo(databaseTarget)); For Database-Parameters then one can use DbTypeEnum -property, and if needing custom DbType, then one can create instance of DatabaseParameterInfo with delegate: var databaseParameter = new DatabaseParameterInfo(\"@context\", \"${all-event-properties}\", (p) => ((NpgsqlParameter)p).NpgsqlDbType = NpgsqlDbType.VarChar); databaseTarget.Parameters.Add(databaseParameter);","title":"AOT Example"},{"location":"Database-target/#dbprovider-examples","text":"","title":"DbProvider Examples"},{"location":"Database-target/#microsoftdatasqlclient","text":"Install package: https://www.nuget.org/packages/Microsoft.Data.SqlClient/ dbProvider=\"Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient\"","title":"Microsoft.Data.SqlClient"},{"location":"Database-target/#mysql","text":"Install package: https://www.nuget.org/packages/MySql.Data/ dbProvider=\"MySql.Data.MySqlClient.MySqlConnection, MySql.Data\" or if using packages: https://www.nuget.org/packages/MySqlConnector/ and https://www.nuget.org/packages/MySqlConnector.Logging.NLog/ dbProvider=\"MySqlConnector.MySqlConnection, MySqlConnector\"","title":"MySql"},{"location":"Database-target/#systemdatasqlite","text":"Install package: https://www.nuget.org/packages/System.Data.SQLite dbProvider=\"System.Data.SQLite.SQLiteConnection, System.Data.SQLite\"","title":"System.Data.SQLite"},{"location":"Database-target/#microsoftdatasqlite","text":"Install package: https://www.nuget.org/packages/Microsoft.Data.SQLite/ dbProvider=\"Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite\"","title":"Microsoft.Data.Sqlite"},{"location":"Database-target/#postgresql-npgsql","text":"Install package: https://www.nuget.org/packages/Npgsql/ dbProvider=\"Npgsql.NpgsqlConnection, Npgsql\"","title":"PostgreSQL Npgsql"},{"location":"Database-target/#oraclemanageddataaccess","text":"dbProvider=\"Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess\"","title":"Oracle.ManagedDataAccess"},{"location":"Database-target/#monodatasqlite-and-net","text":"dbProvider=\"Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite\"","title":"Mono.Data.Sqlite and .NET"},{"location":"Database-target/#microsoft-access","text":" ...","title":"Microsoft Access"},{"location":"Date-layout-renderer/","text":"Current date and time. Platforms Supported: All Alternative ${longdate} or ${shortdate} can be used for high performance timestamp-logging. Configuration Syntax ${date:universalTime=Boolean:format=String:culture=Culture} Parameters Rendering Options universalTime - Indicates whether to output UTC time instead of local time.Boolean Default: False format - Date format. Can be any argument accepted by DateTime.ToString(format). Note that colons need to escaped with a backslash: \\ Example: ${date:format=yyyy-MM-dd HH\\:mm\\:ss.fff} -> DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\") -> \"2000-01-01 00:00:00.000\" Note that backslashes, that shall be passed through, also need to be escaped: \\ Example: ${date:format=\\\\Yyyyy\\\\MMM\\\\Ddd} -> DateTime.Now.ToString(@\"\\Yyyyy\\MMM\\Ddd\") -> Y2000M01D01\" * culture - Culture used for rendering. Default: InvariantCulture Time Source Precision NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Date layout renderer"},{"location":"Date-layout-renderer/#configuration-syntax","text":"${date:universalTime=Boolean:format=String:culture=Culture}","title":"Configuration Syntax"},{"location":"Date-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Date-layout-renderer/#rendering-options","text":"universalTime - Indicates whether to output UTC time instead of local time.Boolean Default: False format - Date format. Can be any argument accepted by DateTime.ToString(format). Note that colons need to escaped with a backslash: \\ Example: ${date:format=yyyy-MM-dd HH\\:mm\\:ss.fff} -> DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\") -> \"2000-01-01 00:00:00.000\" Note that backslashes, that shall be passed through, also need to be escaped: \\ Example: ${date:format=\\\\Yyyyy\\\\MMM\\\\Ddd} -> DateTime.Now.ToString(@\"\\Yyyyy\\MMM\\Ddd\") -> Y2000M01D01\" * culture - Culture used for rendering. Default: InvariantCulture","title":"Rendering Options"},{"location":"Date-layout-renderer/#time-source-precision","text":"NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Time Source Precision"},{"location":"Debug-target/","text":"Mock target for unit-testing. If looking for output to System.Diagnostics.Debug then use DebugSystem-target . Platforms Supported: All Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} Examples Logging to Debug Target (snippet from Debug Simple Example.cs ) NLog.Targets.DebugTarget target = new NLog.Targets.DebugTarget() { Name = \"Debug\" }; target.Layout = \"${message}\"; NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; NLog.Logger logger = NLog.LogManager.GetLogger(\"Example\"); logger.Debug(\"log message\"); logger.Debug(\"another log message\"); Console.WriteLine(\"The debug target has been hit {0} times.\", target.Counter); Console.WriteLine(\"The last message was '{0}'.\", target.LastMessage); Some examples of DebugTarget use can be found in unit tests","title":"Debug target"},{"location":"Debug-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Debug-target/#parameters","text":"","title":"Parameters"},{"location":"Debug-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Debug-target/#layout-options","text":"layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}","title":"Layout Options"},{"location":"Debug-target/#examples","text":"","title":"Examples"},{"location":"Debug-target/#logging-to-debug-target","text":"(snippet from Debug Simple Example.cs ) NLog.Targets.DebugTarget target = new NLog.Targets.DebugTarget() { Name = \"Debug\" }; target.Layout = \"${message}\"; NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; NLog.Logger logger = NLog.LogManager.GetLogger(\"Example\"); logger.Debug(\"log message\"); logger.Debug(\"another log message\"); Console.WriteLine(\"The debug target has been hit {0} times.\", target.Counter); Console.WriteLine(\"The last message was '{0}'.\", target.LastMessage); Some examples of DebugTarget use can be found in unit tests","title":"Logging to Debug Target"},{"location":"DebugSystem-target/","text":"Sends log messages through System.Diagnostics.Debug.WriteLine Platforms Supported: All (Introduced with NLog 5.0) Configuration Syntax Parameters General Options name - Name of the target. Output Options layout - Layout used to format log messages. Layout Required header - Layout used to format header-output when initializing. Layout footer - Layout used to format footer-output when closing. Layout Notes Alternative targets for diagnostic output: - Trace-target for output to System.Diagnostics.Trace - Debugger-target for output to System.Diagnostics.Debugger.Log - OutputDebugString-target for output to OutputDebugString Win32 API","title":"DebugSystem target"},{"location":"DebugSystem-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"DebugSystem-target/#parameters","text":"","title":"Parameters"},{"location":"DebugSystem-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"DebugSystem-target/#output-options","text":"layout - Layout used to format log messages. Layout Required header - Layout used to format header-output when initializing. Layout footer - Layout used to format footer-output when closing. Layout","title":"Output Options"},{"location":"DebugSystem-target/#notes","text":"Alternative targets for diagnostic output: - Trace-target for output to System.Diagnostics.Trace - Debugger-target for output to System.Diagnostics.Debugger.Log - OutputDebugString-target for output to OutputDebugString Win32 API","title":"Notes"},{"location":"Debugger-target/","text":"Writes log messages to the attached managed debugger (Ex. Visual Studio Output Window). See also System.Diagnostics.Debugger.Log Platforms Supported: All Configuration Syntax Read more about using the Configuration File . Parameters name - Name of the target. layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} header - Layout used to format header-output when initializing. footer - Layout used to format footer-output when closing. Category - Layout used to format the category. Default: ${logger} Introduced with NLog v6.1 MaxMessageSize - Max message length in characters before applying OnOverflow -action (0 means unlimited) . Default: 0 . Introduced with NLog v6.1 OnOverflow - Action to perform when max message size is exceeded. Default: Split Introduced with NLog v6.1 Truncate - Truncate the message to fit. Split - Split the big message into multiple log messages. Discard - Discard the entire message. Examples From stackoverflow Notes Alternative targets for diagnostic output: - Trace-target for output to System.Diagnostics.Trace - DebugSystem-target for output to System.Diagnostics.Debug - OutputDebugString-target for output to OutputDebugString Win32 API","title":"Debugger target"},{"location":"Debugger-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Debugger-target/#parameters","text":"name - Name of the target. layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} header - Layout used to format header-output when initializing. footer - Layout used to format footer-output when closing. Category - Layout used to format the category. Default: ${logger} Introduced with NLog v6.1 MaxMessageSize - Max message length in characters before applying OnOverflow -action (0 means unlimited) . Default: 0 . Introduced with NLog v6.1 OnOverflow - Action to perform when max message size is exceeded. Default: Split Introduced with NLog v6.1 Truncate - Truncate the message to fit. Split - Split the big message into multiple log messages. Discard - Discard the entire message.","title":"Parameters"},{"location":"Debugger-target/#examples","text":"From stackoverflow ","title":"Examples"},{"location":"Debugger-target/#notes","text":"Alternative targets for diagnostic output: - Trace-target for output to System.Diagnostics.Trace - DebugSystem-target for output to System.Diagnostics.Debug - OutputDebugString-target for output to OutputDebugString Win32 API","title":"Notes"},{"location":"Dependency-injection-with-NLog/","text":"Resolve Dependency Injection Interface during initialization NLog 5.0 makes it possible to resolve interfaces using dependency injection during initialization. This allows you to load targets using NLog config file, before dependency injection provider is available. The custom NLog target can then override InitializeTarget to resolve the necessary dependencies: protected override void InitializeTarget() { var wantedDependency = base.ResolveService(); base.InitializeTarget(); } If the custom NLog target requests a dependency, that is unavailable, then NLog will perform re-initialization of the NLog when the dependency becomes available. Service interfaces can registered like this: NLog.LogManager.Setup().SetupExtensions(ext => RegisterSingletonService(wantedInstance)); It is also possible to connect with an external IServiceProvider for resolving dependencies: NLog.LogManager.Setup().SetupExtensions(ext => RegisterServiceProvider(serviceProvider)); It is recommended to setup dependency-injection early before loading the NLog LoggingConfiguration, or else they might not take effect. Resolve Dependency Injection Interface during object creation NLog v5.2 introduces the ability to register extensions together with custom factory-method: NLog.LogManager.Setup().SetupExtensions(ext => RegisterTarget(() => new MyTarget(wantedDependency)); \u26a0\ufe0f NLog v5.2 has marked ConfigurationItemFactory.CreateInstance as obsolete, as it doesn't work well with Ahead-of-Time (AOT) application trimming in .NET NLog will by default use the default constructor for creating new objects. It is possible to override the creation by using ConfigurationItemFactory.CreateInstance . Example: using NLog.Config; var defaultConstructor = ConfigurationItemFactory.Default.CreateInstance; ConfigurationItemFactory.Default.CreateInstance.CreateInstance = type => { if (type == typeof(MyCustomTarget)) return new MyCustomTarget(myCustomParameter); return defaultConstructor(type); }; NLog will only be able to create objects of known types. To support custom objects one must also register the config-item-type before it will be recognized. See also Register your custom component Initialize NLog configuration with Dependency Injection Provider The combination of dynamic logging configuration and dependency injection can give a catch22. You want to have logging up and running early, but this will fail if dependent on custom objects that requires a dependency injection provider is fully loaded. The \"ugly\" work-around to this catch22 is to have two constructors for your custom-objects: - Default Constructor that initializes an object in disabled state (Ignored by dependency injection provider). - Specialized Constructor that initializes an object in working state. Alternative override the CreateInstance -method as first thing (Before creating first Logger-object or loading NLog config). Where it calls the specialized constructor with parameters that signals that it should be in disabled state. Then one can \"just\" perform a reload of the NLog config, after the dependency injection provider has been fully loaded and performed final override of CreateInstance . This will make NLog recreate all configuration items once again, and now with a working dependency injection provider that calls the specialized constructor with correct parameters. using NLog; LogManager.Configuration = LogManager.Configuration.Reload(); See also Reinitialize NLog configuration","title":"Dependency injection with NLog"},{"location":"Dependency-injection-with-NLog/#resolve-dependency-injection-interface-during-initialization","text":"NLog 5.0 makes it possible to resolve interfaces using dependency injection during initialization. This allows you to load targets using NLog config file, before dependency injection provider is available. The custom NLog target can then override InitializeTarget to resolve the necessary dependencies: protected override void InitializeTarget() { var wantedDependency = base.ResolveService(); base.InitializeTarget(); } If the custom NLog target requests a dependency, that is unavailable, then NLog will perform re-initialization of the NLog when the dependency becomes available. Service interfaces can registered like this: NLog.LogManager.Setup().SetupExtensions(ext => RegisterSingletonService(wantedInstance)); It is also possible to connect with an external IServiceProvider for resolving dependencies: NLog.LogManager.Setup().SetupExtensions(ext => RegisterServiceProvider(serviceProvider)); It is recommended to setup dependency-injection early before loading the NLog LoggingConfiguration, or else they might not take effect.","title":"Resolve Dependency Injection Interface during initialization"},{"location":"Dependency-injection-with-NLog/#resolve-dependency-injection-interface-during-object-creation","text":"NLog v5.2 introduces the ability to register extensions together with custom factory-method: NLog.LogManager.Setup().SetupExtensions(ext => RegisterTarget(() => new MyTarget(wantedDependency)); \u26a0\ufe0f NLog v5.2 has marked ConfigurationItemFactory.CreateInstance as obsolete, as it doesn't work well with Ahead-of-Time (AOT) application trimming in .NET NLog will by default use the default constructor for creating new objects. It is possible to override the creation by using ConfigurationItemFactory.CreateInstance . Example: using NLog.Config; var defaultConstructor = ConfigurationItemFactory.Default.CreateInstance; ConfigurationItemFactory.Default.CreateInstance.CreateInstance = type => { if (type == typeof(MyCustomTarget)) return new MyCustomTarget(myCustomParameter); return defaultConstructor(type); }; NLog will only be able to create objects of known types. To support custom objects one must also register the config-item-type before it will be recognized. See also Register your custom component","title":"Resolve Dependency Injection Interface during object creation"},{"location":"Dependency-injection-with-NLog/#initialize-nlog-configuration-with-dependency-injection-provider","text":"The combination of dynamic logging configuration and dependency injection can give a catch22. You want to have logging up and running early, but this will fail if dependent on custom objects that requires a dependency injection provider is fully loaded. The \"ugly\" work-around to this catch22 is to have two constructors for your custom-objects: - Default Constructor that initializes an object in disabled state (Ignored by dependency injection provider). - Specialized Constructor that initializes an object in working state. Alternative override the CreateInstance -method as first thing (Before creating first Logger-object or loading NLog config). Where it calls the specialized constructor with parameters that signals that it should be in disabled state. Then one can \"just\" perform a reload of the NLog config, after the dependency injection provider has been fully loaded and performed final override of CreateInstance . This will make NLog recreate all configuration items once again, and now with a working dependency injection provider that calls the specialized constructor with correct parameters. using NLog; LogManager.Configuration = LogManager.Configuration.Reload(); See also Reinitialize NLog configuration","title":"Initialize NLog configuration with Dependency Injection Provider"},{"location":"Directory-separator/","text":"Renders the OS dependent directory separator Introduced in NLog 4.7 Platforms Supported: All Configuration Syntax ${dir-separator} Remarks Same result as Path.DirectorySeparatorChar","title":"Directory separator"},{"location":"Directory-separator/#configuration-syntax","text":"${dir-separator}","title":"Configuration Syntax"},{"location":"Directory-separator/#remarks","text":"Same result as Path.DirectorySeparatorChar","title":"Remarks"},{"location":"DocumentUri-layout-renderer/","text":"URI of the HTML page which hosts the current Silverlight application. Supported in Silverlight (NLog 5.0 does not support Silverlight) Configuration Syntax ${document-uri}","title":"DocumentUri layout renderer"},{"location":"DocumentUri-layout-renderer/#configuration-syntax","text":"${document-uri}","title":"Configuration Syntax"},{"location":"Elmah-target/","text":"","title":"Elmah target"},{"location":"Environment-User-Layout-Renderer/","text":"Thread User identity information (username). Platforms Supported: All Introduced with NLog ver. 4.6.4 Configuration Syntax ${environment-user:userName=Boolean:domain=Boolean} Parameters Rendering Options userName - Indicates whether username should be included. Boolean Default: True domain - Indicates whether domain name should be included. Boolean Default: False DefaultUser - Fallback value if unable to lookup username DefaultDomain - Fallback value if unable to lookup domain Notes On Windows the Environment.UserName property wraps a call to the Windows GetUserName function . On Unix platforms the UserName property wraps a call to the getpwuid_r function. If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user. In a published ASP.NET application, this property returns the name of the application pool account (such as Default AppPool). Alternative one can use ${windows-identity} that depends on WindowsIdentity.Getcurrent() Another alternative is ${identity} that depends on Thread.CurrentPrincipal . Yet another alternative is ${aspnet-user-identity} but it only works on ASP.NET Applications with identity enabled.","title":"Environment User Layout Renderer"},{"location":"Environment-User-Layout-Renderer/#configuration-syntax","text":"${environment-user:userName=Boolean:domain=Boolean}","title":"Configuration Syntax"},{"location":"Environment-User-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Environment-User-Layout-Renderer/#rendering-options","text":"userName - Indicates whether username should be included. Boolean Default: True domain - Indicates whether domain name should be included. Boolean Default: False DefaultUser - Fallback value if unable to lookup username DefaultDomain - Fallback value if unable to lookup domain","title":"Rendering Options"},{"location":"Environment-User-Layout-Renderer/#notes","text":"On Windows the Environment.UserName property wraps a call to the Windows GetUserName function . On Unix platforms the UserName property wraps a call to the getpwuid_r function. If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user. In a published ASP.NET application, this property returns the name of the application pool account (such as Default AppPool). Alternative one can use ${windows-identity} that depends on WindowsIdentity.Getcurrent() Another alternative is ${identity} that depends on Thread.CurrentPrincipal . Yet another alternative is ${aspnet-user-identity} but it only works on ASP.NET Applications with identity enabled.","title":"Notes"},{"location":"Environment-layout-renderer/","text":"The environment variable like USERNAME , TMP , USERPROFILE , COMPUTERNAME , PROCESSOR_ARCHITECTURE etc. Platforms Supported: All Configuration Syntax ${environment:variable=String} Parameters Rendering Options variable - Name of the environment variable. Required. Examples: USERNAME , TMP , USERPROFILE , COMPUTERNAME , PROCESSOR_ARCHITECTURE etc. Remarks For better performance then consider to combine with cached=true . Thus only resolving environment-variable value only once, but then not react to any changes of the environment variable. This Layout Renderer outputs environment variables, and NOT properties from System.Environment To list all environment variables in your system: Open Command Prompt (cmd) and execute the command set Open PowerShell and execute the command dir env: System.Environment.GetEnvironmentVariables() Example log file for 32 bits systems in folder 32 and otherwise in folder 64 ","title":"Environment layout renderer"},{"location":"Environment-layout-renderer/#configuration-syntax","text":"${environment:variable=String}","title":"Configuration Syntax"},{"location":"Environment-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Environment-layout-renderer/#rendering-options","text":"variable - Name of the environment variable. Required. Examples: USERNAME , TMP , USERPROFILE , COMPUTERNAME , PROCESSOR_ARCHITECTURE etc.","title":"Rendering Options"},{"location":"Environment-layout-renderer/#remarks","text":"For better performance then consider to combine with cached=true . Thus only resolving environment-variable value only once, but then not react to any changes of the environment variable. This Layout Renderer outputs environment variables, and NOT properties from System.Environment To list all environment variables in your system: Open Command Prompt (cmd) and execute the command set Open PowerShell and execute the command dir env: System.Environment.GetEnvironmentVariables()","title":"Remarks"},{"location":"Environment-layout-renderer/#example","text":"log file for 32 bits systems in folder 32 and otherwise in folder 64 ","title":"Example"},{"location":"Environment-specific-NLog-Logging-Configuration/","text":"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 (As part of application installation). Alternative approach is having a basic NLog.config file, and use the include-feature to apply environment-specific-overrides like this: And then deploy nlog.local.config that only contains the environment-specific overrides: 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: 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. 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","title":"Environment specific NLog Logging Configuration"},{"location":"Environment-specific-NLog-Logging-Configuration/#deploy-nlog-configuration-file","text":"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 (As part of application installation). Alternative approach is having a basic NLog.config file, and use the include-feature to apply environment-specific-overrides like this: And then deploy nlog.local.config that only contains the environment-specific overrides: ","title":"Deploy NLog configuration file"},{"location":"Environment-specific-NLog-Logging-Configuration/#include-nlog-configuration-file","text":"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: 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).","title":"Include NLog configuration file"},{"location":"Environment-specific-NLog-Logging-Configuration/#explict-load-nlog-configuration","text":"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","title":"Explict load NLog configuration"},{"location":"Environment-specific-NLog-Logging-Configuration/#setup-with-loadconfigurationfromappsettings","text":"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 )","title":"Setup with LoadConfigurationFromAppSettings"},{"location":"Environment-specific-NLog-Logging-Configuration/#resolve-configuration-from-environment","text":"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)","title":"Resolve configuration from environment"},{"location":"Environment-specific-NLog-Logging-Configuration/#conditional-nlog-target-filters","text":"Instead of maintaining multiple NLog configuration files, then one can consider just have a single NLog.config with conditional target output. 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","title":"Conditional NLog Target filters"},{"location":"Event-Context-Layout-Renderer/","text":"Log event property data. Platforms Supported: All Configuration Syntax ${event-properties:item=MyValue} Note that ${event-properties} syntax replaces the now deprecated ${event-context} syntax. Parameters Rendering Options item - Name of the item (required) Example In your C# code, create an event and add an element to the Properties dictionary (or the deprecated Context dictionary): ... Logger log = LogManager.GetCurrentClassLogger(); LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, \"\", \"Pass my custom value\"); theEvent.Properties[\"MyValue\"] = \"My custom string\"; // deprecated theEvent.Context[\"TheAnswer\"] = 42; log.Log(theEvent); ... And in your NLog.config file: ${event-properties:item=MyValue} -- renders \"My custom string\" ${event-properties:item=TheAnswer} -- renders \"42\"","title":"Event Context Layout Renderer"},{"location":"Event-Context-Layout-Renderer/#configuration-syntax","text":"${event-properties:item=MyValue} Note that ${event-properties} syntax replaces the now deprecated ${event-context} syntax.","title":"Configuration Syntax"},{"location":"Event-Context-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Event-Context-Layout-Renderer/#rendering-options","text":"item - Name of the item (required)","title":"Rendering Options"},{"location":"Event-Context-Layout-Renderer/#example","text":"In your C# code, create an event and add an element to the Properties dictionary (or the deprecated Context dictionary): ... Logger log = LogManager.GetCurrentClassLogger(); LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, \"\", \"Pass my custom value\"); theEvent.Properties[\"MyValue\"] = \"My custom string\"; // deprecated theEvent.Context[\"TheAnswer\"] = 42; log.Log(theEvent); ... And in your NLog.config file: ${event-properties:item=MyValue} -- renders \"My custom string\" ${event-properties:item=TheAnswer} -- renders \"42\"","title":"Example"},{"location":"EventProperties-Layout-Renderer/","text":"Log event properties data. This has the same implementation as ${event-context} , but the latter is deprecated. Platforms Supported: All To log all properties, use ${all-event-properties} . See also NLog Context . Configuration Syntax ${event-properties:item=String:culture=String:format=String:objectpath=String} Parameters item - Name of the item. Required. ignoreCase - Name lookup should be case-insensitive. Default true . Introduced in NLog 5.0 objectpath - property path if the value is an object. Nested properties are supported. Examples: Id , Details.Title . Introduced in NLog 4.6.3 Rendering Options culture - The culture used for rendering. Introduced in NLog 4.1. Default value is CultureInfo.InvariantCulture format - Format for conversion from object to string. Introduced in NLog 4.1. format=@ means serialize object properties into Json-format. Introduced in NLog 4.5. Example Structured logging Properties NLog 4.5+ logger.Info(\"Order {orderid} created for {user}\", 42, \"Kenny\"); and in your NLog.config file: ${event-properties:item=orderId} -- renders \"42\" ${event-properties:item=user} -- renders \"Kenny\" LogEvent Properties Dictionary In C# class, create an event and add an element to the Properties dictionary (or the deprecated Context dictionary): ... Logger logger = LogManager.GetCurrentClassLogger(); LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, null, \"My log message\"); theEvent.Properties[\"MyValue\"] = \"My custom string\"; theEvent.Properties[\"MyDateTimeValue\"] = new DateTime(2015, 08, 30, 11, 26, 50); theEvent.Properties[\"MyInteger\"] = 42; logger.Log(theEvent); ... and in your NLog.config file: ${event-properties:item=MyValue} -- renders \"My custom string\" ${event-properties:MyDateTimeValue:format=yyyy-M-dd}\"; -- renders \"2015-8-30\" ${event-properties:MyDateTimeValue:culture=en-US} -- renders \"8/30/2015 11:26:50 AM\" ${event-properties:MyDateTimeValue:format=yyyy-M-dd HH:mm:ss:culture=en-US} -- renders \"2015-8-30 11:26:50\" Logger WithProperty Introduced in NLog 4.6.3, where Logger have the method WithProperty . The Logger can be enriched, so it automatically injects one (or more) log-event properties for all log-events being written by the Logger. This can work as an alternative to ScopeContext properties . Examples: // WithProperty will return a new unique Logger with the newly added property var newLogger = logger.WithProperty(\"myProperty\", myValue); newLogger.Info(\"hello\"); newLogger.Info(\"again\"); // will also have \"myProperty\" logger.Info(\"hi\"); // is not affected Logger FLuent API NLog 5.0 provides Fluent-Logger-API for building LogEvents: _logger.ForInfoEvent() .Message(\"This is a fluent message {0}.\", \"test\") .Property(\"PropertyName\", \"PropertyValue\") .Log(); Fallback to default value When LogEvent Property cannot be found (or has blank value), then one can use whenEmpty to specify fallback value: ${event-properties:EventId:whenEmpty=42} Objectpath Examples with usage of Objectpath . NLog 4.6.3+ Set the property: var property1 = new { Id = 1, Name = \"test\", Nested = new { Id = 3 } }; var logger = LogManager.GetLogger(\"logger1\"); // e.g. with WithProperty logger.WithProperty(\"prop1\", property1 ).Info(\"test message\"); // or with structured logging logger.Info(\"test Message with {prop1}\", property1); config examples: ${event-properties:prop1} -- renders: { Id = 1, Name = test, Nested = { Id = 3 } } ${event-properties:prop1:objectpath=Id} -- renders: 1 ${event-properties:prop1:objectpath=Nested.Id} -- renders: 3 See also Transform captured properties","title":"EventProperties Layout Renderer"},{"location":"EventProperties-Layout-Renderer/#configuration-syntax","text":"${event-properties:item=String:culture=String:format=String:objectpath=String}","title":"Configuration Syntax"},{"location":"EventProperties-Layout-Renderer/#parameters","text":"item - Name of the item. Required. ignoreCase - Name lookup should be case-insensitive. Default true . Introduced in NLog 5.0 objectpath - property path if the value is an object. Nested properties are supported. Examples: Id , Details.Title . Introduced in NLog 4.6.3","title":"Parameters"},{"location":"EventProperties-Layout-Renderer/#rendering-options","text":"culture - The culture used for rendering. Introduced in NLog 4.1. Default value is CultureInfo.InvariantCulture format - Format for conversion from object to string. Introduced in NLog 4.1. format=@ means serialize object properties into Json-format. Introduced in NLog 4.5.","title":"Rendering Options"},{"location":"EventProperties-Layout-Renderer/#example","text":"","title":"Example"},{"location":"EventProperties-Layout-Renderer/#structured-logging-properties","text":"NLog 4.5+ logger.Info(\"Order {orderid} created for {user}\", 42, \"Kenny\"); and in your NLog.config file: ${event-properties:item=orderId} -- renders \"42\" ${event-properties:item=user} -- renders \"Kenny\"","title":"Structured logging Properties"},{"location":"EventProperties-Layout-Renderer/#logevent-properties-dictionary","text":"In C# class, create an event and add an element to the Properties dictionary (or the deprecated Context dictionary): ... Logger logger = LogManager.GetCurrentClassLogger(); LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, null, \"My log message\"); theEvent.Properties[\"MyValue\"] = \"My custom string\"; theEvent.Properties[\"MyDateTimeValue\"] = new DateTime(2015, 08, 30, 11, 26, 50); theEvent.Properties[\"MyInteger\"] = 42; logger.Log(theEvent); ... and in your NLog.config file: ${event-properties:item=MyValue} -- renders \"My custom string\" ${event-properties:MyDateTimeValue:format=yyyy-M-dd}\"; -- renders \"2015-8-30\" ${event-properties:MyDateTimeValue:culture=en-US} -- renders \"8/30/2015 11:26:50 AM\" ${event-properties:MyDateTimeValue:format=yyyy-M-dd HH:mm:ss:culture=en-US} -- renders \"2015-8-30 11:26:50\"","title":"LogEvent Properties Dictionary"},{"location":"EventProperties-Layout-Renderer/#logger-withproperty","text":"Introduced in NLog 4.6.3, where Logger have the method WithProperty . The Logger can be enriched, so it automatically injects one (or more) log-event properties for all log-events being written by the Logger. This can work as an alternative to ScopeContext properties . Examples: // WithProperty will return a new unique Logger with the newly added property var newLogger = logger.WithProperty(\"myProperty\", myValue); newLogger.Info(\"hello\"); newLogger.Info(\"again\"); // will also have \"myProperty\" logger.Info(\"hi\"); // is not affected","title":"Logger WithProperty"},{"location":"EventProperties-Layout-Renderer/#logger-fluent-api","text":"NLog 5.0 provides Fluent-Logger-API for building LogEvents: _logger.ForInfoEvent() .Message(\"This is a fluent message {0}.\", \"test\") .Property(\"PropertyName\", \"PropertyValue\") .Log();","title":"Logger FLuent API"},{"location":"EventProperties-Layout-Renderer/#fallback-to-default-value","text":"When LogEvent Property cannot be found (or has blank value), then one can use whenEmpty to specify fallback value: ${event-properties:EventId:whenEmpty=42}","title":"Fallback to default value"},{"location":"EventProperties-Layout-Renderer/#objectpath","text":"Examples with usage of Objectpath . NLog 4.6.3+ Set the property: var property1 = new { Id = 1, Name = \"test\", Nested = new { Id = 3 } }; var logger = LogManager.GetLogger(\"logger1\"); // e.g. with WithProperty logger.WithProperty(\"prop1\", property1 ).Info(\"test message\"); // or with structured logging logger.Info(\"test Message with {prop1}\", property1); config examples: ${event-properties:prop1} -- renders: { Id = 1, Name = test, Nested = { Id = 3 } } ${event-properties:prop1:objectpath=Id} -- renders: 1 ${event-properties:prop1:objectpath=Nested.Id} -- renders: 3 See also Transform captured properties","title":"Objectpath"},{"location":"Eventlog-target/","text":"Writes log message to the Windows Event Log. Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsEventLog since NLog 5.0 Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} . Note: max size of 31839 characters (limitation of the EventLog API) Event Log Options machineName - Name of the machine on which Event Log service is running. Default: . NLog 6.0 changed property-type from string to NLog Layout . source - Value to be used as the event Source. By default this is the friendly name of the current AppDomain. NLog 4.0 changed property-type from string to NLog Layout . category - Layout that renders event Category. The categories must be predefined for the specified source and needs to be numeric. NLog 5.0 changed property-type from string to NLog Layout . eventId - Layout that renders event ID. NLog 5.0 changed property-type from standard NLog Layout to typed-layout. eventLogEntryType - Layout that renders EventLogEntryType . Default: Use LogLevel NLog 5.0 changed property-type from standard NLog Layout to typed-layout. log - Name of the Event Log to write to. This can be System, Application or any user-defined name. Default: Application NLog 6.0 changed property-type from string to NLog Layout . MaxMessageLength - The message length limit to write to the Event Log. There are various message length limit that depends on the OS. Introduced in NLog 4.3 with default-value: 16,384, and bumped to 30,000 with NLog v5.0.2 . NLog 6.0 changed property-type from integer to NLog Layout . onOverflow - Action to take when a log message is larger than the MaxMessageLength option. Available actions are: Truncate - Truncates the message before writing to the Event Log. This is the default. Split - Splits the message and writes multiple entries to the Event Log. Warning: the message layout will be spread across multiple Event Log entries; if there is an application reading and parsing the Event Log, split messages will not have the expected layout of a log entry. Discard - Discards of the message. It will not be written to the Event Log. MaxKilobytes - maximum Event log size in kilobytes. null is default (512KB). Value should be multiples of 64 and between 64 and 4194240. Note, this requires admin rights. Introduced in NLog 4.4.10 . NLog 6.0 changed property-type from integer to NLog Layout . Notes When writing to the Windows EventLog, the EventLog-Source must be registered. NLog will automatically attempt to register the EventLog-Source if the application is running with necessary permissions. Alternatively, one must explicitly perform the EventLog-Source registration during application install. - Installing Targets will only register EventLog-Source if source is static (Not using layout renderers). - A simple PowerShell command can be used to register an EventLog-Source (run PowerShell as Administrator): PowerShell New-EventLog -LogName Application -Source \"MySourceName\" NOTE : It may be necessary to restart the Windows Event Log Service (or, alternatively, reboot the computer) after making a change to the EventLog-Source registration in order for the change to take effect. Notice a specific EventLog-source can only be registered for writing to a single named EventLog. Windows gives the illusion of multiple EventLogs, but all LogEvents are stored in the same blob where the EventLog-name is more like a category. The Windows Registry Database controls where the LogEvents from registered EventLog-source should be shown. If changing an EventLog-source to write to a different EventLog, then the change will not be applied until having restarted Windows (or restarted the EventLog-Windows-Service). The Event Log has a limit in the number of bytes in a message. From MSDN : The message string is longer than 31,839 bytes (32,766 bytes on Windows operating systems before Windows Vista). Example NLog.LogManager.GetLogger(\"ApplicationEventLog\").WithProperty(\"EventId\", 42).Error(\"Kilroy was here\");","title":"Eventlog target"},{"location":"Eventlog-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Eventlog-target/#parameters","text":"","title":"Parameters"},{"location":"Eventlog-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Eventlog-target/#layout-options","text":"layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} . Note: max size of 31839 characters (limitation of the EventLog API)","title":"Layout Options"},{"location":"Eventlog-target/#event-log-options","text":"machineName - Name of the machine on which Event Log service is running. Default: . NLog 6.0 changed property-type from string to NLog Layout . source - Value to be used as the event Source. By default this is the friendly name of the current AppDomain. NLog 4.0 changed property-type from string to NLog Layout . category - Layout that renders event Category. The categories must be predefined for the specified source and needs to be numeric. NLog 5.0 changed property-type from string to NLog Layout . eventId - Layout that renders event ID. NLog 5.0 changed property-type from standard NLog Layout to typed-layout. eventLogEntryType - Layout that renders EventLogEntryType . Default: Use LogLevel NLog 5.0 changed property-type from standard NLog Layout to typed-layout. log - Name of the Event Log to write to. This can be System, Application or any user-defined name. Default: Application NLog 6.0 changed property-type from string to NLog Layout . MaxMessageLength - The message length limit to write to the Event Log. There are various message length limit that depends on the OS. Introduced in NLog 4.3 with default-value: 16,384, and bumped to 30,000 with NLog v5.0.2 . NLog 6.0 changed property-type from integer to NLog Layout . onOverflow - Action to take when a log message is larger than the MaxMessageLength option. Available actions are: Truncate - Truncates the message before writing to the Event Log. This is the default. Split - Splits the message and writes multiple entries to the Event Log. Warning: the message layout will be spread across multiple Event Log entries; if there is an application reading and parsing the Event Log, split messages will not have the expected layout of a log entry. Discard - Discards of the message. It will not be written to the Event Log. MaxKilobytes - maximum Event log size in kilobytes. null is default (512KB). Value should be multiples of 64 and between 64 and 4194240. Note, this requires admin rights. Introduced in NLog 4.4.10 . NLog 6.0 changed property-type from integer to NLog Layout .","title":"Event Log Options"},{"location":"Eventlog-target/#notes","text":"When writing to the Windows EventLog, the EventLog-Source must be registered. NLog will automatically attempt to register the EventLog-Source if the application is running with necessary permissions. Alternatively, one must explicitly perform the EventLog-Source registration during application install. - Installing Targets will only register EventLog-Source if source is static (Not using layout renderers). - A simple PowerShell command can be used to register an EventLog-Source (run PowerShell as Administrator): PowerShell New-EventLog -LogName Application -Source \"MySourceName\" NOTE : It may be necessary to restart the Windows Event Log Service (or, alternatively, reboot the computer) after making a change to the EventLog-Source registration in order for the change to take effect. Notice a specific EventLog-source can only be registered for writing to a single named EventLog. Windows gives the illusion of multiple EventLogs, but all LogEvents are stored in the same blob where the EventLog-name is more like a category. The Windows Registry Database controls where the LogEvents from registered EventLog-source should be shown. If changing an EventLog-source to write to a different EventLog, then the change will not be applied until having restarted Windows (or restarted the EventLog-Windows-Service). The Event Log has a limit in the number of bytes in a message. From MSDN : The message string is longer than 31,839 bytes (32,766 bytes on Windows operating systems before Windows Vista).","title":"Notes"},{"location":"Eventlog-target/#example","text":" NLog.LogManager.GetLogger(\"ApplicationEventLog\").WithProperty(\"EventId\", 42).Error(\"Kilroy was here\");","title":"Example"},{"location":"Examples/","text":"Using NLog as .NET Core and ASP.NET Core logging provider Getting started for .NET Core Console application Getting started for ASP.NET Core Changing log file name at runtime using NLog.Targets; ... FileTarget target = LogManager.Configuration.FindTargetByName(targetName); target.FileName = filename; Note that it is often easier to create the file name with a combination of layout-renderers . See also Configure from code Using NLog with Autofac - ASP.NET Web API 2 This example is using a nuget package Autofac.Extras.Nlog that takes care of creating the Autofac module needed to wire up the dependency in the Web API. First, add an nlog section to the configSections in the Web.config:
Then, in the Global.asax.cs (or Startup.cs, depending where Autofac is configured) register the module provided by the Autofac.Extras.Nlog nuget package: var builder = new ContainerBuilder(); ... builder.RegisterModule(); Nothing extra is needed to configure the NLog targets . This example uses constructor injection but Autofac.Extras.Nlog supports property and service locator injection as well. using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Autofac.Extras.NLog; using Microsoft.AspNet.Identity; public class UserService: IUserService { private readonly IUserStore _userStore; private readonly ILogger _logger; public UserService(IUserStore userStore, ILogger logger) { _userStore = userStore; _logger = logger; } ..... } Happy logging!","title":"Examples"},{"location":"Examples/#using-nlog-as-net-core-and-aspnet-core-logging-provider","text":"Getting started for .NET Core Console application Getting started for ASP.NET Core","title":"Using NLog as .NET Core and ASP.NET Core logging provider"},{"location":"Examples/#changing-log-file-name-at-runtime","text":"using NLog.Targets; ... FileTarget target = LogManager.Configuration.FindTargetByName(targetName); target.FileName = filename; Note that it is often easier to create the file name with a combination of layout-renderers . See also Configure from code","title":"Changing log file name at runtime"},{"location":"Examples/#using-nlog-with-autofac-aspnet-web-api-2","text":"This example is using a nuget package Autofac.Extras.Nlog that takes care of creating the Autofac module needed to wire up the dependency in the Web API. First, add an nlog section to the configSections in the Web.config:
Then, in the Global.asax.cs (or Startup.cs, depending where Autofac is configured) register the module provided by the Autofac.Extras.Nlog nuget package: var builder = new ContainerBuilder(); ... builder.RegisterModule(); Nothing extra is needed to configure the NLog targets . This example uses constructor injection but Autofac.Extras.Nlog supports property and service locator injection as well. using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Autofac.Extras.NLog; using Microsoft.AspNet.Identity; public class UserService: IUserService { private readonly IUserStore _userStore; private readonly ILogger _logger; public UserService(IUserStore userStore, ILogger logger) { _userStore = userStore; _logger = logger; } ..... } Happy logging!","title":"Using NLog with Autofac - ASP.NET Web API 2"},{"location":"Exception-layout-renderer/","text":"Exception information provided together with the LogEvent. See also How to properly log exceptions . Platforms Supported: All Configuration Syntax ${exception:format=String:innerFormat=String:maxInnerExceptionLevel=Integer:innerExceptionSeparator=String :separator=String:exceptionDataSeparator=string} Parameters Rendering Options format - Format of the output. Default: ToString,Data . Must be a comma-separated list of exception properties: Notice before NLog 5.0, then default was just message . Message - Serialize Exception.Message Type - Serialize Exception.GetType().FullName ShortType - Serialize Exception.GetType().Name ToString - Serialize Exception.ToString() Method - Serialize Exception.TargetSite StackTrace - Serialize Exception.StackTrace Data - Serialize the dictionary Exception.Data Source - Serialize Exception.Source . Introduced in NLog 4.6.7 TargetSite - Serialize Exception.TargetSite . Introduced in NLog 4.6.7 HResult - Serialize Exception.HResult . Introduced in NLog 4.6.8 Properties - Appends any additional properties that specific type of Exception might have. Introduced in NLog 4.6.8 @ - Serialize all Exception-properties into Json-format. Introduced in NLog 4.5 innerFormat - Format of the output of inner exceptions. Must be a comma-separated list of exception properties (As shown above). This parameter value is case-insensitive. maxInnerExceptionLevel - Maximum number of inner exceptions to include in the output. By default inner exceptions are not enabled for compatibility with NLog 1.0. Note that the format @ serializes InnerException like any other property. Integer. Default: 0 separator - Separator used to concatenate parts specified in the Format. Default: single space innerExceptionSeparator - Separator between inner exceptions. Default: new line exceptionDataSeparator - Separator used to concatenate the exception data parts. Default: ; Introduced in NLog 4.3.9 baseException - Render innermost Exception from Exception.GetBaseException(). Boolean. Default: false Introduced in NLog 4.7.1 flattenException - Automatically flatten AggregateException from async operations to extract its inner exceptions. Boolean. Default: true Introduced in NLog 4.7.6 Notes If debug symbol information is not available, then Exception.ToString() will not output source-code filenames or line-numbers. Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause \"unexpected\" line-numbers. Examples Log only message ${exception:format=message} Log full (without Data) ToString will also print the innerException: ${exception:format=toString} Log full (including Data) Also print exception data, e.g. var ex = new Exception(); ex.Data.Add(\"data1\", \"val2\"); throw ex; ${exception:format=toString,Data} Log exception as JSON the @ format recursively serializes the entire exception hierarchy; combining it with maxInnerExceptionLevel and innerExceptionSeparator won't do what you want. To get the entire exception hierarchy including innerexceptions as nested objects, just specify :format=@ . ${exception:format=@} Custom Exception Serialization NLog 4.7 allows you to override the object reflection for certain object-types. This can be useful for objects with dangerous properties or complex properties. LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(ex => new { Type = ex.GetType().ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, InnerException = ex.InnerException, Status = ex.Status, Response = ex.Response.ToString(), // Call your custom method to render stream as string }) ); This can then be used together with: ${exception:format=ToString,Properties,Data} Or like this for generating JSON: ${exception:format=@}","title":"Exception layout renderer"},{"location":"Exception-layout-renderer/#configuration-syntax","text":"${exception:format=String:innerFormat=String:maxInnerExceptionLevel=Integer:innerExceptionSeparator=String :separator=String:exceptionDataSeparator=string}","title":"Configuration Syntax"},{"location":"Exception-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Exception-layout-renderer/#rendering-options","text":"format - Format of the output. Default: ToString,Data . Must be a comma-separated list of exception properties: Notice before NLog 5.0, then default was just message . Message - Serialize Exception.Message Type - Serialize Exception.GetType().FullName ShortType - Serialize Exception.GetType().Name ToString - Serialize Exception.ToString() Method - Serialize Exception.TargetSite StackTrace - Serialize Exception.StackTrace Data - Serialize the dictionary Exception.Data Source - Serialize Exception.Source . Introduced in NLog 4.6.7 TargetSite - Serialize Exception.TargetSite . Introduced in NLog 4.6.7 HResult - Serialize Exception.HResult . Introduced in NLog 4.6.8 Properties - Appends any additional properties that specific type of Exception might have. Introduced in NLog 4.6.8 @ - Serialize all Exception-properties into Json-format. Introduced in NLog 4.5 innerFormat - Format of the output of inner exceptions. Must be a comma-separated list of exception properties (As shown above). This parameter value is case-insensitive. maxInnerExceptionLevel - Maximum number of inner exceptions to include in the output. By default inner exceptions are not enabled for compatibility with NLog 1.0. Note that the format @ serializes InnerException like any other property. Integer. Default: 0 separator - Separator used to concatenate parts specified in the Format. Default: single space innerExceptionSeparator - Separator between inner exceptions. Default: new line exceptionDataSeparator - Separator used to concatenate the exception data parts. Default: ; Introduced in NLog 4.3.9 baseException - Render innermost Exception from Exception.GetBaseException(). Boolean. Default: false Introduced in NLog 4.7.1 flattenException - Automatically flatten AggregateException from async operations to extract its inner exceptions. Boolean. Default: true Introduced in NLog 4.7.6","title":"Rendering Options"},{"location":"Exception-layout-renderer/#notes","text":"If debug symbol information is not available, then Exception.ToString() will not output source-code filenames or line-numbers. Symbol information from PDB files must be deployed with the application to retrieve and output source-code line-number. For applications compiled in release mode, then inlining can occur and cause \"unexpected\" line-numbers.","title":"Notes"},{"location":"Exception-layout-renderer/#examples","text":"","title":"Examples"},{"location":"Exception-layout-renderer/#log-only-message","text":"${exception:format=message}","title":"Log only message"},{"location":"Exception-layout-renderer/#log-full-without-data","text":"ToString will also print the innerException: ${exception:format=toString}","title":"Log full (without Data)"},{"location":"Exception-layout-renderer/#log-full-including-data","text":"Also print exception data, e.g. var ex = new Exception(); ex.Data.Add(\"data1\", \"val2\"); throw ex; ${exception:format=toString,Data}","title":"Log full (including Data)"},{"location":"Exception-layout-renderer/#log-exception-as-json","text":"the @ format recursively serializes the entire exception hierarchy; combining it with maxInnerExceptionLevel and innerExceptionSeparator won't do what you want. To get the entire exception hierarchy including innerexceptions as nested objects, just specify :format=@ . ${exception:format=@}","title":"Log exception as JSON"},{"location":"Exception-layout-renderer/#custom-exception-serialization","text":"NLog 4.7 allows you to override the object reflection for certain object-types. This can be useful for objects with dangerous properties or complex properties. LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(ex => new { Type = ex.GetType().ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, InnerException = ex.InnerException, Status = ex.Status, Response = ex.Response.ToString(), // Call your custom method to render stream as string }) ); This can then be used together with: ${exception:format=ToString,Properties,Data} Or like this for generating JSON: ${exception:format=@}","title":"Custom Exception Serialization"},{"location":"ExceptionData-Layout-Renderer/","text":"Lookup item in Exception.Data -Dictionary from Exception provided together with the LogEvent. See also How to properly log exceptions . Platforms Supported: All (Introduced with NLog 5.0) Configuration Syntax ${exceptiondata:item=String:format=String:BaseException=Boolean} Parameters Item - Item to lookup in Exception.Data Format - Format for conversion from object to string ( @ means serialize object properties into Json-format) BaseException - Render innermost Exception from Exception.GetBaseException(). Boolean. Default: false","title":"ExceptionData Layout Renderer"},{"location":"ExceptionData-Layout-Renderer/#configuration-syntax","text":"${exceptiondata:item=String:format=String:BaseException=Boolean}","title":"Configuration Syntax"},{"location":"ExceptionData-Layout-Renderer/#parameters","text":"Item - Item to lookup in Exception.Data Format - Format for conversion from object to string ( @ means serialize object properties into Json-format) BaseException - Render innermost Exception from Exception.GetBaseException(). Boolean. Default: false","title":"Parameters"},{"location":"Explicit-NLog-configuration-loading/","text":"\u2139\ufe0f See also Environment specific NLog Logging Configuration Loading NLog configuration from file NLog will automatically scan for configuration files , but sometimes the platform requires explicit configuration loading like this: NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(\"nlog.config\"); Loading NLog configuration from string The configuration can also come from standard string like this with NLog v4.6: NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString); NLog v5 introduces this fluent extension-method: NLog.LogManager.Setup().LoadConfigurationFromXml(xmlString); Loading NLog config from Assembly Resource You need to put the NLog.config file into the application-project, then edit file's properties - change the build action to embedded resource . public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName) { var resourcePaths = assembly.GetManifestResourceNames() .Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase)) .ToList(); if (resourcePaths.Count == 1) { return assembly.GetManifestResourceStream(resourcePaths.Single()); } return null; } var nlogConfigStream = GetEmbeddedResourceStream(myAssembly, \"NLog.config\"); if (nlogConfigStream != null) { var xmlString = new System.IO.StreamReader(nlogConfigStream).ReadToEnd(); NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString); } NLog v5 introduces this fluent configuration extension-method: NLog.LogManager.Setup().LoadConfigurationFromAssemblyResource(typeof(App).GetTypeInfo().Assembly); Xamarin Android \u26a0\ufe0f NLog v5 will no longer scan the assets folder for NLog.config . Instead consider using Embedded Assembly Resource With NLog v4 then the NLog.dll built for Xamarin Android would automatically scan the assets folder for NLog.config . If the file name is different, then NLog v4 also supported this: LogManager.Configuration = new XmlLoggingConfiguration(\"assets/someothername.config\"); ```` If using the NLog.dll built for NetStandard in Xamarin, then the Android `assets`-folder is not recognized or scanned. Instead consider using Assembly Resource. To explicly read file from [Android Assets](https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/resources-in-android/android-assets), then one can do this: ```c# AssetManager assets = this.Assets; var assetStream = assets.Open(\"NLog.config\"); var xmlString = new System.IO.StreamReader(assetStream).ReadToEnd(); NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString);","title":"Explicit NLog configuration loading"},{"location":"Explicit-NLog-configuration-loading/#loading-nlog-configuration-from-file","text":"NLog will automatically scan for configuration files , but sometimes the platform requires explicit configuration loading like this: NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(\"nlog.config\");","title":"Loading NLog configuration from file"},{"location":"Explicit-NLog-configuration-loading/#loading-nlog-configuration-from-string","text":"The configuration can also come from standard string like this with NLog v4.6: NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString); NLog v5 introduces this fluent extension-method: NLog.LogManager.Setup().LoadConfigurationFromXml(xmlString);","title":"Loading NLog configuration from string"},{"location":"Explicit-NLog-configuration-loading/#loading-nlog-config-from-assembly-resource","text":"You need to put the NLog.config file into the application-project, then edit file's properties - change the build action to embedded resource . public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName) { var resourcePaths = assembly.GetManifestResourceNames() .Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase)) .ToList(); if (resourcePaths.Count == 1) { return assembly.GetManifestResourceStream(resourcePaths.Single()); } return null; } var nlogConfigStream = GetEmbeddedResourceStream(myAssembly, \"NLog.config\"); if (nlogConfigStream != null) { var xmlString = new System.IO.StreamReader(nlogConfigStream).ReadToEnd(); NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString); } NLog v5 introduces this fluent configuration extension-method: NLog.LogManager.Setup().LoadConfigurationFromAssemblyResource(typeof(App).GetTypeInfo().Assembly);","title":"Loading NLog config from Assembly Resource"},{"location":"Explicit-NLog-configuration-loading/#xamarin-android","text":"\u26a0\ufe0f NLog v5 will no longer scan the assets folder for NLog.config . Instead consider using Embedded Assembly Resource With NLog v4 then the NLog.dll built for Xamarin Android would automatically scan the assets folder for NLog.config . If the file name is different, then NLog v4 also supported this: LogManager.Configuration = new XmlLoggingConfiguration(\"assets/someothername.config\"); ```` If using the NLog.dll built for NetStandard in Xamarin, then the Android `assets`-folder is not recognized or scanned. Instead consider using Assembly Resource. To explicly read file from [Android Assets](https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/resources-in-android/android-assets), then one can do this: ```c# AssetManager assets = this.Assets; var assetStream = assets.Open(\"NLog.config\"); var xmlString = new System.IO.StreamReader(assetStream).ReadToEnd(); NLog.LogManager.Configuration = NLog.Config.XmlLoggingConfiguration.CreateFromXmlString(xmlString);","title":"Xamarin Android"},{"location":"Extending-NLog/","text":"The following article has related news post: Extending NLog is... easy! If one needs to capture additional context for target output, then one can create own custom NLog LayoutRenderer . But usually most people will just make use of NLog LogEvent Properties for providing custom context. Ensure also to check the available layoutrenderers . If one needs to redirect output to a different output target destination, then one can create own custom NLog Target . But usually most people will just make use of NLog Network-Target or NLog WebService-Target and override the NLog Layout to match the payload format. Ensure also to check the available targets . Write Extensions How to write a custom target How to write a custom layout renderer Writing custom conditions Properties constraints for custom extensions Custom extension of Logger interface Register Extensions Register your custom component","title":"Extending NLog"},{"location":"Extending-NLog/#write-extensions","text":"How to write a custom target How to write a custom layout renderer Writing custom conditions Properties constraints for custom extensions Custom extension of Logger interface","title":"Write Extensions"},{"location":"Extending-NLog/#register-extensions","text":"Register your custom component","title":"Register Extensions"},{"location":"FAQ/","text":"What is NLog? NLog is a free and open source library which helps to write log messages. Why should I use NLog? I can just do file.WriteLine() or Console.WriteLine() Beside writing to files or console, then NLog can also write to many other targets, like database, email, event viewer, trace etc. Output can be written in standard formats like Json / Csv / Xml or simple plain text with support for structured logging The output can be customized to include extra context like ${threadid} with help from Layout Renderers . NLog can use background threads for asynchronous output writing, so application threads are less impacted by logging. On-the-fly changing of the logging-configuration without needing to restart or redeploy. Configuration can be changed at runtime from code or by updating the configuration file. Updating the LogLevel filtering or the output targets. Is it free? Yes, it's licensed under the BSD license, so you can use it in commercial (closed source) programs without problems. Show me the magic! Check the tutorial to get started! Just show me a config example voil\u00e0 Why is NLog not working?! Most problems are fixed by following the troubleshooting guide . If you think it's a bug, please check contributing.md and create a GitHub issue ! Is NLog thread safe? Yes NLog provides thread safety: Creating new Logger is threadsafe Writing LogEvents is threadsafe Updating context containers like GDC / ScopeContext is threadsafe Adding new LoggingRules or Targets using LoggingConfiguration.AddRule and ReconfigExistingLoggers is threadsafe Performing Reload of LoggingConfiguration will cause LogEvents from active loggers to be dropped until reload has completed. Changing values of existing rules and targets at run-time isn't thread-safe! Why is trace and debug logs missing in ASP.NET Core? Check your appsettings.json Should I use Microsoft Extensions Logging? That's up to you. It has it pros and cons. The greatest advantage is that you can easily switch between logging implementations (NLog, Log4Net, etc). This can be very important if you\u2019re writing a library yourself, then the user who's using your library can choose which implementation to use. There are some downsides: You are limited in some features, or some features aren't available at all or harder to access. The performance is a bit lower. See also NLog GetCurrentClassLogger vs Microsoft ILogger When a library depends on NLog, what version of NLog should be used? If you don't use the latest additions, then you should only update every NLog major version. Since NLog 4.0 the assembly version is fixed to 4.0.0.0 and because follow semver . The end-user don't need -magic! So in short: your library should target NLog 4.0 and in the future NLog 5.0. How to properly log exceptions? How to log extra Context Information? How do I get the most optimal performance? How to handle environment specific configuration? How to load NLog configuration from non standard path? How to create NLog Logger for sub classes? How to create isolated NLog Logger for Addons and Plugins? How to wrap NLog Logger? How do I write custom Targets, layouts and layout renderers? How to do dependency injection with NLog? How could I combine programmatic configuration with XML configuration?","title":"FAQ"},{"location":"FallbackGroup-target/","text":"Provides fallback-on-error. Platforms Supported: All Configuration Syntax ... Parameters General Options name - Name of the target. Fallback Options returnToFirstOnSuccess - Indicates whether to return to the first target after any successful write. Boolean . Default false Example Fallback to another mail if the mailserver is down ","title":"FallbackGroup target"},{"location":"FallbackGroup-target/#configuration-syntax","text":" ... ","title":"Configuration Syntax"},{"location":"FallbackGroup-target/#parameters","text":"","title":"Parameters"},{"location":"FallbackGroup-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"FallbackGroup-target/#fallback-options","text":"returnToFirstOnSuccess - Indicates whether to return to the first target after any successful write. Boolean . Default false","title":"Fallback Options"},{"location":"FallbackGroup-target/#example","text":"Fallback to another mail if the mailserver is down ","title":"Example"},{"location":"File-target/","text":"Writes log messages to one or more files. Platforms Supported: All Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} header - Header. Layout footer - Footer. Layout encoding - File encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Default: Utf-8 (Before NLog 5.0 the default was Encoding.Default ) writeBom - Indicates whether to write BOM (byte order mark) in created files. Boolean Default: false. Introduced with NLog 4.5. And after NLog 5.0 is is automatically enabled when encoding UTF16 or UTF32. lineEnding - Line ending mode. Possible values: CR - Insert CR character (ASCII 13) after each line. CRLF - Insert CR LF sequence (ASCII 13, ASCII 10) after each line. Default - Insert platform-dependent end-of-line sequence after each line. LF - Insert LF character (ASCII 10) after each line. NULL - Null terminator (ASCII 0) after each line. None - Don't insert any line ending. Output Options fileName - Name of the file to write to. Layout Required. This FileName string is a layout which may include instances of layout renderers. This lets you use a single target to write to multiple files. The following value makes NLog write logging events to files based on the log level in the directory where the application runs. ${basedir}/${level}.log All Debug messages will go to Debug.log , all Info messages will go to Info.log and so on. You can combine as many of the layout renderers as you want to produce an arbitrary log file name. See also Filename Directory enableFileDelete - Indicates whether to enable log file(s) to be deleted. The FileTarget will periodically verify if the file has been deleted and must be recreated. Boolean Default: True createDirs - Indicates whether to create directories if they don't exist. Boolean Default: True Setting this to false may improve performance a bit, but you'll receive an error when attempting to write to a directory that's not present. replaceFileContentsOnEachWrite - Indicates whether to replace file contents on each write instead of appending log message at the end. Boolean Default: False writeHeaderWhenInitialFileNotEmpty - Indicates whether to write the Header on initial creation of file appender, independent of file is empty or not. Boolean Default: False (Alternative one can use archiveOldFileOnStartup to ensure each application-session has its own individual log-file) Introduced with NLog v5.2.6 forceManaged - Indicates that the file target should only use managed methods. This disables some of the options. NLog v6 removed support for native methods, and always use managed FileStream fileAttributes - File attributes (Windows only). NLog v6 removed support for native methods and assigning file-attributes. Possible values: Archive - File should be archived. ~~Compressed~~ - Compress won't work due to .Net restrictions. You can use enableArchiveFileCompression. DeleteOnClose - Delete file after it is closed. Device - Device file. Encrypted - Encrypted file. Hidden - Hidden file. NoBuffering - The system opens a file with no system caching. Normal - Normal file. NotContentIndexed - File should not be indexed by the content indexing service. PosixSemantics - A file is accessed according to POSIX rules. Readonly - Read-only ReadOnly - Read-only file. ReparsePoint - Reparse point. SparseFile - Sparse file. System - System file. Temporary - File is temporary (should be kept in cache and not written to disk if possible). WriteThrough - The system writes through any intermediate cache and goes directly to disk. Archival Options archiveAboveSize - Size in bytes above which log files will be automatically archived. Long Before NLog ver. 4.5.7 then this would not work together with archiveNumbering=Date . Newer version will correctly merge into the existing file on archive. maxArchiveFiles - Maximum number of archive files that should be kept. If maxArchiveFiles is less or equal to 0, old files aren't deleted Integer Default: 0 maxArchiveDays - Maximum age of archive files that should be kept. Has no effect when archiveNumbering is Rolling . If maxArchiveDays is less or equal to 0, old files aren't deleted Integer Default: 0 Introduced with NLog 4.7 but not supporting archiveNumbering=\"Rolling\" , or archiveNumbering=\"Sequence\" with custom archiveFileName -path NLog 5.0 added support for archiveNumbering=\"Sequence\" with custom archiveFileName -path archiveSuffixFormat - Filename-suffix to append, when the archive-logic is rolling to the next file. Works like string.Format where {0} outputs archive-sequence-number and {1} outputs the archiveFileName -timestamp. Default: _{0:00} . Introduced with NLog v6 to replace archiveNumbering and archiveDateFormat . archiveOldFileOnStartup - Archive old log file on startup. Default: False deleteOldFileOnStartup - Indicates whether to delete old log file on startup. Boolean Default: False. This option works only when the \"FileName\" parameter denotes a single file. archiveFileName - Name of the file to be used for an archive. Layout It may contain a special placeholder {###} that will be replaced with a sequence of numbers depending on the archiving strategy. The number of hash characters used determines the number of numerical digits to be used for numbering files. NLog v6 replaces the special placeholder {###} with new ArchiveSuffixFormat Warning : Before NLog 4.5 then it would lead to very aggressive cleanup if having configured maxArchiveFiles without having specified the special placeholder {###}, as cleanup-wildcard would become any files in the archive folder (not just log files). archiveNumbering - Way file archives are numbered. See also Archive Numbering Examples Possible values: NLog v6 replaces ArchiveNumbering -option with new ArchiveSuffixFormat Rolling - Rolling style numbering (the most recent is always #0 then #1, ..., #N). Sequence - Sequence style numbering. The most recent archive has the highest number. Date - Date style numbering. The date is formatted according to the value of archiveDateFormat . Warning : Before NLog ver. 4.5.7 then this would not work together with archiveAboveSize . Newer version will correctly merge into the existing file on archive. DateAndSequence - Combination of Date and Sequence .Archives will be stamped with the prior period (Year, Month, Day) datetime. The most recent archive has the highest number (in combination with the date). The date is formatted according to the value of archiveDateFormat . archiveEvery - Indicates whether to automatically archive log files every time the specified time passes. Possible values: Day - Archive daily. Hour - Archive every hour. Minute - Archive every minute. Month - Archive every month. None - Don't archive based on time. Year - Archive every year. Sunday - Archive every Sunday. Introduced in NLog 4.4.4. Monday - Archive every Monday. Introduced in NLog 4.4.4. Tuesday - Archive every Tuesday. Introduced in NLog 4.4.4. Wednesday - Archive every Wednesday. Introduced in NLog 4.4.4. Thursday - Archive every Thursday. Introduced in NLog 4.4.4. Friday - Archive every Friday. Introduced in NLog 4.4.4. Saturday - Archive every Saturday. Introduced in NLog 4.4.4. Files are moved to the archive as part of the write operation if the current period of time changes. For example if the current hour changes from 10 to 11, the first write that will occur on or after 11:00 will trigger the archiving. archiveDateFormat - Specifies the date format used for archive numbering. Default format depends on the archive period. This option works only when the \"ArchiveNumbering\" parameter is set to Date or DateAndSequence NLog v6 replaces ArchiveDateFormat -option with new ArchiveSuffixFormat Default: yyyyMMdd Default when ArchiveEvery = Minute: yyyyMMddHHmm Default when ArchiveEvery = Hour: yyyyMMddHH Default when ArchiveEvery = Month: yyyyMM Default when ArchiveEvery = Year: yyyy archiveOldFileOnStartupAboveSize - File size threshold to archive old log file on startup. Default value is 0 which means that the file is archived as soon as archiveOldFileOnStartup is enabled. Introduced in NLog 4.7 NLog v6 replaces archiveOldFileOnStartupAboveSize -option with archiveOldFileOnStartup and archiveAboveSize . enableArchiveFileCompression - Indicates whether to compress the archive files into the zip files. Boolean Default: False Introduced in NLog ver. 4.0. Not supported for .Net35 + .Net40 and only works with static filename Before NLog ver. 5.0 then the filename inside the zip-file would be original filename, instead of archive-filename. NLog v6 removed enableArchiveFileCompression -option. Instead use NTFS-compression or setup cron-job / scheduled-task for nightly compression or GZip-File-Target or legacy NLog.Targets.ConcurrentFile writeFooterOnArchivingOnly - Indicates whether the footer should be written only when the file is archived. If False , the footer will also be written when starting to write to a different file and when the target is closed Boolean Default: False Performance Tuning Options keepFileOpen - Indicates whether to keep log file open instead of opening and closing it on each logging event. When set to false it will allow other applications to \"take over\" the filehandle, and NLog will fail logging to file. When set to false then it will give a major performance hit because it is expensive to open/close file-handle. If the FileName points to a network-path, then it is recommended to use keepFileOpen=\"false\" in combination with . Boolean Default: True (Before NLog 5.0 the default was false ) concurrentWrites - Enables support for optimized concurrent writes to same log file from multiple processes on the same machine-host, when using keepFileOpen = true. By using a special synchronization techniques that lets it keep the files open from multiple processes. The special synchronization cost performance and not compatible with platforms like UWP / Xamarin. Default: False (Before NLog 5.0 the default was true ) NLog v6 removed concurrentWrites -option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile openFileCacheTimeout - Maximum number of seconds that files are kept open. Configures Timer that automatically closes file-handles, that have been open for more than specified number of seconds. Integer Default: -1 openFileCacheSize - Maximum number of files to be kept open. Closes files in LRU (least-recently-used) ordering, so closes files unused for the longest period of time should the cache become full. Increasing the value can improve performance, when single file target is writing to many files (such as splitting by loglevel or by logger-name). But having too many file-handles open can also hurt performance. Integer Default: 5 networkWrites - Indicates whether concurrent writes to the log file by multiple processes on different network hosts. This effectively prevents files from being kept open, so behaves just like KeepFileOpen=\"false\" . Boolean Default: False NLog v6 removed networkWrites -option. Instead use KeepFileOpen=false . concurrentWriteAttemptDelay - Delay in milliseconds to wait before attempting to write to the file again. Integer Default: 1 The actual delay is a random value between 0 and the value specified in this parameter. On each failed attempt the delay base is doubled up to ConcurrentWriteAttempts times. Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be: a random value between 0 and 10 milliseconds - 1st attempt a random value between 0 and 20 milliseconds - 2nd attempt a random value between 0 and 40 milliseconds - 3rd attempt a random value between 0 and 80 milliseconds - 4th attempt ... and so on. NLog v6 removed concurrentWrites -option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile concurrentWriteAttempts - Number of times the write is attempted on the file before NLog discards the log message. Integer Default: 10 NLog v6 removed concurrentWrites -option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile cleanupFileName - before writing to a file, the name of the file get checked for illegal characters (OS dependent). This can be costly if a lot of messages are written. The cleanup is cached for fixed names (no layout renderers). Set this to false for optimal performance (but beware of the file name, if it's wrong, nothing gets written). Default: true . Introduced in NLog 4.2.3. NLog v6 removed cleanupFileName -option, since it happens implicitly. bufferSize - Log file buffer size in bytes. Notice Large-Object-Heap will be used when size 85000 or above. Integer Default: 32768 autoFlush - Ensures file buffers are flushed after each log message, thus avoiding loss of critical log-messages during unexpected application-crash or -exit. The operating system will ensure that flushed data will be written to disk, even if application has left the planet. But if the operating system also crashes or computer-power-failure, then flushed data might still be lost, as it is not flush with write-through. If log-messages are not super critical for troubleshooting, or not having issues with unexptected application crashes, then one can improve performance with AutoFlush = false (See also openFileFlushTimeout ). Boolean Default: True openFileFlushTimeout - Number of seconds between explicit flush of file buffers. Helps to ensure file buffers are eventually flushed when autoFlush = false . Integer Default: 0 (Disabled) > Introduced with NLog v4.5.7 Examples Simple logging The simplest use of File target is to produce single log file. In order to do this, put the following code in the configuration file such as NLog.config. Logs wil be written to logfile.txt in logs directory. Filename Directory File Target supports relative paths since NLog 4.3, where it will implicitly use ${BaseDir} (AppDomain.BaseDirectory). It is also possible to specify an absolute path or make use of these helpers: ${ProcessDir} - Executable Directory of process binary. ${CurrentDir} - Current Directory for startup. ${TempDir} - TEMP directory. ${SpecialFolder} - Special Folders like CommonApplicationData . Example using CommonApplicationData which is good when running as Windows Service: fileName=\"${specialfolder:folder=CommonApplicationData:cached=true}/AppName/logfile.txt\" Windows-Path - C:/ProgramData/AppName/logfile.txt To remove all doubt, then one can also use absolute-paths. And by using NLog config variables then one can reuse the absolute path for multiple file targets: It is also possible to override the directory at runtime using GDC : NLog.GlobalDiagnosticsContext.Set(\"logDirectory\", \"C:/Temp/\"); Batch write and asynchronous logging The file target has support for batch writing, where multiple log messages are written in one file-operation. Batch write will improve performance, especially when using KeepFileOpen=false . Batch writing is enabled automatically when using the AsyncWrapper . This can be done by adding the attribute async=\"true\" to the -element. Asynchronous logging is recommended for multi-threaded server applications, but might not be worth it for quick-finishing command line application. Make sure to remember to flush at application shutdown, or else output can be dropped. Multi processes writing same file The IIS-application can run multiple AppDomains, and each AppDomain operates like a child process. When multiple processes are concurrently writing to the same file, then some locking for coordination is needed: Operating System File Locks - Enabled with KeepFileOpen=false . File locking from operating system are not fair and doesn't scale when having more than 2 processes writing to the same file. Exceptions will be thrown when one process tries to open a file, that is currently in use by another process. NLog tries to handle these exception by retrying on error, but will backoff so LogEvents are lost. Performance can be improved a lot by applying . Atomic File Append - The lock synchronization is fair, and happens at the operating system level. It is the fastest concurrent mode available with minimum overhead. Each application performs non-buffered file-append with help from operating system O_APPEND . NLog v6 introduces Atomic-File-Target that supports both .NET Framework and new NET platforms on both Windows and Linux. Before this option was only available for .NET Framework. Global Mutex Locks - Each application acquires a handle to a global mutex controlled by the operating system. But will not work when application doesn't have user-capabilities that allows access to global mutexes (Ex. Mobile platforms like Android / iOS). NLog v6 have moved the logic into NLog.Targets.ConcurrentFile -nuget-package. NLog v6 has removed support for ConcurrentWrites -option in the standard NLog File-Target. Instead one must use additional nuget-package like Atomic-File-Target or NLog.Targets.ConcurrentFile . It is recommended to enable asynchronous logging as it will reduce the overhead from file locking coordination (Especially when using KeepFileOpen=false and ConcurrentWrites=true ). Archive old log files NLog 4.5 makes it easy to setup archive logic to cleanup old files when using dynamic fileName-Layout. You just need to configure maxArchiveFiles and it will automatically perform cleanup. NLog 4.7 (and newer) adds support for the option MaxArchiveDays . It works like MaxArchiveFiles but instead inspect the timestamp of the files in the archive. They can be combined. Ex. maxArchiveDays=\"30\" maxArchiveFiles=\"90\" (Deletes files older than 30 days or if more than 90 files in archive). Dynamic vs. Static Archive Logic Do not mix \"Dynamic FileName Archive Logic\" together with \"Static FileName Archive Logic\" as one will get unexpected archive behavior. Dynamic FileName Archive Logic - Enabled by using fileName=\"${basedir}/AppLog.${shortdate}.log\" . This means it will roll / archive dynamically because of the layout-renderer-logic in ${date} (Changes on day-change). Never use it together with archiveFileName=\"...\" or archiveEvery=\"Day\" . Static FileName Archive Logic - Enabled by using archiveEvery=\"Day\" and archiveFileName=\"...\" . This means it will expect the FileName to be static (Ex. fileName=\"${basedir}/AppLog.txt\" ). Never use dynamic layout (Ex. ${date} ) in archiveFileName=\"...\" or fileName=\"...\" . Static-filename-archive-logic are well suited for being used with tail-applications, that monitors a single static-filename. But there might be issues when NLog tries to rename/move the old file to create new file (Ex. when locked by external file-viewer). It is possible to move files into a different folder when using static-filename-archive-logic: - archiveFileName - Can move old files into other folder and also rename with datetime/seq-no There are several FileTarget-Archive-Examples of how to use Static FileName with ArchiveEvery. Per-level log files Single File target can be used to write to multiple files at once. The following configuration will cause log entries for each log level to be written to a separate file, so you will get: * Trace.log * Debug.log * Info.log * Warn.log * Error.log * Fatal.log JSON Log-file The NLog FileTarget can be combined with the JsonLayout to create Json-LogFile: CSV Log-file The NLog FileTarget can be combined with the CsvLayout to create comma-separated CSV-LogFile. Here is an example of a file with 4 columns: ","title":"File target"},{"location":"File-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"File-target/#parameters","text":"","title":"Parameters"},{"location":"File-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"File-target/#layout-options","text":"layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} header - Header. Layout footer - Footer. Layout encoding - File encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Default: Utf-8 (Before NLog 5.0 the default was Encoding.Default ) writeBom - Indicates whether to write BOM (byte order mark) in created files. Boolean Default: false. Introduced with NLog 4.5. And after NLog 5.0 is is automatically enabled when encoding UTF16 or UTF32. lineEnding - Line ending mode. Possible values: CR - Insert CR character (ASCII 13) after each line. CRLF - Insert CR LF sequence (ASCII 13, ASCII 10) after each line. Default - Insert platform-dependent end-of-line sequence after each line. LF - Insert LF character (ASCII 10) after each line. NULL - Null terminator (ASCII 0) after each line. None - Don't insert any line ending.","title":"Layout Options"},{"location":"File-target/#output-options","text":"fileName - Name of the file to write to. Layout Required. This FileName string is a layout which may include instances of layout renderers. This lets you use a single target to write to multiple files. The following value makes NLog write logging events to files based on the log level in the directory where the application runs. ${basedir}/${level}.log All Debug messages will go to Debug.log , all Info messages will go to Info.log and so on. You can combine as many of the layout renderers as you want to produce an arbitrary log file name. See also Filename Directory enableFileDelete - Indicates whether to enable log file(s) to be deleted. The FileTarget will periodically verify if the file has been deleted and must be recreated. Boolean Default: True createDirs - Indicates whether to create directories if they don't exist. Boolean Default: True Setting this to false may improve performance a bit, but you'll receive an error when attempting to write to a directory that's not present. replaceFileContentsOnEachWrite - Indicates whether to replace file contents on each write instead of appending log message at the end. Boolean Default: False writeHeaderWhenInitialFileNotEmpty - Indicates whether to write the Header on initial creation of file appender, independent of file is empty or not. Boolean Default: False (Alternative one can use archiveOldFileOnStartup to ensure each application-session has its own individual log-file) Introduced with NLog v5.2.6 forceManaged - Indicates that the file target should only use managed methods. This disables some of the options. NLog v6 removed support for native methods, and always use managed FileStream fileAttributes - File attributes (Windows only). NLog v6 removed support for native methods and assigning file-attributes. Possible values: Archive - File should be archived. ~~Compressed~~ - Compress won't work due to .Net restrictions. You can use enableArchiveFileCompression. DeleteOnClose - Delete file after it is closed. Device - Device file. Encrypted - Encrypted file. Hidden - Hidden file. NoBuffering - The system opens a file with no system caching. Normal - Normal file. NotContentIndexed - File should not be indexed by the content indexing service. PosixSemantics - A file is accessed according to POSIX rules. Readonly - Read-only ReadOnly - Read-only file. ReparsePoint - Reparse point. SparseFile - Sparse file. System - System file. Temporary - File is temporary (should be kept in cache and not written to disk if possible). WriteThrough - The system writes through any intermediate cache and goes directly to disk.","title":"Output Options"},{"location":"File-target/#archival-options","text":"archiveAboveSize - Size in bytes above which log files will be automatically archived. Long Before NLog ver. 4.5.7 then this would not work together with archiveNumbering=Date . Newer version will correctly merge into the existing file on archive. maxArchiveFiles - Maximum number of archive files that should be kept. If maxArchiveFiles is less or equal to 0, old files aren't deleted Integer Default: 0 maxArchiveDays - Maximum age of archive files that should be kept. Has no effect when archiveNumbering is Rolling . If maxArchiveDays is less or equal to 0, old files aren't deleted Integer Default: 0 Introduced with NLog 4.7 but not supporting archiveNumbering=\"Rolling\" , or archiveNumbering=\"Sequence\" with custom archiveFileName -path NLog 5.0 added support for archiveNumbering=\"Sequence\" with custom archiveFileName -path archiveSuffixFormat - Filename-suffix to append, when the archive-logic is rolling to the next file. Works like string.Format where {0} outputs archive-sequence-number and {1} outputs the archiveFileName -timestamp. Default: _{0:00} . Introduced with NLog v6 to replace archiveNumbering and archiveDateFormat . archiveOldFileOnStartup - Archive old log file on startup. Default: False deleteOldFileOnStartup - Indicates whether to delete old log file on startup. Boolean Default: False. This option works only when the \"FileName\" parameter denotes a single file. archiveFileName - Name of the file to be used for an archive. Layout It may contain a special placeholder {###} that will be replaced with a sequence of numbers depending on the archiving strategy. The number of hash characters used determines the number of numerical digits to be used for numbering files. NLog v6 replaces the special placeholder {###} with new ArchiveSuffixFormat Warning : Before NLog 4.5 then it would lead to very aggressive cleanup if having configured maxArchiveFiles without having specified the special placeholder {###}, as cleanup-wildcard would become any files in the archive folder (not just log files). archiveNumbering - Way file archives are numbered. See also Archive Numbering Examples Possible values: NLog v6 replaces ArchiveNumbering -option with new ArchiveSuffixFormat Rolling - Rolling style numbering (the most recent is always #0 then #1, ..., #N). Sequence - Sequence style numbering. The most recent archive has the highest number. Date - Date style numbering. The date is formatted according to the value of archiveDateFormat . Warning : Before NLog ver. 4.5.7 then this would not work together with archiveAboveSize . Newer version will correctly merge into the existing file on archive. DateAndSequence - Combination of Date and Sequence .Archives will be stamped with the prior period (Year, Month, Day) datetime. The most recent archive has the highest number (in combination with the date). The date is formatted according to the value of archiveDateFormat . archiveEvery - Indicates whether to automatically archive log files every time the specified time passes. Possible values: Day - Archive daily. Hour - Archive every hour. Minute - Archive every minute. Month - Archive every month. None - Don't archive based on time. Year - Archive every year. Sunday - Archive every Sunday. Introduced in NLog 4.4.4. Monday - Archive every Monday. Introduced in NLog 4.4.4. Tuesday - Archive every Tuesday. Introduced in NLog 4.4.4. Wednesday - Archive every Wednesday. Introduced in NLog 4.4.4. Thursday - Archive every Thursday. Introduced in NLog 4.4.4. Friday - Archive every Friday. Introduced in NLog 4.4.4. Saturday - Archive every Saturday. Introduced in NLog 4.4.4. Files are moved to the archive as part of the write operation if the current period of time changes. For example if the current hour changes from 10 to 11, the first write that will occur on or after 11:00 will trigger the archiving. archiveDateFormat - Specifies the date format used for archive numbering. Default format depends on the archive period. This option works only when the \"ArchiveNumbering\" parameter is set to Date or DateAndSequence NLog v6 replaces ArchiveDateFormat -option with new ArchiveSuffixFormat Default: yyyyMMdd Default when ArchiveEvery = Minute: yyyyMMddHHmm Default when ArchiveEvery = Hour: yyyyMMddHH Default when ArchiveEvery = Month: yyyyMM Default when ArchiveEvery = Year: yyyy archiveOldFileOnStartupAboveSize - File size threshold to archive old log file on startup. Default value is 0 which means that the file is archived as soon as archiveOldFileOnStartup is enabled. Introduced in NLog 4.7 NLog v6 replaces archiveOldFileOnStartupAboveSize -option with archiveOldFileOnStartup and archiveAboveSize . enableArchiveFileCompression - Indicates whether to compress the archive files into the zip files. Boolean Default: False Introduced in NLog ver. 4.0. Not supported for .Net35 + .Net40 and only works with static filename Before NLog ver. 5.0 then the filename inside the zip-file would be original filename, instead of archive-filename. NLog v6 removed enableArchiveFileCompression -option. Instead use NTFS-compression or setup cron-job / scheduled-task for nightly compression or GZip-File-Target or legacy NLog.Targets.ConcurrentFile writeFooterOnArchivingOnly - Indicates whether the footer should be written only when the file is archived. If False , the footer will also be written when starting to write to a different file and when the target is closed Boolean Default: False","title":"Archival Options"},{"location":"File-target/#performance-tuning-options","text":"keepFileOpen - Indicates whether to keep log file open instead of opening and closing it on each logging event. When set to false it will allow other applications to \"take over\" the filehandle, and NLog will fail logging to file. When set to false then it will give a major performance hit because it is expensive to open/close file-handle. If the FileName points to a network-path, then it is recommended to use keepFileOpen=\"false\" in combination with . Boolean Default: True (Before NLog 5.0 the default was false ) concurrentWrites - Enables support for optimized concurrent writes to same log file from multiple processes on the same machine-host, when using keepFileOpen = true. By using a special synchronization techniques that lets it keep the files open from multiple processes. The special synchronization cost performance and not compatible with platforms like UWP / Xamarin. Default: False (Before NLog 5.0 the default was true ) NLog v6 removed concurrentWrites -option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile openFileCacheTimeout - Maximum number of seconds that files are kept open. Configures Timer that automatically closes file-handles, that have been open for more than specified number of seconds. Integer Default: -1 openFileCacheSize - Maximum number of files to be kept open. Closes files in LRU (least-recently-used) ordering, so closes files unused for the longest period of time should the cache become full. Increasing the value can improve performance, when single file target is writing to many files (such as splitting by loglevel or by logger-name). But having too many file-handles open can also hurt performance. Integer Default: 5 networkWrites - Indicates whether concurrent writes to the log file by multiple processes on different network hosts. This effectively prevents files from being kept open, so behaves just like KeepFileOpen=\"false\" . Boolean Default: False NLog v6 removed networkWrites -option. Instead use KeepFileOpen=false . concurrentWriteAttemptDelay - Delay in milliseconds to wait before attempting to write to the file again. Integer Default: 1 The actual delay is a random value between 0 and the value specified in this parameter. On each failed attempt the delay base is doubled up to ConcurrentWriteAttempts times. Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be: a random value between 0 and 10 milliseconds - 1st attempt a random value between 0 and 20 milliseconds - 2nd attempt a random value between 0 and 40 milliseconds - 3rd attempt a random value between 0 and 80 milliseconds - 4th attempt ... and so on. NLog v6 removed concurrentWrites -option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile concurrentWriteAttempts - Number of times the write is attempted on the file before NLog discards the log message. Integer Default: 10 NLog v6 removed concurrentWrites -option. Instead use Atomic-File-Target or legacy NLog.Targets.ConcurrentFile cleanupFileName - before writing to a file, the name of the file get checked for illegal characters (OS dependent). This can be costly if a lot of messages are written. The cleanup is cached for fixed names (no layout renderers). Set this to false for optimal performance (but beware of the file name, if it's wrong, nothing gets written). Default: true . Introduced in NLog 4.2.3. NLog v6 removed cleanupFileName -option, since it happens implicitly. bufferSize - Log file buffer size in bytes. Notice Large-Object-Heap will be used when size 85000 or above. Integer Default: 32768 autoFlush - Ensures file buffers are flushed after each log message, thus avoiding loss of critical log-messages during unexpected application-crash or -exit. The operating system will ensure that flushed data will be written to disk, even if application has left the planet. But if the operating system also crashes or computer-power-failure, then flushed data might still be lost, as it is not flush with write-through. If log-messages are not super critical for troubleshooting, or not having issues with unexptected application crashes, then one can improve performance with AutoFlush = false (See also openFileFlushTimeout ). Boolean Default: True openFileFlushTimeout - Number of seconds between explicit flush of file buffers. Helps to ensure file buffers are eventually flushed when autoFlush = false . Integer Default: 0 (Disabled) > Introduced with NLog v4.5.7","title":"Performance Tuning Options"},{"location":"File-target/#examples","text":"","title":"Examples"},{"location":"File-target/#simple-logging","text":"The simplest use of File target is to produce single log file. In order to do this, put the following code in the configuration file such as NLog.config. Logs wil be written to logfile.txt in logs directory. ","title":"Simple logging"},{"location":"File-target/#filename-directory","text":"File Target supports relative paths since NLog 4.3, where it will implicitly use ${BaseDir} (AppDomain.BaseDirectory). It is also possible to specify an absolute path or make use of these helpers: ${ProcessDir} - Executable Directory of process binary. ${CurrentDir} - Current Directory for startup. ${TempDir} - TEMP directory. ${SpecialFolder} - Special Folders like CommonApplicationData . Example using CommonApplicationData which is good when running as Windows Service: fileName=\"${specialfolder:folder=CommonApplicationData:cached=true}/AppName/logfile.txt\" Windows-Path - C:/ProgramData/AppName/logfile.txt To remove all doubt, then one can also use absolute-paths. And by using NLog config variables then one can reuse the absolute path for multiple file targets: It is also possible to override the directory at runtime using GDC : NLog.GlobalDiagnosticsContext.Set(\"logDirectory\", \"C:/Temp/\");","title":"Filename Directory"},{"location":"File-target/#batch-write-and-asynchronous-logging","text":"The file target has support for batch writing, where multiple log messages are written in one file-operation. Batch write will improve performance, especially when using KeepFileOpen=false . Batch writing is enabled automatically when using the AsyncWrapper . This can be done by adding the attribute async=\"true\" to the -element. Asynchronous logging is recommended for multi-threaded server applications, but might not be worth it for quick-finishing command line application. Make sure to remember to flush at application shutdown, or else output can be dropped. ","title":"Batch write and asynchronous logging"},{"location":"File-target/#multi-processes-writing-same-file","text":"The IIS-application can run multiple AppDomains, and each AppDomain operates like a child process. When multiple processes are concurrently writing to the same file, then some locking for coordination is needed: Operating System File Locks - Enabled with KeepFileOpen=false . File locking from operating system are not fair and doesn't scale when having more than 2 processes writing to the same file. Exceptions will be thrown when one process tries to open a file, that is currently in use by another process. NLog tries to handle these exception by retrying on error, but will backoff so LogEvents are lost. Performance can be improved a lot by applying . Atomic File Append - The lock synchronization is fair, and happens at the operating system level. It is the fastest concurrent mode available with minimum overhead. Each application performs non-buffered file-append with help from operating system O_APPEND . NLog v6 introduces Atomic-File-Target that supports both .NET Framework and new NET platforms on both Windows and Linux. Before this option was only available for .NET Framework. Global Mutex Locks - Each application acquires a handle to a global mutex controlled by the operating system. But will not work when application doesn't have user-capabilities that allows access to global mutexes (Ex. Mobile platforms like Android / iOS). NLog v6 have moved the logic into NLog.Targets.ConcurrentFile -nuget-package. NLog v6 has removed support for ConcurrentWrites -option in the standard NLog File-Target. Instead one must use additional nuget-package like Atomic-File-Target or NLog.Targets.ConcurrentFile . It is recommended to enable asynchronous logging as it will reduce the overhead from file locking coordination (Especially when using KeepFileOpen=false and ConcurrentWrites=true ).","title":"Multi processes writing same file"},{"location":"File-target/#archive-old-log-files","text":"NLog 4.5 makes it easy to setup archive logic to cleanup old files when using dynamic fileName-Layout. You just need to configure maxArchiveFiles and it will automatically perform cleanup. NLog 4.7 (and newer) adds support for the option MaxArchiveDays . It works like MaxArchiveFiles but instead inspect the timestamp of the files in the archive. They can be combined. Ex. maxArchiveDays=\"30\" maxArchiveFiles=\"90\" (Deletes files older than 30 days or if more than 90 files in archive).","title":"Archive old log files"},{"location":"File-target/#dynamic-vs-static-archive-logic","text":"Do not mix \"Dynamic FileName Archive Logic\" together with \"Static FileName Archive Logic\" as one will get unexpected archive behavior. Dynamic FileName Archive Logic - Enabled by using fileName=\"${basedir}/AppLog.${shortdate}.log\" . This means it will roll / archive dynamically because of the layout-renderer-logic in ${date} (Changes on day-change). Never use it together with archiveFileName=\"...\" or archiveEvery=\"Day\" . Static FileName Archive Logic - Enabled by using archiveEvery=\"Day\" and archiveFileName=\"...\" . This means it will expect the FileName to be static (Ex. fileName=\"${basedir}/AppLog.txt\" ). Never use dynamic layout (Ex. ${date} ) in archiveFileName=\"...\" or fileName=\"...\" . Static-filename-archive-logic are well suited for being used with tail-applications, that monitors a single static-filename. But there might be issues when NLog tries to rename/move the old file to create new file (Ex. when locked by external file-viewer). It is possible to move files into a different folder when using static-filename-archive-logic: - archiveFileName - Can move old files into other folder and also rename with datetime/seq-no There are several FileTarget-Archive-Examples of how to use Static FileName with ArchiveEvery.","title":"Dynamic vs. Static Archive Logic"},{"location":"File-target/#per-level-log-files","text":"Single File target can be used to write to multiple files at once. The following configuration will cause log entries for each log level to be written to a separate file, so you will get: * Trace.log * Debug.log * Info.log * Warn.log * Error.log * Fatal.log ","title":"Per-level log files"},{"location":"File-target/#json-log-file","text":"The NLog FileTarget can be combined with the JsonLayout to create Json-LogFile: ","title":"JSON Log-file"},{"location":"File-target/#csv-log-file","text":"The NLog FileTarget can be combined with the CsvLayout to create comma-separated CSV-LogFile. Here is an example of a file with 4 columns: ","title":"CSV Log-file"},{"location":"FileContents-layout-renderer/","text":"Renders contents of the specified file. Example if having a flat file containing a special setting value. Platforms Supported: All (Removed with NLog v6 - Instead setup custom layout-renderer with method-delegate) Configuration Syntax ${file-contents:encoding=Encoding:fileName=Layout} Parameters File Options encoding - Encoding used in the file.Encoding fileName - Name of the file.Layout Notes If the file content doesn't change, then adding the option :cached=true will give a performance boost.","title":"FileContents layout renderer"},{"location":"FileContents-layout-renderer/#configuration-syntax","text":"${file-contents:encoding=Encoding:fileName=Layout}","title":"Configuration Syntax"},{"location":"FileContents-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"FileContents-layout-renderer/#file-options","text":"encoding - Encoding used in the file.Encoding fileName - Name of the file.Layout","title":"File Options"},{"location":"FileContents-layout-renderer/#notes","text":"If the file content doesn't change, then adding the option :cached=true will give a performance boost.","title":"Notes"},{"location":"FileTarget-Archive-Examples/","text":"NLog v4.5 improves dynamic archive mode, so it is easy to archive old files . NLog v6.0 have introduced ArchiveSuffixFormat and obsoleted the following options: - ArchiveDateFormat - ArchiveNumbering - ArchiveFileKind - ArchiveOldFileOnStartupAboveSize - EnableArchiveFileCompression These examples shows the archive options for the static-archive-mode. One should Not mix dynamic with static-archive-mode . Size-based file archival Log files can be automatically archived by moving them to another location after reaching certain size. The following configuration will produce the following files (and generate new file when file reaches 10KB): + logs/logfile.txt // the current log being written to + archives/log.000000.txt // The oldest log file + archives/log.000001.txt + archives/log.000002.txt + etc. Time-based file archival Log files can also be automatically archived based on time. This configuration will archive a file at the beginning of each day and will use rolling file naming, so log file from the previous day can always be found in archives//log.0.txt, log from two days ago is in archives//log.1.txt and so on. This configuration will keep at most 7 archive files, so logs older than one week will be automatically deleted: logs/logfile.txt // todays log being written to archives/log.0.txt // previous log file from yesterday archives/log.1.txt archives/log.2.txt archives/log.3.txt archives/log.4.txt archives/log.5.txt archives/log.6.txt // Oldest file defined by maxArchiveFiles=7 Archive every Week You can specify different archival time periods. For example, if you wanted to archive once a week on Tuesdays, you would set archiveEvery=\"Tuesday\" . Possible values for archiveEvery can be found above. This will result in the following files being created: + logfile.txt // the current log being written to + logfile.20170307.txt + logfile.20170314.txt + logfile.20170321.txt + etc. Archive Numbering Examples Rolling Example of file names (newest files first): logfile.txt log.0000.txt log.0001.txt log.0002.txt Sequence Example of file names (newest files first): logfile.txt log.0002.txt log.0001.txt log.0000.txt Date Example of file names (newest files first): logfile.txt log.20150731.txt log.20150730.txt DateAndSequence Example of file names (newest files first): logfile.txt log.20150730.3.txt log.20150730.2.txt log.20150730.1.txt Archive file in new folder NLog also has support for writing to a static fileName-Layout, and then move the file to archive-location and re-create new fresh file. But it only works when not including dynamic layout (Ex. ${date} ) in the fileName-Layout or archiveFileName-Layout. See also Do not mix dynamic-filename with static archive logic It will generate the following filenames (newest first): * AppLog.txt // the current log being written to * AppLog.20170321.txt * AppLog.20170314.txt * AppLog.20170307.txt One log file per application instance, remove old logs The following configuration will create a dedicated log file for each start of your application. Multiple instances can run in parallel and write to their respective log file. By adding a timestamp to the filename, each filename is unique (up to the second). Up to ten log files (active + nine archive) are kept. The removal of old logs works, when the archiveFileName contains a placeholder, archiveDateFormat has the same datetime format as in the name property, and archiveNumbering and archiveEvery are enabled. The $(cached:...) directive prevents that a new log file name is generated for every log entry. Log files will be named: * 2017-11-05 08_00_00.log * 2017-11-05 08_00_01.log * 2017-11-05 12_35_04.log * 2017-11-06 09_54_32.log * ... ","title":"FileTarget Archive Examples"},{"location":"FileTarget-Archive-Examples/#size-based-file-archival","text":"Log files can be automatically archived by moving them to another location after reaching certain size. The following configuration will produce the following files (and generate new file when file reaches 10KB): + logs/logfile.txt // the current log being written to + archives/log.000000.txt // The oldest log file + archives/log.000001.txt + archives/log.000002.txt + etc. ","title":"Size-based file archival"},{"location":"FileTarget-Archive-Examples/#time-based-file-archival","text":"Log files can also be automatically archived based on time. This configuration will archive a file at the beginning of each day and will use rolling file naming, so log file from the previous day can always be found in archives//log.0.txt, log from two days ago is in archives//log.1.txt and so on. This configuration will keep at most 7 archive files, so logs older than one week will be automatically deleted: logs/logfile.txt // todays log being written to archives/log.0.txt // previous log file from yesterday archives/log.1.txt archives/log.2.txt archives/log.3.txt archives/log.4.txt archives/log.5.txt archives/log.6.txt // Oldest file defined by maxArchiveFiles=7 ","title":"Time-based file archival"},{"location":"FileTarget-Archive-Examples/#archive-every-week","text":"You can specify different archival time periods. For example, if you wanted to archive once a week on Tuesdays, you would set archiveEvery=\"Tuesday\" . Possible values for archiveEvery can be found above. This will result in the following files being created: + logfile.txt // the current log being written to + logfile.20170307.txt + logfile.20170314.txt + logfile.20170321.txt + etc. ","title":"Archive every Week"},{"location":"FileTarget-Archive-Examples/#archive-numbering-examples","text":"","title":"Archive Numbering Examples"},{"location":"FileTarget-Archive-Examples/#rolling","text":" Example of file names (newest files first): logfile.txt log.0000.txt log.0001.txt log.0002.txt","title":"Rolling"},{"location":"FileTarget-Archive-Examples/#sequence","text":" Example of file names (newest files first): logfile.txt log.0002.txt log.0001.txt log.0000.txt","title":"Sequence"},{"location":"FileTarget-Archive-Examples/#date","text":" Example of file names (newest files first): logfile.txt log.20150731.txt log.20150730.txt","title":"Date"},{"location":"FileTarget-Archive-Examples/#dateandsequence","text":" Example of file names (newest files first): logfile.txt log.20150730.3.txt log.20150730.2.txt log.20150730.1.txt","title":"DateAndSequence"},{"location":"FileTarget-Archive-Examples/#archive-file-in-new-folder","text":"NLog also has support for writing to a static fileName-Layout, and then move the file to archive-location and re-create new fresh file. But it only works when not including dynamic layout (Ex. ${date} ) in the fileName-Layout or archiveFileName-Layout. See also Do not mix dynamic-filename with static archive logic It will generate the following filenames (newest first): * AppLog.txt // the current log being written to * AppLog.20170321.txt * AppLog.20170314.txt * AppLog.20170307.txt","title":"Archive file in new folder"},{"location":"FileTarget-Archive-Examples/#one-log-file-per-application-instance-remove-old-logs","text":"The following configuration will create a dedicated log file for each start of your application. Multiple instances can run in parallel and write to their respective log file. By adding a timestamp to the filename, each filename is unique (up to the second). Up to ten log files (active + nine archive) are kept. The removal of old logs works, when the archiveFileName contains a placeholder, archiveDateFormat has the same datetime format as in the name property, and archiveNumbering and archiveEvery are enabled. The $(cached:...) directive prevents that a new log file name is generated for every log entry. Log files will be named: * 2017-11-05 08_00_00.log * 2017-11-05 08_00_01.log * 2017-11-05 12_35_04.log * 2017-11-06 09_54_32.log * ... ","title":"One log file per application instance, remove old logs"},{"location":"Filesystem-Normalize-Layout-Renderer/","text":"Filters characters not allowed in the file names by replacing them with safe character. Platforms Supported: All Configuration Syntax ${filesystem-normalize:fSNormalize=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:fSNormalize=Boolean} Parameters Advanced Options fSNormalize - Indicates whether to modify the output of this renderer so it can be used as a part of file path (illegal characters are replaced with '_'). Boolean Default: True Transformation Options inner - Wrapped layout. Layout","title":"Filesystem Normalize Layout Renderer"},{"location":"Filesystem-Normalize-Layout-Renderer/#configuration-syntax","text":"${filesystem-normalize:fSNormalize=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:fSNormalize=Boolean}","title":"Configuration Syntax"},{"location":"Filesystem-Normalize-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Filesystem-Normalize-Layout-Renderer/#advanced-options","text":"fSNormalize - Indicates whether to modify the output of this renderer so it can be used as a part of file path (illegal characters are replaced with '_'). Boolean Default: True","title":"Advanced Options"},{"location":"Filesystem-Normalize-Layout-Renderer/#transformation-options","text":"inner - Wrapped layout. Layout","title":"Transformation Options"},{"location":"Filtering-log-messages/","text":"Log messages may be filtered via either routing or filtering . Routing Logging Rules is the most efficient way to perform filtering using the name of the Logger. By skipping the allocation of LogEventInfo -objects, when no output is needed. One can silence a noisy loggger by redirecting it to a \"blackhole\" by not specifying writeTo= for the logging-rule. But if also needing custom filter logic, then one needs to use a Null target . NLog 4.5 made it possible to specify empty writeTo=\"\" , but when using older versions then Null target must be used. NLog v5 introduced the FinalMinLevel -option, because MaxLevel was causing a lot of headache and confusion. Filters With the use of then you can inspect the actual log-events and decide to ignore (blacklist) and/or allow (whitelist) the events. See also filter . e.g. 100\" action=\"Ignore\" /> The defaultAction -option was introduced with NLog 4.6. Before NLog 5.0 then the default value was Neutral . Note filters gives a performance penalty, because NLog LogEventInfo objects will be allocated upfront even if discarded by filter-result. Example in C The above configuration can be implemented directly in C# like this: var config = LogManager.Configuration; // some target var fileTarget = new FileTarget(); // set-up rule with filter var loggingRule = new LoggingRule(\"*\", fileTarget); loggingRule.FilterDefaultAction = FilterResult.Log; loggingRule.Filters.Add(new ConditionBasedFilter() { Condition = \"length('${message}') > 100\", Action = FilterResult.Ignore }); config.LoggingRules.Add(loggingRule); // apply config LogManager.Configuration = config; With NLog 5.0 then one can also do this: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterDynamicIgnore(evt => evt.FormattedMessage?.Length > 100).WriteToFile(\"log.txt\"); }); Global Threshold LogManager.GlobalThreshold can be assigned a LogLevel, and then only LogEvents with same severity (or higher) will be logged. LogManager.GlobalThreshold will overrule the configuration of logging rules. If logging rules says minLevel=\"Debug\" then LogManager.GlobalThreshold = LogLevel.Error will still win. if (IsProduction) NLog.LogManager.GlobalThreshold = NLog.LogLevel.Info; else NLog.LogManager.GlobalThreshold = NLog.LogLevel.Trace; // No global filter Null Logger LogManager.CreateNullLogger() will return a Logger-instance that will not generate any output. This can be used to silence certain components without depending on the NLog-configuration. var logger = IsProduction ? LogManager.CreateNullLogger() : LogManager.GetCurrentClassLogger(); logger.Info(\"No output when in production\"); DEBUG build only The .NET compiler has the ability to remove DEBUG-code when making Release-build. This means only Debug-build will give output, when using these conditional logging methods: - Logger.ConditionalTrace - Performs logging using NLog LogLevel.Trace - Logger.ConditionalDebug - Performs logging using NLog LogLevel.Debug _logger.ConditionalDebug(\"DEBUG build only output\"); It is shorthand of doing this: #if DEBUG _logger.Debug(\"DEBUG build only output\"); #endif Semi Dynamic Routing Rules Routing rules are more efficient than using dynamic filters, and the performance comes from static nature of the rules. NLog 4.6.7 introduced the ability to use Layout-logic for controlling LogLevel in the logging-rules, that can be explicitly refreshed. Then NLog 4.6.7 allows you to do this: #if DEBUG LogManager.Configuration.Variables[\"myLevel\"] = \"Debug\"; LogManager.ReconfigExistingLoggers(); // Explicit refresh of Layouts and updates active Logger-objects #endif It is possible to disable logging output completely by using minLevel=\"Off\" for the logging-rule. Possible use-case could be to activate special debug-mode, that changes the loglevel-variable as shown above, and then schedules a timer to restore default-level to \"Warn\" after 5 mins. Environment Specific Filtering There is a dedicated wiki-page for how to setup Environment specific NLog Logging Configuration so Production- and Development-environment can have different output-levels and destination targets. Fully Dynamic Filtering The Semi Dynamic Routing Rules improves the combination of NLog configuration loaded from config-file, and adjusting NLog configuration at runtime. When NLog configuration is created at runtime alone, then one have access to even more dynamic filtering logic capabilities. Ex. by using NLog.Filters.WhenMethodFilter : config.LoggingRules.Last().Filters.Add(new WhenMethodFilter(logEvent => ShouldIgnoreLogEvent(logEvent) ? FilterResult.Ignore : FilterResult.Log)); It is also possible to use the NLog.Config.LoggingRule constructor that specifies RuleName . Where it is possible to lookup the LoggingRule using LoggingConfiguration.FindRuleByName when needing to adjust it. Deprecated filters These filters are deprecated. They have been replace by the filter, which exposes uses modifiable conditions for filtering log events. filter - Matches when the calculated layout contains the specified substring. filter - Matches when the calculated layout is equal to the specified substring. filter - Matches when the calculated layout does NOT contain the specified substring. filter - Matches when the calculated layout is NOT equal to the specified substring.","title":"Filtering log messages"},{"location":"Filtering-log-messages/#routing","text":"Logging Rules is the most efficient way to perform filtering using the name of the Logger. By skipping the allocation of LogEventInfo -objects, when no output is needed. One can silence a noisy loggger by redirecting it to a \"blackhole\" by not specifying writeTo= for the logging-rule. But if also needing custom filter logic, then one needs to use a Null target . NLog 4.5 made it possible to specify empty writeTo=\"\" , but when using older versions then Null target must be used. NLog v5 introduced the FinalMinLevel -option, because MaxLevel was causing a lot of headache and confusion. ","title":"Routing"},{"location":"Filtering-log-messages/#filters","text":"With the use of then you can inspect the actual log-events and decide to ignore (blacklist) and/or allow (whitelist) the events. See also filter . e.g. 100\" action=\"Ignore\" /> The defaultAction -option was introduced with NLog 4.6. Before NLog 5.0 then the default value was Neutral . Note filters gives a performance penalty, because NLog LogEventInfo objects will be allocated upfront even if discarded by filter-result.","title":"Filters"},{"location":"Filtering-log-messages/#example-in-c","text":"The above configuration can be implemented directly in C# like this: var config = LogManager.Configuration; // some target var fileTarget = new FileTarget(); // set-up rule with filter var loggingRule = new LoggingRule(\"*\", fileTarget); loggingRule.FilterDefaultAction = FilterResult.Log; loggingRule.Filters.Add(new ConditionBasedFilter() { Condition = \"length('${message}') > 100\", Action = FilterResult.Ignore }); config.LoggingRules.Add(loggingRule); // apply config LogManager.Configuration = config; With NLog 5.0 then one can also do this: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterDynamicIgnore(evt => evt.FormattedMessage?.Length > 100).WriteToFile(\"log.txt\"); });","title":"Example in C"},{"location":"Filtering-log-messages/#global-threshold","text":"LogManager.GlobalThreshold can be assigned a LogLevel, and then only LogEvents with same severity (or higher) will be logged. LogManager.GlobalThreshold will overrule the configuration of logging rules. If logging rules says minLevel=\"Debug\" then LogManager.GlobalThreshold = LogLevel.Error will still win. if (IsProduction) NLog.LogManager.GlobalThreshold = NLog.LogLevel.Info; else NLog.LogManager.GlobalThreshold = NLog.LogLevel.Trace; // No global filter","title":"Global Threshold"},{"location":"Filtering-log-messages/#null-logger","text":"LogManager.CreateNullLogger() will return a Logger-instance that will not generate any output. This can be used to silence certain components without depending on the NLog-configuration. var logger = IsProduction ? LogManager.CreateNullLogger() : LogManager.GetCurrentClassLogger(); logger.Info(\"No output when in production\");","title":"Null Logger"},{"location":"Filtering-log-messages/#debug-build-only","text":"The .NET compiler has the ability to remove DEBUG-code when making Release-build. This means only Debug-build will give output, when using these conditional logging methods: - Logger.ConditionalTrace - Performs logging using NLog LogLevel.Trace - Logger.ConditionalDebug - Performs logging using NLog LogLevel.Debug _logger.ConditionalDebug(\"DEBUG build only output\"); It is shorthand of doing this: #if DEBUG _logger.Debug(\"DEBUG build only output\"); #endif","title":"DEBUG build only"},{"location":"Filtering-log-messages/#semi-dynamic-routing-rules","text":"Routing rules are more efficient than using dynamic filters, and the performance comes from static nature of the rules. NLog 4.6.7 introduced the ability to use Layout-logic for controlling LogLevel in the logging-rules, that can be explicitly refreshed. Then NLog 4.6.7 allows you to do this: #if DEBUG LogManager.Configuration.Variables[\"myLevel\"] = \"Debug\"; LogManager.ReconfigExistingLoggers(); // Explicit refresh of Layouts and updates active Logger-objects #endif It is possible to disable logging output completely by using minLevel=\"Off\" for the logging-rule. Possible use-case could be to activate special debug-mode, that changes the loglevel-variable as shown above, and then schedules a timer to restore default-level to \"Warn\" after 5 mins.","title":"Semi Dynamic Routing Rules"},{"location":"Filtering-log-messages/#environment-specific-filtering","text":"There is a dedicated wiki-page for how to setup Environment specific NLog Logging Configuration so Production- and Development-environment can have different output-levels and destination targets.","title":"Environment Specific Filtering"},{"location":"Filtering-log-messages/#fully-dynamic-filtering","text":"The Semi Dynamic Routing Rules improves the combination of NLog configuration loaded from config-file, and adjusting NLog configuration at runtime. When NLog configuration is created at runtime alone, then one have access to even more dynamic filtering logic capabilities. Ex. by using NLog.Filters.WhenMethodFilter : config.LoggingRules.Last().Filters.Add(new WhenMethodFilter(logEvent => ShouldIgnoreLogEvent(logEvent) ? FilterResult.Ignore : FilterResult.Log)); It is also possible to use the NLog.Config.LoggingRule constructor that specifies RuleName . Where it is possible to lookup the LoggingRule using LoggingConfiguration.FindRuleByName when needing to adjust it.","title":"Fully Dynamic Filtering"},{"location":"Filtering-log-messages/#deprecated-filters","text":"These filters are deprecated. They have been replace by the filter, which exposes uses modifiable conditions for filtering log events. filter - Matches when the calculated layout contains the specified substring. filter - Matches when the calculated layout is equal to the specified substring. filter - Matches when the calculated layout does NOT contain the specified substring. filter - Matches when the calculated layout is NOT equal to the specified substring.","title":"Deprecated filters"},{"location":"FilteringWrapper-target/","text":"Filters log entries based on a condition. Platforms Supported: All Configuration Syntax Filtering using condition: Filtering using filter (Introduced with NLog 4.6.4): Parameters General Options name - Name of the target. Filtering Options condition - Condition Expression . Log events who meet this condition will be forwarded to the wrapped target. Condition Required, unless having specified a filter . filter - Filter expression. For complex filtering logic like WhenRepeated-Filter . Introduced with NLog 4.6.4 Examples Repeat filter Filter repeated LogEvents, so it will only send mail every 5 minutes (Introduced with NLog 4.6.4): ${exception:format=Type} ","title":"FilteringWrapper target"},{"location":"FilteringWrapper-target/#configuration-syntax","text":"Filtering using condition: Filtering using filter (Introduced with NLog 4.6.4): ","title":"Configuration Syntax"},{"location":"FilteringWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"FilteringWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"FilteringWrapper-target/#filtering-options","text":"condition - Condition Expression . Log events who meet this condition will be forwarded to the wrapped target. Condition Required, unless having specified a filter . filter - Filter expression. For complex filtering logic like WhenRepeated-Filter . Introduced with NLog 4.6.4","title":"Filtering Options"},{"location":"FilteringWrapper-target/#examples","text":"","title":"Examples"},{"location":"FilteringWrapper-target/#repeat-filter","text":"Filter repeated LogEvents, so it will only send mail every 5 minutes (Introduced with NLog 4.6.4): ${exception:format=Type} ","title":"Repeat filter"},{"location":"Fluent-API/","text":"NLog v5 supports fluent API: - Fluent-Logger-API - Build LogEvents using a fluent C# API. - Fluent-Configuration-API - Build Configuration using a fluent C# API. Legacy Fluent API \u26a0\ufe0f The original NLog.Fluent -namespace introduced with NLog v3.2 became obsolete with NLog v5 Writing info message via fluent API. using NLog.Fluent; _logger.Info() .Message(\"This is a test fluent message '{0}'.\", DateTime.Now.Ticks) .Property(\"Test\", \"InfoWrite\") .Write(); Writing error message. try { string text = File.ReadAllText(path); } catch (Exception ex) { _logger.Error() .Message(\"Error reading file '{0}'.\", path) .Exception(ex) .Property(\"Test\", \"ErrorWrite\") .Write(); } Caller Info Use the static Log class so you don't have to include loggers in all of classes. The static Log class using .net 4.5 caller info to get the logger from the file name. Writing info message via static Log class with fluent API. Log.Info() .Message(\"This is a test fluent message.\") .Property(\"Test\", \"InfoWrite\") .Write(); Writing error message. try { string text = File.ReadAllText(path); } catch (Exception ex) { Log.Error() .Message(\"Error reading file '{0}'.\", path) .Exception(ex) .Property(\"Test\", \"ErrorWrite\") .Write(); }","title":"Fluent API"},{"location":"Fluent-API/#legacy-fluent-api","text":"\u26a0\ufe0f The original NLog.Fluent -namespace introduced with NLog v3.2 became obsolete with NLog v5 Writing info message via fluent API. using NLog.Fluent; _logger.Info() .Message(\"This is a test fluent message '{0}'.\", DateTime.Now.Ticks) .Property(\"Test\", \"InfoWrite\") .Write(); Writing error message. try { string text = File.ReadAllText(path); } catch (Exception ex) { _logger.Error() .Message(\"Error reading file '{0}'.\", path) .Exception(ex) .Property(\"Test\", \"ErrorWrite\") .Write(); }","title":"Legacy Fluent API"},{"location":"Fluent-API/#caller-info","text":"Use the static Log class so you don't have to include loggers in all of classes. The static Log class using .net 4.5 caller info to get the logger from the file name. Writing info message via static Log class with fluent API. Log.Info() .Message(\"This is a test fluent message.\") .Property(\"Test\", \"InfoWrite\") .Write(); Writing error message. try { string text = File.ReadAllText(path); } catch (Exception ex) { Log.Error() .Message(\"Error reading file '{0}'.\", path) .Exception(ex) .Property(\"Test\", \"ErrorWrite\") .Write(); }","title":"Caller Info"},{"location":"Fluent-Configuration-API/","text":"The NLog Fluent Configuration API allows you to configure NLog directly in C# instead of XML. No XML required. No separate configuration file required. Explicit setup logging as part of application startup Compile-time checking Full access to NLog features Allow building reusable components or libraries with addtional NLog extensions . The NLog LogFactory has support for fluent setup of the initial NLog configuration: - LoadConfiguration - Explicit build/adjust NLog config. Introduced with NLog 4.7 but heavily improved with NLog 5.0 - SetupExtensions - Registration of NLog extensions before loading configuration. Introduced with NLog 4.7 - SetupSerialization - Override default log output for specific object types. Introduced with NLog 4.7 - SetupLogFactory - LogFactory specific options. Introduced with NLog 5.0 - SetupInternalLogger - InternalLogger specific options. Introduced with NLog 4.7 - LoadConfigurationFromFile - For loading NLog config from specific xml file. Introduced with NLog 4.7 - LoadConfigurationFromXml - For loading NLog config from xml content. Introduced with NLog 4.7 Example with LoadConfiguration Build NLog config that writes everything to console: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().WriteToConsole() }); Build NLog config that writes to file and console: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: \"App_${shortdate}.txt\"); }); Build NLog config that writes to custom target:: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteTo(new MyCustomTarget() { Layout = \"${message}\" }); }); Build NLog config that restricts output from noisy logger: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger(\"Microsoft.*\").WriteToNil(finalMinLevel: LogLevel.Warn); builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); }); Example with SetupExtensions To register a custom LayoutRenderer: NLog.LogManager.Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer(\"trace_id\", (logevent) => CorrelationIdentifier.TraceId.ToString()) ); To register a custom Target: NLog.LogManager.Setup().SetupExtensions(ext => ext.RegisterTarget(\"MyFirst\") ); Example with SetupSerialization Override the default object reflection for System.Net.WebException : NLog.LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(ex => new { Type = ex.GetType().ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, InnerException = ex.InnerException, Status = ex.Status, Response = ex.Response.ToString(), // Call your custom method to render stream as string }) ); Skip default object reflection for ReadOnlyMemory : NLog.LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation>(obj => obj.Length) ); Examples with SetupLogFactory Explicit configure the global NLog TimeSource: NLog.LogManager.Setup().SetupLogFactory(fac => fac.SetTimeSourcAccurateUtc() ); Explicit activate exceptions on configuration errors: NLog.LogManager.Setup().SetupLogFactory(fac => fac.SetThrowConfigExceptions(true) ); Explicit configure the global LogLevel threshold: NLog.LogManager.Setup().SetupLogFactory(fac => fac.SetGlobalThreshold(LogLevel.Info) ); Example with SetupInternalLogger Write internal warnings and errors to console output: NLog.LogManager.Setup().SetupExtensions(intern => intern.SetMinimumLogLevel(LogLevel.Warn).LogToConsole(true) ); Register event handler to be called on warnings and errors: NLog.LogManager.Setup().SetupExtensions(intern => intern.SetMinimumLogLevel(LogLevel.Warn).AddLogSubscription((sender, evt) => ReportEvent(evt.Message)) ); Example with LoadConfigurationFromAppSettings Loads NLog config from appsettings.json (with fallback to NLog.confg) and requires NLog.Web.AspNetCore : var logger = LogManager.Setup() .LoadConfigurationFromAppSettings() .GetCurrentClassLogger(); See also NLog configuration with appsettings.json Example with LoadConfigurationFromSection Loads NLog config from Microsoft Configuration Section, and requires NLog.Extensions.Logging : var config = new ConfigurationBuilder() .SetBasePath(basePath ?? Directory.GetCurrentDirectory()) .AddJsonFile(\"appsettings.json\", optional: false, reloadOnChange: true) .AddJsonFile($\"appsettings.{environment}.json\", optional: true) .AddEnvironmentVariables().Build(); var logger = LogManager.Setup() .LoadConfigurationFromSection(config) .GetCurrentClassLogger(); See also NLog configuration with appsettings.json Example with LoadConfigurationFromFile Ensure NLog config has been loaded, and fail with exception when not: NLog.LogManager.Setup().LoadConfigurationFromFile(optional: false); Example with LoadConfigurationFromXml Load NLog config from custom location (like assembly resource): var fileXmlContent = File.ReadAllText(xmlFilePath); NLog.LogManager.Setup().LoadConfigurationFromXml(fileXmlContent);","title":"Fluent Configuration API"},{"location":"Fluent-Configuration-API/#example-with-loadconfiguration","text":"Build NLog config that writes everything to console: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().WriteToConsole() }); Build NLog config that writes to file and console: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: \"App_${shortdate}.txt\"); }); Build NLog config that writes to custom target:: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteTo(new MyCustomTarget() { Layout = \"${message}\" }); }); Build NLog config that restricts output from noisy logger: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger(\"Microsoft.*\").WriteToNil(finalMinLevel: LogLevel.Warn); builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); });","title":"Example with LoadConfiguration"},{"location":"Fluent-Configuration-API/#example-with-setupextensions","text":"To register a custom LayoutRenderer: NLog.LogManager.Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer(\"trace_id\", (logevent) => CorrelationIdentifier.TraceId.ToString()) ); To register a custom Target: NLog.LogManager.Setup().SetupExtensions(ext => ext.RegisterTarget(\"MyFirst\") );","title":"Example with SetupExtensions"},{"location":"Fluent-Configuration-API/#example-with-setupserialization","text":"Override the default object reflection for System.Net.WebException : NLog.LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(ex => new { Type = ex.GetType().ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, InnerException = ex.InnerException, Status = ex.Status, Response = ex.Response.ToString(), // Call your custom method to render stream as string }) ); Skip default object reflection for ReadOnlyMemory : NLog.LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation>(obj => obj.Length) );","title":"Example with SetupSerialization"},{"location":"Fluent-Configuration-API/#examples-with-setuplogfactory","text":"Explicit configure the global NLog TimeSource: NLog.LogManager.Setup().SetupLogFactory(fac => fac.SetTimeSourcAccurateUtc() ); Explicit activate exceptions on configuration errors: NLog.LogManager.Setup().SetupLogFactory(fac => fac.SetThrowConfigExceptions(true) ); Explicit configure the global LogLevel threshold: NLog.LogManager.Setup().SetupLogFactory(fac => fac.SetGlobalThreshold(LogLevel.Info) );","title":"Examples with SetupLogFactory"},{"location":"Fluent-Configuration-API/#example-with-setupinternallogger","text":"Write internal warnings and errors to console output: NLog.LogManager.Setup().SetupExtensions(intern => intern.SetMinimumLogLevel(LogLevel.Warn).LogToConsole(true) ); Register event handler to be called on warnings and errors: NLog.LogManager.Setup().SetupExtensions(intern => intern.SetMinimumLogLevel(LogLevel.Warn).AddLogSubscription((sender, evt) => ReportEvent(evt.Message)) );","title":"Example with SetupInternalLogger"},{"location":"Fluent-Configuration-API/#example-with-loadconfigurationfromappsettings","text":"Loads NLog config from appsettings.json (with fallback to NLog.confg) and requires NLog.Web.AspNetCore : var logger = LogManager.Setup() .LoadConfigurationFromAppSettings() .GetCurrentClassLogger(); See also NLog configuration with appsettings.json","title":"Example with LoadConfigurationFromAppSettings"},{"location":"Fluent-Configuration-API/#example-with-loadconfigurationfromsection","text":"Loads NLog config from Microsoft Configuration Section, and requires NLog.Extensions.Logging : var config = new ConfigurationBuilder() .SetBasePath(basePath ?? Directory.GetCurrentDirectory()) .AddJsonFile(\"appsettings.json\", optional: false, reloadOnChange: true) .AddJsonFile($\"appsettings.{environment}.json\", optional: true) .AddEnvironmentVariables().Build(); var logger = LogManager.Setup() .LoadConfigurationFromSection(config) .GetCurrentClassLogger(); See also NLog configuration with appsettings.json","title":"Example with LoadConfigurationFromSection"},{"location":"Fluent-Configuration-API/#example-with-loadconfigurationfromfile","text":"Ensure NLog config has been loaded, and fail with exception when not: NLog.LogManager.Setup().LoadConfigurationFromFile(optional: false);","title":"Example with LoadConfigurationFromFile"},{"location":"Fluent-Configuration-API/#example-with-loadconfigurationfromxml","text":"Load NLog config from custom location (like assembly resource): var fileXmlContent = File.ReadAllText(xmlFilePath); NLog.LogManager.Setup().LoadConfigurationFromXml(fileXmlContent);","title":"Example with LoadConfigurationFromXml"},{"location":"Fluent-Logger-API/","text":"Fluent Logger API NLog 5.0 introduces new fluent LogEventBuilder that can be activated with one of these extensions methods for ILogger : ForLogEvent - Builds base LogEvent ForTraceEvent - Builds LogEvent with Trace-LogLevel ForDebugEvent - Builds LogEvent with Debug-LogLevel ForInfoEvent - Builds LogEvent with Info-LogLevel ForWarnEvent - Builds LogEvent with Warn-LogLevel ForErrorEvent - Builds LogEvent with Error-LogLevel ForFatalEvent - Builds LogEvent with Fatal-LogLevel ForExceptionEvent - Builds LogEvent with Exception and Error-LogLevel To complete the fluent builder then call Log() to capture available callsite information with help from Caller Member Attributes , and then writes the actual LogEvent to any configured NLog targets. Replaces the old Fluent -namespace and also reduces memory-allocation when LogLevel not enabled. Examples Writing Info Message _logger.ForInfoEvent() .Message(\"This is a fluent message {0}.\", \"test\") .Property(\"PropertyName\", \"PropertyValue\") .Log(); Writing Exception Message. try { string text = File.ReadAllText(path); } catch (Exception ex) { _logger.ForExceptionEvent(ex) .Message(\"Error reading file '{0}'.\", path) .Property(\"Test\", \"InfoWrite\") .Log(); }","title":"Fluent Logger API"},{"location":"Fluent-Logger-API/#fluent-logger-api","text":"NLog 5.0 introduces new fluent LogEventBuilder that can be activated with one of these extensions methods for ILogger : ForLogEvent - Builds base LogEvent ForTraceEvent - Builds LogEvent with Trace-LogLevel ForDebugEvent - Builds LogEvent with Debug-LogLevel ForInfoEvent - Builds LogEvent with Info-LogLevel ForWarnEvent - Builds LogEvent with Warn-LogLevel ForErrorEvent - Builds LogEvent with Error-LogLevel ForFatalEvent - Builds LogEvent with Fatal-LogLevel ForExceptionEvent - Builds LogEvent with Exception and Error-LogLevel To complete the fluent builder then call Log() to capture available callsite information with help from Caller Member Attributes , and then writes the actual LogEvent to any configured NLog targets. Replaces the old Fluent -namespace and also reduces memory-allocation when LogLevel not enabled.","title":"Fluent Logger API"},{"location":"Fluent-Logger-API/#examples","text":"","title":"Examples"},{"location":"Fluent-Logger-API/#writing-info-message","text":"_logger.ForInfoEvent() .Message(\"This is a fluent message {0}.\", \"test\") .Property(\"PropertyName\", \"PropertyValue\") .Log();","title":"Writing Info Message"},{"location":"Fluent-Logger-API/#writing-exception-message","text":"try { string text = File.ReadAllText(path); } catch (Exception ex) { _logger.ForExceptionEvent(ex) .Message(\"Error reading file '{0}'.\", path) .Property(\"Test\", \"InfoWrite\") .Log(); }","title":"Writing Exception Message."},{"location":"FormControl-target/","text":"Page move to FormControlTarget - NLog.Windows.Forms","title":"FormControl target"},{"location":"GELF-Target/","text":"Sends log messages to the remote instance of Graylog Server using Graylog Extended Log Format (GELF). Platforms Supported: All - Requires nuget-package NLog.Targets.Network This target inherits from the Network Target , and so it has also all the properties of the Network Target available. Using the GelfLayout to produce GELF JSON output. Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Payload Options layout - Instance of GelfLayout that is used to format log messages. Layout Default: GelfLayout GelfHostName - Graylog Message Host-field. Default = ${hostname} GelfShortMessage - Graylog Message Short-Message-field (Truncates when longer than 250 chars). Default = ${message} GelfFullMessage - Graylog Message Full-Message-field. Default = ${message} GelfFacility - Legacy Graylog Message Facility-field. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. IncludeProperties - Comma separated string with names which properties to explicitly include. GelfField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout) encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default) Connection Options address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: * Discard - Discard new messages when reaching limit (Default) * Grow - Send message and ignore limit * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6 Example ","title":"GELF Target"},{"location":"GELF-Target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"GELF-Target/#parameters","text":"","title":"Parameters"},{"location":"GELF-Target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"GELF-Target/#payload-options","text":"layout - Instance of GelfLayout that is used to format log messages. Layout Default: GelfLayout GelfHostName - Graylog Message Host-field. Default = ${hostname} GelfShortMessage - Graylog Message Short-Message-field (Truncates when longer than 250 chars). Default = ${message} GelfFullMessage - Graylog Message Full-Message-field. Default = ${message} GelfFacility - Legacy Graylog Message Facility-field. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. IncludeProperties - Comma separated string with names which properties to explicitly include. GelfField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout) encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default)","title":"Payload Options"},{"location":"GELF-Target/#connection-options","text":"address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: * Discard - Discard new messages when reaching limit (Default) * Grow - Send message and ignore limit * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6","title":"Connection Options"},{"location":"GELF-Target/#example","text":" ","title":"Example"},{"location":"GZip-File-Target/","text":"Writes LogEvents to file using GZip compression, by extending the standard NLog File Target . Platforms Supported: All - Requires nuget-package NLog.Targets.GZipFile Configuration Syntax Parameters fileName - Name of the file to write to. Layout Required. layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} compressionLevel - File compression level Optimal - Optimize for small file size Fastest - Optimize for speed NoCompression - Disables GZip compression keepFileOpen - Disables GZip compression when configured to false . Default: true archiveOldFileOnStartup - Disables GZip compression when configured to false . Default: true Also inherits all parameters from the standard File-Target . Tools Linux has the zutils to make it easier to view / tail GZip compressed log-files: | Tool | Description | Example | |-------|--------------|----------| | zcat | Decompresses and copies files to standard output. | zcat | | zgrep | Decompresses and searches files for a regular expression. | zgrep -i | | zless | Decompresses and view in pages. | zless | | zmore | Decompresses and view in pages. | zmore | | ztest | Tests integrity of compressed files. | zcat |","title":"GZip File Target"},{"location":"GZip-File-Target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"GZip-File-Target/#parameters","text":"fileName - Name of the file to write to. Layout Required. layout - Text to be rendered. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} compressionLevel - File compression level Optimal - Optimize for small file size Fastest - Optimize for speed NoCompression - Disables GZip compression keepFileOpen - Disables GZip compression when configured to false . Default: true archiveOldFileOnStartup - Disables GZip compression when configured to false . Default: true Also inherits all parameters from the standard File-Target .","title":"Parameters"},{"location":"GZip-File-Target/#tools","text":"Linux has the zutils to make it easier to view / tail GZip compressed log-files: | Tool | Description | Example | |-------|--------------|----------| | zcat | Decompresses and copies files to standard output. | zcat | | zgrep | Decompresses and searches files for a regular expression. | zgrep -i | | zless | Decompresses and view in pages. | zless | | zmore | Decompresses and view in pages. | zmore | | ztest | Tests integrity of compressed files. | zcat |","title":"Tools"},{"location":"Gc-layout-renderer/","text":"The information about the garbage collector. Platforms Supported: All Configuration Syntax ${gc:property=Enum} Parameters Rendering Options property - Property to retrieve. Default: TotalMemory Possible values: CollectionCount0 - The number of Gen0 collections. CollectionCount1 - The number of Gen1 collections. CollectionCount2 - The number of Gen2 collections. MaxGeneration - Maximum generation number supported by GC. TotalMemory - Managed heap size in bytes (ignoring memory fragmentation). TotalMemoryForceCollection - Managed heap size in bytes (after having forced full garbage collection) > Marked obsolete with NLog v6.2 since method is not recommended, because of the application wide side-effects. WorkingSet - Physical memory used by the process both managed and unmanaged/native memory. > Introduced with NLog v6.2 Format - The ToString(...) format-specifier. Ex. \"N0\" to output 1000-delimiter to be easier on the eye. > Introduced with NLog v6.2","title":"Gc layout renderer"},{"location":"Gc-layout-renderer/#configuration-syntax","text":"${gc:property=Enum}","title":"Configuration Syntax"},{"location":"Gc-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Gc-layout-renderer/#rendering-options","text":"property - Property to retrieve. Default: TotalMemory Possible values: CollectionCount0 - The number of Gen0 collections. CollectionCount1 - The number of Gen1 collections. CollectionCount2 - The number of Gen2 collections. MaxGeneration - Maximum generation number supported by GC. TotalMemory - Managed heap size in bytes (ignoring memory fragmentation). TotalMemoryForceCollection - Managed heap size in bytes (after having forced full garbage collection) > Marked obsolete with NLog v6.2 since method is not recommended, because of the application wide side-effects. WorkingSet - Physical memory used by the process both managed and unmanaged/native memory. > Introduced with NLog v6.2 Format - The ToString(...) format-specifier. Ex. \"N0\" to output 1000-delimiter to be easier on the eye. > Introduced with NLog v6.2","title":"Rendering Options"},{"location":"Gdc-layout-renderer/","text":"Global Diagnostic Context (GDC) - Dictionary structure for global settings for the entire application-instance. Platforms Supported: All (NLog 4.1 allows storing any Object type, not just String ) GDC properties should be assigned at application-startup and remain static and immutable during the lifetime of the application/process. Do NOT modify the GDC as part of the logging operations, as it will have unwanted side-effects. If needing to include additional context information for a specific logevent, then consider using Logger.WithProperty() or Logger.PushScopeProperty() . See also NLog Context . NLog also supports alternative locations for global state like Environment Variables , AppSettings.json , etc. See also Environment-specific-NLog-Logging-Configuration Configuration Syntax ${gdc:item=String} Parameters Rendering Options item - Name of the item. Required. Note Before NLog 5.0 it was case-sensitive. culture - The culture used for rendering. Introduced in NLog 5.0. Default value is CultureInfo.InvariantCulture format - Format for conversion from object to string. Introduced in NLog 4.5. format=@ means serialize object properties into Json-format. Example Simple Properties The following example demonstrates the basic usage of the Global Diagnostics Context. GlobalDiagnosticsContext.Set(\"myDataBase\",\"someValue\"); GlobalDiagnosticsContext.Set(\"informationGroup\", new { One = 1, Two = 2 }); GlobalDiagnosticsContext.Set(\"anyObject\", anyObjectReferenceOrString); Add the following to your logger configuration to reference the above properties: ${gdc:item=myDatabase} ${gdc:item=informationGroup} ${gdc:item=anyObject} Dynamic Properties The Global Diagnostics Context (GDC) can also store complex objects, and can be used as an alternative to registering own custom layout renderer . NLog sees the GDC like global variables that doesn't depend on thread execution context, so make sure any complex object logic doesn't depend on application logging thread-state. public class ApplicationStateProperty : IFormattable { public static readonly ApplicationStateProperty Default = new ApplicationStateProperty(); private ApplicationStateProperty() { } public override string ToString() { // Physical memory used by application process (in megabytes) return ((long)(System.Environment.WorkingSet / (1024 * 1024))).ToString(); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } } During initialization, add the following code: GlobalDiagnosticsContext.Set(\"AppMemorySize\", ApplicationStateProperty.Default); To reference the AppMemorySize Global Diagnostics Context property. ${gdc:item=AppMemorySize} Notes When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.","title":"Gdc layout renderer"},{"location":"Gdc-layout-renderer/#configuration-syntax","text":"${gdc:item=String}","title":"Configuration Syntax"},{"location":"Gdc-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Gdc-layout-renderer/#rendering-options","text":"item - Name of the item. Required. Note Before NLog 5.0 it was case-sensitive. culture - The culture used for rendering. Introduced in NLog 5.0. Default value is CultureInfo.InvariantCulture format - Format for conversion from object to string. Introduced in NLog 4.5. format=@ means serialize object properties into Json-format.","title":"Rendering Options"},{"location":"Gdc-layout-renderer/#example","text":"","title":"Example"},{"location":"Gdc-layout-renderer/#simple-properties","text":"The following example demonstrates the basic usage of the Global Diagnostics Context. GlobalDiagnosticsContext.Set(\"myDataBase\",\"someValue\"); GlobalDiagnosticsContext.Set(\"informationGroup\", new { One = 1, Two = 2 }); GlobalDiagnosticsContext.Set(\"anyObject\", anyObjectReferenceOrString); Add the following to your logger configuration to reference the above properties: ${gdc:item=myDatabase} ${gdc:item=informationGroup} ${gdc:item=anyObject}","title":"Simple Properties"},{"location":"Gdc-layout-renderer/#dynamic-properties","text":"The Global Diagnostics Context (GDC) can also store complex objects, and can be used as an alternative to registering own custom layout renderer . NLog sees the GDC like global variables that doesn't depend on thread execution context, so make sure any complex object logic doesn't depend on application logging thread-state. public class ApplicationStateProperty : IFormattable { public static readonly ApplicationStateProperty Default = new ApplicationStateProperty(); private ApplicationStateProperty() { } public override string ToString() { // Physical memory used by application process (in megabytes) return ((long)(System.Environment.WorkingSet / (1024 * 1024))).ToString(); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } } During initialization, add the following code: GlobalDiagnosticsContext.Set(\"AppMemorySize\", ApplicationStateProperty.Default); To reference the AppMemorySize Global Diagnostics Context property. ${gdc:item=AppMemorySize}","title":"Dynamic Properties"},{"location":"Gdc-layout-renderer/#notes","text":"When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.","title":"Notes"},{"location":"GelfLayout/","text":"A specialized layout that renders to Graylog Extended Log Format (GELF) which produces JSON output. Platforms Supported: All - Requires nuget-package NLog.Targets.Network Layout Options GelfHostName - Graylog Message Host-field. Default = ${hostname} GelfShortMessage - Graylog Message Short-Message-field (Truncates when longer than 250 chars). Default = ${message} GelfFullMessage - Graylog Message Full-Message-field. Default = ${message} GelfFacility - Legacy Graylog Message Facility-field. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. IncludeProperties - Comma separated string with names which properties to explicitly include. GelfField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout)","title":"GelfLayout"},{"location":"GelfLayout/#layout-options","text":"GelfHostName - Graylog Message Host-field. Default = ${hostname} GelfShortMessage - Graylog Message Short-Message-field (Truncates when longer than 250 chars). Default = ${message} GelfFullMessage - Graylog Message Full-Message-field. Default = ${message} GelfFacility - Legacy Graylog Message Facility-field. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. IncludeProperties - Comma separated string with names which properties to explicitly include. GelfField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout)","title":"Layout Options"},{"location":"Getting-started-with-.NET-Core-2---Console-application/","text":"\u2139\ufe0f For updated tutorial see Getting started with .NET Core \u2139\ufe0f For ASP.NET Core use Getting started with ASP.NET Core Description Explains how to setup NLog as logging provider for .NET Core and Microsoft Extension Logging (MEL). Notice that NLog can be used on .NET Core without help from Microsoft Extension Logging and NLog.Extension.Hosting. See standard NLog Tutorial . 0. Create a new .NET Core console project In Visual Studio 2017, using .NET 4.6.1+ or .NET Core 2 1. Add dependency in csproj manually or using NuGet Install: The package NLog.Extensions.Logging Update the NLog package if possible e.g. 2. Create a nlog.config file. Create nlog.config (lowercase all) file in the root of your application project (File Properties: Copy Always) We use this example: For an introduction to the NLog.config -file then see the NLog Tutorial , and for more detailed information then see here . Ensure to configure your project-file to copy NLog.config to the output directory: 3. Update your program 3.1 Create your runner class public class Runner { private readonly ILogger _logger; public Runner(ILogger logger) { _logger = logger; } public void DoAction(string name) { _logger.LogDebug(20, \"Doing hard work! {Action}\", name); } } 3.2 Setup Microsoft Logging with Dependency Injection using Microsoft.Extensions.Logging; using NLog; using NLog.Extensions.Logging; static void Main(string[] args) { // Disposing the ServiceProvider will also flush / dispose / shutdown the NLog Logging Provider using var servicesProvider = new ServiceCollection() .AddTransient() // Runner is the custom class .AddLogging(loggingBuilder => { // Setup NLog for logging loggingBuilder.ClearProviders(); loggingBuilder.AddNLog(); }).BuildServiceProvider(); var runner = servicesProvider.GetRequiredService(); runner.DoAction(\"Action1\"); Console.WriteLine(\"Press ANY key to exit\"); Console.ReadKey(); } 4 Example output On screen: In file: 2017/10/16 23:08:46.479|DEBUG|Doing hard work! Action1 |ConsoleExample.Runner|Action=Action1, EventId_Id=20, EventId_Name=, EventId=20 \u2139\ufe0f See also example in GitHub","title":"Getting started with .NET Core 2 Console application"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#description","text":"Explains how to setup NLog as logging provider for .NET Core and Microsoft Extension Logging (MEL). Notice that NLog can be used on .NET Core without help from Microsoft Extension Logging and NLog.Extension.Hosting. See standard NLog Tutorial .","title":"Description"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#0-create-a-new-net-core-console-project","text":"In Visual Studio 2017, using .NET 4.6.1+ or .NET Core 2","title":"0. Create a new .NET Core console project"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#1-add-dependency-in-csproj-manually-or-using-nuget","text":"Install: The package NLog.Extensions.Logging Update the NLog package if possible e.g. ","title":"1. Add dependency in csproj manually or using NuGet"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#2-create-a-nlogconfig-file","text":"Create nlog.config (lowercase all) file in the root of your application project (File Properties: Copy Always) We use this example: For an introduction to the NLog.config -file then see the NLog Tutorial , and for more detailed information then see here . Ensure to configure your project-file to copy NLog.config to the output directory: ","title":"2. Create a nlog.config file."},{"location":"Getting-started-with-.NET-Core-2---Console-application/#3-update-your-program","text":"","title":"3. Update your program"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#31-create-your-runner-class","text":"public class Runner { private readonly ILogger _logger; public Runner(ILogger logger) { _logger = logger; } public void DoAction(string name) { _logger.LogDebug(20, \"Doing hard work! {Action}\", name); } }","title":"3.1 Create your runner class"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#32-setup-microsoft-logging-with-dependency-injection","text":"using Microsoft.Extensions.Logging; using NLog; using NLog.Extensions.Logging; static void Main(string[] args) { // Disposing the ServiceProvider will also flush / dispose / shutdown the NLog Logging Provider using var servicesProvider = new ServiceCollection() .AddTransient() // Runner is the custom class .AddLogging(loggingBuilder => { // Setup NLog for logging loggingBuilder.ClearProviders(); loggingBuilder.AddNLog(); }).BuildServiceProvider(); var runner = servicesProvider.GetRequiredService(); runner.DoAction(\"Action1\"); Console.WriteLine(\"Press ANY key to exit\"); Console.ReadKey(); }","title":"3.2 Setup Microsoft Logging with Dependency Injection"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#4-example-output","text":"On screen: In file: 2017/10/16 23:08:46.479|DEBUG|Doing hard work! Action1 |ConsoleExample.Runner|Action=Action1, EventId_Id=20, EventId_Name=, EventId=20","title":"4 Example output"},{"location":"Getting-started-with-.NET-Core-2---Console-application/#i-see-also-example-in-github","text":"","title":"\u2139\ufe0f See also example in GitHub"},{"location":"Getting-started-with-.NET-Core-Console-application/","text":"NLog integrates with the built-in Microsoft.Extensions.Logging (MEL) infrastructure. Application code continues to use ILogger , while NLog handles log routing, formatting, and writing to configured targets. This guide shows how to configure NLog as a logging provider for a .NET console application. 1. Install NLog Install the NLog.Extensions.Logging NuGet package: dotnet add package NLog.Extensions.Logging 2. Register NLog Logging Provider Create a LoggerFactory and include AddNLog() : using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using var loggerFactory = LoggerFactory.Create(builder => { // Remove default Microsoft logging providers builder.ClearProviders(); // Register NLog builder.AddNLog(); }); var logger = loggerFactory.CreateLogger(); logger.LogInformation(\"Application started.\"); AddNLog() registers NLog as the logging provider for the Microsoft.Extensions.Logging LoggerFactory. From this point log messages will be processed by NLog. 3. Configure NLog NLog supports several configuration approaches: NLog.config - Classic NLog configuration style. appsettings.json - AddNLog() automatically loads the \"NLog\" section if present, with environment overrides. Fluent Configuration API - Configure NLog directly using C#. This guide uses an NLog.config XML file as the configuration example, but the alternatives above also work. Create a file named NLog.config in the application project root directory and add the following content: ${longdate}|${level}|${message}|${all-event-properties} ${exception:format=tostring} This configuration includes: Targets \u2014 Define output destinations for writing log messages. See NLog Targets Rules \u2014 Define how log messages are routed from loggers to output targets. Layout \u2014 Define how log messages are formatted. See NLog Layouts Layout Renderers - Provide additional details to include in log output. See NLog Layout Renderers The Console-target ensures that .NET Core hosting lifetime startup messages are available on the console. The file-target uses a simple layout, but the layout can be changed to JSON to capture structured logging properties and trace context ( TraceId and SpanId ) to correlate logs with traces in distributed systems. Ensure that the NLog.config file is copied to the output directory when building or publishing the application. In Visual Studio, set the Copy to Output Directory property to Copy if newer . 4. Start logging NLog is now configured in the application. Start the application, and existing ILogger calls will be processed by NLog and written to the configured targets. You are not required to use the ILogger , if you prefer using NLog.LogManager.GetCurrentClassLogger() in the console application. If NLog is not working as expected, see the NLog Logging troubleshooting guide to identify configuration issues. Using the .NET Generic Host If the console application uses the .NET Generic Host, NLog can be registered directly with the host using UseNLog() . See the NLog.Extensions.Hosting NuGet package for information about integrating NLog with the .NET Generic Host.","title":"Getting started with .NET Core Console application"},{"location":"Getting-started-with-.NET-Core-Console-application/#1-install-nlog","text":"Install the NLog.Extensions.Logging NuGet package: dotnet add package NLog.Extensions.Logging","title":"1. Install NLog"},{"location":"Getting-started-with-.NET-Core-Console-application/#2-register-nlog-logging-provider","text":"Create a LoggerFactory and include AddNLog() : using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using var loggerFactory = LoggerFactory.Create(builder => { // Remove default Microsoft logging providers builder.ClearProviders(); // Register NLog builder.AddNLog(); }); var logger = loggerFactory.CreateLogger(); logger.LogInformation(\"Application started.\"); AddNLog() registers NLog as the logging provider for the Microsoft.Extensions.Logging LoggerFactory. From this point log messages will be processed by NLog.","title":"2. Register NLog Logging Provider"},{"location":"Getting-started-with-.NET-Core-Console-application/#3-configure-nlog","text":"NLog supports several configuration approaches: NLog.config - Classic NLog configuration style. appsettings.json - AddNLog() automatically loads the \"NLog\" section if present, with environment overrides. Fluent Configuration API - Configure NLog directly using C#. This guide uses an NLog.config XML file as the configuration example, but the alternatives above also work. Create a file named NLog.config in the application project root directory and add the following content: ${longdate}|${level}|${message}|${all-event-properties} ${exception:format=tostring} This configuration includes: Targets \u2014 Define output destinations for writing log messages. See NLog Targets Rules \u2014 Define how log messages are routed from loggers to output targets. Layout \u2014 Define how log messages are formatted. See NLog Layouts Layout Renderers - Provide additional details to include in log output. See NLog Layout Renderers The Console-target ensures that .NET Core hosting lifetime startup messages are available on the console. The file-target uses a simple layout, but the layout can be changed to JSON to capture structured logging properties and trace context ( TraceId and SpanId ) to correlate logs with traces in distributed systems. Ensure that the NLog.config file is copied to the output directory when building or publishing the application. In Visual Studio, set the Copy to Output Directory property to Copy if newer .","title":"3. Configure NLog"},{"location":"Getting-started-with-.NET-Core-Console-application/#4-start-logging","text":"NLog is now configured in the application. Start the application, and existing ILogger calls will be processed by NLog and written to the configured targets. You are not required to use the ILogger , if you prefer using NLog.LogManager.GetCurrentClassLogger() in the console application. If NLog is not working as expected, see the NLog Logging troubleshooting guide to identify configuration issues.","title":"4. Start logging"},{"location":"Getting-started-with-.NET-Core-Console-application/#using-the-net-generic-host","text":"If the console application uses the .NET Generic Host, NLog can be registered directly with the host using UseNLog() . See the NLog.Extensions.Hosting NuGet package for information about integrating NLog with the .NET Generic Host.","title":"Using the .NET Generic Host"},{"location":"Getting-started-with-ASP.NET-Core-2/","text":"\u26a0\ufe0f Missing the trace/debug logs in .NET Core 2? Check your appsettings.json \u2139\ufe0f See also example in GitHub This tutorial is for ASP.NET Core 2. For ASP.NET Core 6, check Getting started with ASP.NET Core 6 For ASP.NET Core 5, check Getting started with ASP.NET Core 5 For ASP.NET Core 3, check Getting started with ASP.NET Core 3 For ASP.NET Core 1? Go here! Note: .NET 4.6+ or .NET standard 2 are required 0. Create a new ASP.NET Core project In Visual Studio 2017. 1. Add dependency in csproj manually or using NuGet Install the latest: - NLog.Web.AspNetCore 4.8+ - Update the NLog package if possible in csproj: 2. Create a nlog.config file. Create nlog.config (lowercase all) file in the root of your project. We use this example: autoReload=\"true\" internalLogLevel=\"Info\" internalLogFile=\"c:\\temp\\internal-nlog.txt\"> More details of the config file are here . If you like to include other targets or layout renderers, check the Platform support table, as there is a limited set implemented. Check the column NetStandard . To read more about NetStandard, see the docs from Microsoft 3. Enable copy to bin folder Enable copy to bin folder for nlog.config or edit .csproj file manually and add: 4. Update program.cs Update the program.cs using NLog.Web; using Microsoft.Extensions.Logging; public static void Main(string[] args) { // NLog: setup the logger first to catch all errors var logger = NLog.LogManager.Setup().RegisterNLogWeb().GetCurrentClassLogger(); try { logger.Debug(\"init main\"); CreateWebHostBuilder(args).Build().Run(); } catch (Exception ex) { //NLog: catch setup errors logger.Error(ex, \"Stopped program because of exception\"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog(); // NLog: Register as Logging Provider 5. Configure appsettings.json The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel . So either remove \"Default\": or adjust it correctly to your needs. { \"Logging\": { \"LogLevel\": { \"Default\": \"Trace\", \"Microsoft\": \"Information\" } } } Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json 6. Write logs Inject the ILogger in your controller: using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation(\"Index page says hello\"); return View(); } 7. Example Output When starting the ASP.NET Core website, we get two files: nlog-own-2017-10-10.log 2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main |url: |action: 2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index! |url: http://localhost/|action: Index nlog-all-2017-10-10.log 2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main 2017-10-10 23:40:30.9739|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\\Users\\j.verdurmen\\AppData\\Local\\ASP.NET\\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 2017-10-10 23:40:30.9897|37|DEBUG|Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository|Reading data from file 'C:\\Users\\j.verdurmen\\AppData\\Local\\ASP.NET\\DataProtection-Keys\\key-bfd1ce07-8dc6-4eef-a51a-d21ddb547109.xml'. 2017-10-10 23:40:31.0004|18|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Found key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109}. 2017-10-10 23:40:31.0124|13|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver|Considering key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} with expiration date 2017-12-28 19:01:07Z as default key. 2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60 2017-10-10 23:40:31.0422|51|DEBUG|Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor|Decrypting secret element using Windows DPAPI. 2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60 2017-10-10 23:40:31.0422|4|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'AES' from provider '(null)' with chaining mode CBC. 2017-10-10 23:40:31.0543|3|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'SHA256' from provider '(null)' with HMAC. 2017-10-10 23:40:31.0543|2|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider|Using key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} as the default key. 2017-10-10 23:40:31.0543|0|DEBUG|Microsoft.AspNetCore.DataProtection.Internal.DataProtectionStartupFilter|Key ring with default key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} was loaded during application startup. 2017-10-10 23:40:31.4080|3|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting starting 2017-10-10 23:40:31.5508|4|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting started 2017-10-10 23:40:31.5508|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly ASP.NET Core 2 - VS2017 2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.ApplicationInsights.HostingStartup 2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.Server.IISIntegration 2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" started. 2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK65\" started. 2017-10-10 23:40:31.7418|19|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK65\" reset. 2017-10-10 23:40:31.7418|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK65\" disconnecting. 2017-10-10 23:40:31.7418|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK65\" sending FIN. 2017-10-10 23:40:31.7591|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK65\" stopped. 2017-10-10 23:40:31.8153|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/ 2017-10-10 23:40:31.8607|4|DEBUG|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|The request path / does not match a supported file type 2017-10-10 23:40:32.0160|1|DEBUG|Microsoft.AspNetCore.Routing.RouteBase|Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'. 2017-10-10 23:40:32.1120|1|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) 2017-10-10 23:40:32.1326|1|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) with arguments ((null)) - ModelState is Valid 2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index! 2017-10-10 23:40:32.1620|2|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017), returned result Microsoft.AspNetCore.Mvc.ViewResult. 2017-10-10 23:40:32.1620|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine|View lookup cache miss for view 'Index' in controller 'Home'. 2017-10-10 23:40:33.6906|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Home\\Index.cshtml' started. 2017-10-10 23:40:35.7180|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Home\\Index.cshtml' completed in 2024.1338ms. 2017-10-10 23:40:35.7988|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\_ViewStart.cshtml' started. 2017-10-10 23:40:35.8637|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\_ViewStart.cshtml' completed in 63.9912ms. 2017-10-10 23:40:35.8710|2|DEBUG|Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor|The view 'Index' was found. 2017-10-10 23:40:35.8710|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor|Executing ViewResult, running view at path /Views/Home/Index.cshtml. 2017-10-10 23:40:35.9577|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine|View lookup cache miss for view '_Layout' in controller 'Home'. 2017-10-10 23:40:36.0454|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Shared\\_Layout.cshtml' started. 2017-10-10 23:40:36.2080|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Shared\\_Layout.cshtml' completed in 161.8031ms. 2017-10-10 23:40:36.2209|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' initialized. 2017-10-10 23:40:36.2209|3|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' processed. 2017-10-10 23:40:36.2367|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' initialized. 2017-10-10 23:40:36.2367|3|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' processed. 2017-10-10 23:40:36.2942|2|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) in 4181.1451ms 2017-10-10 23:40:36.3036|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" completed keep alive response. 2017-10-10 23:40:36.3273|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 4515.4954ms 200 text/html; charset=utf-8 2017-10-10 23:40:36.3273|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" started. 2017-10-10 23:40:36.3273|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" started. 2017-10-10 23:40:36.3386|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/css/bootstrap.css 2017-10-10 23:40:36.3386|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/css/site.css 2017-10-10 23:40:36.3610|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\css\\site.css' 2017-10-10 23:40:36.3610|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.css'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\bootstrap\\dist\\css\\bootstrap.css' 2017-10-10 23:40:36.4312|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" completed keep alive response. 2017-10-10 23:40:36.4312|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 90.8043ms 200 text/css 2017-10-10 23:40:36.4312|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" completed keep alive response. 2017-10-10 23:40:36.4312|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 98.4683ms 200 text/css 2017-10-10 23:40:36.4710|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" started. 2017-10-10 23:40:36.4710|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" started. 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/jquery/dist/jquery.js 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/js/bootstrap.js 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner2.svg 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/js/site.js?v=ji3-IxbEzYWjzzLCGkF1KDjrT2jLbbrSYXw-AhMPNIA 2017-10-10 23:40:36.4819|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" started. 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\js\\site.js' 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.js'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\jquery\\dist\\jquery.js' 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner2.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner2.svg' 2017-10-10 23:40:36.4933|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" completed keep alive response. 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.js'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\bootstrap\\dist\\js\\bootstrap.js' 2017-10-10 23:40:36.4933|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 20.2541ms 200 application/javascript 2017-10-10 23:40:36.5143|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" completed keep alive response. 2017-10-10 23:40:36.5143|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 32.361ms 200 image/svg+xml 2017-10-10 23:40:36.5143|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2 2017-10-10 23:40:36.5401|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\bootstrap\\dist\\fonts\\glyphicons-halflings-regular.woff2' 2017-10-10 23:40:36.5401|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner1.svg 2017-10-10 23:40:36.5401|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner1.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner1.svg' 2017-10-10 23:40:36.5539|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" completed keep alive response. 2017-10-10 23:40:36.5539|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 39.9074ms 200 font/woff2 2017-10-10 23:40:36.5745|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner3.svg 2017-10-10 23:40:36.5745|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner4.svg 2017-10-10 23:40:36.5951|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" completed keep alive response. 2017-10-10 23:40:36.6015|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 119.5389ms 200 application/javascript 2017-10-10 23:40:36.6015|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner4.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner4.svg' 2017-10-10 23:40:36.5745|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner3.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner3.svg' 2017-10-10 23:40:36.6946|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" completed keep alive response. 2017-10-10 23:40:36.6703|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" completed keep alive response. 2017-10-10 23:40:36.6946|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 119.7561ms 200 image/svg+xml 2017-10-10 23:40:36.6015|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" completed keep alive response. 2017-10-10 23:40:36.7137|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 170.2078ms 200 image/svg+xml 2017-10-10 23:40:36.7137|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" completed keep alive response. 2017-10-10 23:40:36.7560|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 181.4017ms 200 image/svg+xml 2017-10-10 23:40:36.6946|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 216.2838ms 200 application/javascript 2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK68\" received FIN. 2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK67\" received FIN. 2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" disconnecting. 2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK69\" received FIN. 2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" disconnecting. 2017-10-10 23:42:21.6657|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK67\" sending FIN. 2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" disconnecting. 2017-10-10 23:42:21.6657|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" stopped. 2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK66\" received FIN. 2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" disconnecting. 2017-10-10 23:42:21.6657|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK69\" sending FIN. 2017-10-10 23:42:21.6657|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" stopped. 2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK6A\" received FIN. 2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" disconnecting. 2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK64\" received FIN. 2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" disconnecting. 2017-10-10 23:42:21.6800|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK68\" sending FIN. 2017-10-10 23:42:21.6800|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" stopped. 2017-10-10 23:42:21.6800|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK66\" sending FIN. 2017-10-10 23:42:21.6800|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" stopped. 2017-10-10 23:42:21.6943|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" stopped. 2017-10-10 23:42:21.6943|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK6A\" sending FIN. 2017-10-10 23:42:21.6943|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK64\" sending FIN. 2017-10-10 23:42:21.6943|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" stopped. Configure NLog Targets for output Next step, see Configure NLog with nlog.config","title":"Getting started with ASP.NET Core 2"},{"location":"Getting-started-with-ASP.NET-Core-2/#0-create-a-new-aspnet-core-project","text":"In Visual Studio 2017.","title":"0. Create a new ASP.NET Core project"},{"location":"Getting-started-with-ASP.NET-Core-2/#1-add-dependency-in-csproj-manually-or-using-nuget","text":"Install the latest: - NLog.Web.AspNetCore 4.8+ - Update the NLog package if possible in csproj: ","title":"1. Add dependency in csproj manually or using NuGet"},{"location":"Getting-started-with-ASP.NET-Core-2/#2-create-a-nlogconfig-file","text":"Create nlog.config (lowercase all) file in the root of your project. We use this example: autoReload=\"true\" internalLogLevel=\"Info\" internalLogFile=\"c:\\temp\\internal-nlog.txt\"> More details of the config file are here . If you like to include other targets or layout renderers, check the Platform support table, as there is a limited set implemented. Check the column NetStandard . To read more about NetStandard, see the docs from Microsoft","title":"2. Create a nlog.config file."},{"location":"Getting-started-with-ASP.NET-Core-2/#3-enable-copy-to-bin-folder","text":"Enable copy to bin folder for nlog.config or edit .csproj file manually and add: ","title":"3. Enable copy to bin folder"},{"location":"Getting-started-with-ASP.NET-Core-2/#4-update-programcs","text":"Update the program.cs using NLog.Web; using Microsoft.Extensions.Logging; public static void Main(string[] args) { // NLog: setup the logger first to catch all errors var logger = NLog.LogManager.Setup().RegisterNLogWeb().GetCurrentClassLogger(); try { logger.Debug(\"init main\"); CreateWebHostBuilder(args).Build().Run(); } catch (Exception ex) { //NLog: catch setup errors logger.Error(ex, \"Stopped program because of exception\"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog(); // NLog: Register as Logging Provider","title":"4. Update program.cs"},{"location":"Getting-started-with-ASP.NET-Core-2/#5-configure-appsettingsjson","text":"The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel . So either remove \"Default\": or adjust it correctly to your needs. { \"Logging\": { \"LogLevel\": { \"Default\": \"Trace\", \"Microsoft\": \"Information\" } } } Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json","title":"5. Configure appsettings.json"},{"location":"Getting-started-with-ASP.NET-Core-2/#6-write-logs","text":"Inject the ILogger in your controller: using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation(\"Index page says hello\"); return View(); }","title":"6. Write logs"},{"location":"Getting-started-with-ASP.NET-Core-2/#7-example-output","text":"When starting the ASP.NET Core website, we get two files:","title":"7. Example Output"},{"location":"Getting-started-with-ASP.NET-Core-2/#nlog-own-2017-10-10log","text":"2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main |url: |action: 2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index! |url: http://localhost/|action: Index","title":"nlog-own-2017-10-10.log"},{"location":"Getting-started-with-ASP.NET-Core-2/#nlog-all-2017-10-10log","text":"2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main 2017-10-10 23:40:30.9739|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\\Users\\j.verdurmen\\AppData\\Local\\ASP.NET\\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 2017-10-10 23:40:30.9897|37|DEBUG|Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository|Reading data from file 'C:\\Users\\j.verdurmen\\AppData\\Local\\ASP.NET\\DataProtection-Keys\\key-bfd1ce07-8dc6-4eef-a51a-d21ddb547109.xml'. 2017-10-10 23:40:31.0004|18|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Found key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109}. 2017-10-10 23:40:31.0124|13|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver|Considering key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} with expiration date 2017-12-28 19:01:07Z as default key. 2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60 2017-10-10 23:40:31.0422|51|DEBUG|Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor|Decrypting secret element using Windows DPAPI. 2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60 2017-10-10 23:40:31.0422|4|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'AES' from provider '(null)' with chaining mode CBC. 2017-10-10 23:40:31.0543|3|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'SHA256' from provider '(null)' with HMAC. 2017-10-10 23:40:31.0543|2|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider|Using key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} as the default key. 2017-10-10 23:40:31.0543|0|DEBUG|Microsoft.AspNetCore.DataProtection.Internal.DataProtectionStartupFilter|Key ring with default key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} was loaded during application startup. 2017-10-10 23:40:31.4080|3|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting starting 2017-10-10 23:40:31.5508|4|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting started 2017-10-10 23:40:31.5508|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly ASP.NET Core 2 - VS2017 2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.ApplicationInsights.HostingStartup 2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.Server.IISIntegration 2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" started. 2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK65\" started. 2017-10-10 23:40:31.7418|19|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK65\" reset. 2017-10-10 23:40:31.7418|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK65\" disconnecting. 2017-10-10 23:40:31.7418|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK65\" sending FIN. 2017-10-10 23:40:31.7591|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK65\" stopped. 2017-10-10 23:40:31.8153|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/ 2017-10-10 23:40:31.8607|4|DEBUG|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|The request path / does not match a supported file type 2017-10-10 23:40:32.0160|1|DEBUG|Microsoft.AspNetCore.Routing.RouteBase|Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'. 2017-10-10 23:40:32.1120|1|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) 2017-10-10 23:40:32.1326|1|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) with arguments ((null)) - ModelState is Valid 2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index! 2017-10-10 23:40:32.1620|2|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017), returned result Microsoft.AspNetCore.Mvc.ViewResult. 2017-10-10 23:40:32.1620|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine|View lookup cache miss for view 'Index' in controller 'Home'. 2017-10-10 23:40:33.6906|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Home\\Index.cshtml' started. 2017-10-10 23:40:35.7180|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Home\\Index.cshtml' completed in 2024.1338ms. 2017-10-10 23:40:35.7988|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\_ViewStart.cshtml' started. 2017-10-10 23:40:35.8637|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\_ViewStart.cshtml' completed in 63.9912ms. 2017-10-10 23:40:35.8710|2|DEBUG|Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor|The view 'Index' was found. 2017-10-10 23:40:35.8710|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor|Executing ViewResult, running view at path /Views/Home/Index.cshtml. 2017-10-10 23:40:35.9577|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine|View lookup cache miss for view '_Layout' in controller 'Home'. 2017-10-10 23:40:36.0454|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Shared\\_Layout.cshtml' started. 2017-10-10 23:40:36.2080|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\Views\\Shared\\_Layout.cshtml' completed in 161.8031ms. 2017-10-10 23:40:36.2209|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' initialized. 2017-10-10 23:40:36.2209|3|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' processed. 2017-10-10 23:40:36.2367|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' initialized. 2017-10-10 23:40:36.2367|3|DEBUG|Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper|Tag helper component 'Microsoft.AspNetCore.ApplicationInsights.HostingStartup.JavaScriptSnippetTagHelperComponent' processed. 2017-10-10 23:40:36.2942|2|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) in 4181.1451ms 2017-10-10 23:40:36.3036|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" completed keep alive response. 2017-10-10 23:40:36.3273|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 4515.4954ms 200 text/html; charset=utf-8 2017-10-10 23:40:36.3273|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" started. 2017-10-10 23:40:36.3273|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" started. 2017-10-10 23:40:36.3386|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/css/bootstrap.css 2017-10-10 23:40:36.3386|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/css/site.css 2017-10-10 23:40:36.3610|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\css\\site.css' 2017-10-10 23:40:36.3610|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.css'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\bootstrap\\dist\\css\\bootstrap.css' 2017-10-10 23:40:36.4312|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" completed keep alive response. 2017-10-10 23:40:36.4312|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 90.8043ms 200 text/css 2017-10-10 23:40:36.4312|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" completed keep alive response. 2017-10-10 23:40:36.4312|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 98.4683ms 200 text/css 2017-10-10 23:40:36.4710|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" started. 2017-10-10 23:40:36.4710|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" started. 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/jquery/dist/jquery.js 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/js/bootstrap.js 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner2.svg 2017-10-10 23:40:36.4819|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/js/site.js?v=ji3-IxbEzYWjzzLCGkF1KDjrT2jLbbrSYXw-AhMPNIA 2017-10-10 23:40:36.4819|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" started. 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\js\\site.js' 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.js'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\jquery\\dist\\jquery.js' 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner2.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner2.svg' 2017-10-10 23:40:36.4933|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" completed keep alive response. 2017-10-10 23:40:36.4819|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.js'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\bootstrap\\dist\\js\\bootstrap.js' 2017-10-10 23:40:36.4933|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 20.2541ms 200 application/javascript 2017-10-10 23:40:36.5143|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" completed keep alive response. 2017-10-10 23:40:36.5143|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 32.361ms 200 image/svg+xml 2017-10-10 23:40:36.5143|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2 2017-10-10 23:40:36.5401|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\lib\\bootstrap\\dist\\fonts\\glyphicons-halflings-regular.woff2' 2017-10-10 23:40:36.5401|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner1.svg 2017-10-10 23:40:36.5401|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner1.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner1.svg' 2017-10-10 23:40:36.5539|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" completed keep alive response. 2017-10-10 23:40:36.5539|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 39.9074ms 200 font/woff2 2017-10-10 23:40:36.5745|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner3.svg 2017-10-10 23:40:36.5745|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/images/banner4.svg 2017-10-10 23:40:36.5951|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" completed keep alive response. 2017-10-10 23:40:36.6015|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 119.5389ms 200 application/javascript 2017-10-10 23:40:36.6015|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner4.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner4.svg' 2017-10-10 23:40:36.5745|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/images/banner3.svg'. Physical path: 'X:\\nlog\\NLog.Web\\examples\\ASP.NET Core 2\\Visual Studio 2017\\ASP.NET Core 2 - VS2017\\wwwroot\\images\\banner3.svg' 2017-10-10 23:40:36.6946|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" completed keep alive response. 2017-10-10 23:40:36.6703|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" completed keep alive response. 2017-10-10 23:40:36.6946|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 119.7561ms 200 image/svg+xml 2017-10-10 23:40:36.6015|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" completed keep alive response. 2017-10-10 23:40:36.7137|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 170.2078ms 200 image/svg+xml 2017-10-10 23:40:36.7137|9|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" completed keep alive response. 2017-10-10 23:40:36.7560|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 181.4017ms 200 image/svg+xml 2017-10-10 23:40:36.6946|2|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 216.2838ms 200 application/javascript 2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK68\" received FIN. 2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK67\" received FIN. 2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" disconnecting. 2017-10-10 23:42:21.6657|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK69\" received FIN. 2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" disconnecting. 2017-10-10 23:42:21.6657|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK67\" sending FIN. 2017-10-10 23:42:21.6657|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" disconnecting. 2017-10-10 23:42:21.6657|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK69\" stopped. 2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK66\" received FIN. 2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" disconnecting. 2017-10-10 23:42:21.6657|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK69\" sending FIN. 2017-10-10 23:42:21.6657|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK67\" stopped. 2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK6A\" received FIN. 2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" disconnecting. 2017-10-10 23:42:21.6800|6|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK64\" received FIN. 2017-10-10 23:42:21.6800|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" disconnecting. 2017-10-10 23:42:21.6800|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK68\" sending FIN. 2017-10-10 23:42:21.6800|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK68\" stopped. 2017-10-10 23:42:21.6800|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK66\" sending FIN. 2017-10-10 23:42:21.6800|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK66\" stopped. 2017-10-10 23:42:21.6943|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK6A\" stopped. 2017-10-10 23:42:21.6943|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK6A\" sending FIN. 2017-10-10 23:42:21.6943|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id \"0HL8G4U42CK64\" sending FIN. 2017-10-10 23:42:21.6943|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id \"0HL8G4U42CK64\" stopped.","title":"nlog-all-2017-10-10.log"},{"location":"Getting-started-with-ASP.NET-Core-2/#configure-nlog-targets-for-output","text":"Next step, see Configure NLog with nlog.config","title":"Configure NLog Targets for output"},{"location":"Getting-started-with-ASP.NET-Core-3/","text":"\u26a0\ufe0f Missing the trace/debug logs? Check your appsettings.json \u2139\ufe0f See also example in GitHub This tutorial is for ASP.NET Core 3.1 For ASP.NET Core 6, check Getting started with ASP.NET Core 6 0. Create a new ASP.NET Core project In Visual Studio 2019. 1. Add dependency in csproj manually or using NuGet Install the latest: - NLog.Web.AspNetCore 4.9+ - Update the NLog package if possible in csproj: 2. Create a nlog.config file. Create nlog.config (lowercase all) file in the root of your project. We use this example: autoReload=\"true\" throwConfigExceptions=\"true\" internalLogLevel=\"info\" internalLogFile=\"c:\\temp\\internal-nlog-AspNetCore3.txt\"> More details of the config file are here . Notice that one might have to pay special attention to the Hosting Lifetime Startup Messages , if removing all other LoggingProviders (Like Console) and only using NLog. As it can cause hosting environment (Visual Studio / Docker / Azure Container) to not see application as started. If you like to include other targets or layout renderers, check the Platform support table, as there is a limited set implemented. Check the column NetStandard . To read more about NetStandard, see the docs from Microsoft . Check .NET Standard 2 for ASP.NET Core 3. 3. Enable copy to bin folder Enable copy to bin folder for nlog.config or edit .csproj file manually and add: 4. Update program.cs Update the program.cs to include UseNLog() : using System; using NLog.Web; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Hosting; public static void Main(string[] args) { // Early init of NLog to allow startup and exception logging, before host is built var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); try { logger.Debug(\"init main\"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, \"Stopped program because of exception\"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog(); // NLog: Register as Logging Provider 5. Configure appsettings.json The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel . So either remove \"Default\": or adjust it correctly to your needs. { \"Logging\": { \"LogLevel\": { \"Default\": \"Trace\", \"Microsoft\": \"Warning\", \"Microsoft.Hosting.Lifetime\": \"Information\" } }, \"AllowedHosts\": \"*\" } Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json 6. Write logs Inject the ILogger in your controller: using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; _logger.LogDebug(1, \"NLog injected into HomeController\"); } public IActionResult Index() { _logger.LogInformation(\"Hello, this is the index!\"); return View(); } 7. Example Output When starting the ASP.NET Core website, we get two files: nlog-own-2019-10-14.log 2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main |url: |action: |ASP.NET_Core_3___VS2019.Program.Main 2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController..ctor 2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController.Index nlog-all-2019-10-14.log 2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main 2019-10-14 23:15:10.9142|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\\Users\\Julian\\AppData\\Local\\ASP.NET\\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Content root path: D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019 2019-10-14 23:15:11.3238|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/ 2019-10-14 23:15:11.3434|0|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executing endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 2019-10-14 23:15:11.3867|3|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Route matched with {action = \"Index\", controller = \"Home\"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller ASP.NET_Core_3___VS2019.Controllers.HomeController (ASP.NET Core 3 - VS2019). 2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController 2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! 2019-10-14 23:15:11.4161|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executing ViewResult, running view Index. 2019-10-14 23:15:11.5831|4|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executed ViewResult - view Index executed in 167.626ms. 2019-10-14 23:15:11.5831|2|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Executed action ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019) in 196.6052ms 2019-10-14 23:15:11.5831|1|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executed endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 2019-10-14 23:15:11.5910|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 267.9366ms 200 text/html; charset=utf-8 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/jquery/dist/jquery.min.js 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/css/site.css 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/css/bootstrap.min.css 2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/js/bootstrap.bundle.min.js 2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\js\\site.js' 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\css\\site.css' 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 28.7787ms 200 application/javascript 2019-10-14 23:15:11.6696|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 52.4825ms 200 text/css 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.bundle.min.js'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\lib\\bootstrap\\dist\\js\\bootstrap.bundle.min.js' 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.min.css'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\lib\\bootstrap\\dist\\css\\bootstrap.min.css' 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.min.js'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\lib\\jquery\\dist\\jquery.min.js' 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 50.937400000000004ms 200 application/javascript 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 70.65100000000001ms 200 text/css 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 71.51610000000001ms 200 application/javascript Configure NLog Targets for output Next step, see Configure NLog with nlog.config","title":"Getting started with ASP.NET Core 3"},{"location":"Getting-started-with-ASP.NET-Core-3/#0-create-a-new-aspnet-core-project","text":"In Visual Studio 2019.","title":"0. Create a new ASP.NET Core project"},{"location":"Getting-started-with-ASP.NET-Core-3/#1-add-dependency-in-csproj-manually-or-using-nuget","text":"Install the latest: - NLog.Web.AspNetCore 4.9+ - Update the NLog package if possible in csproj: ","title":"1. Add dependency in csproj manually or using NuGet"},{"location":"Getting-started-with-ASP.NET-Core-3/#2-create-a-nlogconfig-file","text":"Create nlog.config (lowercase all) file in the root of your project. We use this example: autoReload=\"true\" throwConfigExceptions=\"true\" internalLogLevel=\"info\" internalLogFile=\"c:\\temp\\internal-nlog-AspNetCore3.txt\"> More details of the config file are here . Notice that one might have to pay special attention to the Hosting Lifetime Startup Messages , if removing all other LoggingProviders (Like Console) and only using NLog. As it can cause hosting environment (Visual Studio / Docker / Azure Container) to not see application as started. If you like to include other targets or layout renderers, check the Platform support table, as there is a limited set implemented. Check the column NetStandard . To read more about NetStandard, see the docs from Microsoft . Check .NET Standard 2 for ASP.NET Core 3.","title":"2. Create a nlog.config file."},{"location":"Getting-started-with-ASP.NET-Core-3/#3-enable-copy-to-bin-folder","text":"Enable copy to bin folder for nlog.config or edit .csproj file manually and add: ","title":"3. Enable copy to bin folder"},{"location":"Getting-started-with-ASP.NET-Core-3/#4-update-programcs","text":"Update the program.cs to include UseNLog() : using System; using NLog.Web; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Hosting; public static void Main(string[] args) { // Early init of NLog to allow startup and exception logging, before host is built var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); try { logger.Debug(\"init main\"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, \"Stopped program because of exception\"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog(); // NLog: Register as Logging Provider","title":"4. Update program.cs"},{"location":"Getting-started-with-ASP.NET-Core-3/#5-configure-appsettingsjson","text":"The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel . So either remove \"Default\": or adjust it correctly to your needs. { \"Logging\": { \"LogLevel\": { \"Default\": \"Trace\", \"Microsoft\": \"Warning\", \"Microsoft.Hosting.Lifetime\": \"Information\" } }, \"AllowedHosts\": \"*\" } Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json","title":"5. Configure appsettings.json"},{"location":"Getting-started-with-ASP.NET-Core-3/#6-write-logs","text":"Inject the ILogger in your controller: using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; _logger.LogDebug(1, \"NLog injected into HomeController\"); } public IActionResult Index() { _logger.LogInformation(\"Hello, this is the index!\"); return View(); }","title":"6. Write logs"},{"location":"Getting-started-with-ASP.NET-Core-3/#7-example-output","text":"When starting the ASP.NET Core website, we get two files:","title":"7. Example Output"},{"location":"Getting-started-with-ASP.NET-Core-3/#nlog-own-2019-10-14log","text":"2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main |url: |action: |ASP.NET_Core_3___VS2019.Program.Main 2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController..ctor 2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController.Index","title":"nlog-own-2019-10-14.log"},{"location":"Getting-started-with-ASP.NET-Core-3/#nlog-all-2019-10-14log","text":"2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main 2019-10-14 23:15:10.9142|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\\Users\\Julian\\AppData\\Local\\ASP.NET\\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Content root path: D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019 2019-10-14 23:15:11.3238|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/ 2019-10-14 23:15:11.3434|0|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executing endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 2019-10-14 23:15:11.3867|3|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Route matched with {action = \"Index\", controller = \"Home\"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller ASP.NET_Core_3___VS2019.Controllers.HomeController (ASP.NET Core 3 - VS2019). 2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController 2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! 2019-10-14 23:15:11.4161|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executing ViewResult, running view Index. 2019-10-14 23:15:11.5831|4|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executed ViewResult - view Index executed in 167.626ms. 2019-10-14 23:15:11.5831|2|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Executed action ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019) in 196.6052ms 2019-10-14 23:15:11.5831|1|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executed endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 2019-10-14 23:15:11.5910|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 267.9366ms 200 text/html; charset=utf-8 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/jquery/dist/jquery.min.js 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/css/site.css 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/css/bootstrap.min.css 2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/js/bootstrap.bundle.min.js 2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\js\\site.js' 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\css\\site.css' 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 28.7787ms 200 application/javascript 2019-10-14 23:15:11.6696|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 52.4825ms 200 text/css 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.bundle.min.js'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\lib\\bootstrap\\dist\\js\\bootstrap.bundle.min.js' 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.min.css'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\lib\\bootstrap\\dist\\css\\bootstrap.min.css' 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.min.js'. Physical path: 'D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 3\\ASP.NET Core 3 - VS2019\\wwwroot\\lib\\jquery\\dist\\jquery.min.js' 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 50.937400000000004ms 200 application/javascript 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 70.65100000000001ms 200 text/css 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 71.51610000000001ms 200 application/javascript","title":"nlog-all-2019-10-14.log"},{"location":"Getting-started-with-ASP.NET-Core-3/#configure-nlog-targets-for-output","text":"Next step, see Configure NLog with nlog.config","title":"Configure NLog Targets for output"},{"location":"Getting-started-with-ASP.NET-Core-5/","text":"\u26a0\ufe0f Missing the trace/debug logs? Check your appsettings.json \u2139\ufe0f See also example in GitHub This tutorial is for ASP.NET Core 5. For ASP.NET Core 6, check Getting started with ASP.NET Core 6 For ASP.NET Core 3.1, check Getting started with ASP.NET Core 3.1 0. Create a new ASP.NET Core project In Visual Studio 2019. Version 16.8+ is needed 1. Add dependency in csproj manually or using NuGet Install the latest: - NLog.Web.AspNetCore 4.9+ - Update the NLog package if possible in csproj: 2. Create a nlog.config file. Create nlog.config (lowercase all) file in the root of your project. We use this example: autoReload=\"true\" internalLogLevel=\"Info\" internalLogFile=\"c:\\temp\\internal-nlog-AspNetCore.txt\"> More details of the config file are here . Notice that one might have to pay special attention to the Hosting Lifetime Startup Messages , if removing all other LoggingProviders (Like Console) and only using NLog. As it can cause hosting environment (Visual Studio / Docker / Azure Container) to not see application as started. 3. Update program.cs Update the program.cs to include UseNLog() : using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using NLog.Web; namespace ASP.NET_Core_5_NLog_Example { public class Program { public static void Main(string[] args) { // Early init of NLog to allow startup and exception logging, before host is built var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); try { logger.Debug(\"init main\"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, \"Stopped program because of exception\"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); }) .UseNLog(); // NLog: Register as Logging Provider } } 4. Configure appsettings.json The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel . So either remove \"Default\": or adjust it correctly to your needs. { \"Logging\": { \"LogLevel\": { \"Default\": \"Trace\", \"Microsoft\": \"Warning\", \"Microsoft.Hosting.Lifetime\": \"Information\" } }, \"AllowedHosts\": \"*\" } Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json 5. Write logs Inject the ILogger in your controller: using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; _logger.LogDebug(1, \"NLog injected into HomeController\"); } public IActionResult Index() { _logger.LogInformation(\"Hello, this is the index!\"); return View(); } 6. Example Output When starting the ASP.NET Core website, we get two files: nlog-own-2020-12-29.log 2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main |url: |action: 2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index 2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index nlog-all-2020-12-29.log 2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Content root path: D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 5\\ASP.NET Core 5 NLog Example 2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController 2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index! Configure NLog Targets for output Next step, see Configure NLog with nlog.config","title":"Getting started with ASP.NET Core 5"},{"location":"Getting-started-with-ASP.NET-Core-5/#0-create-a-new-aspnet-core-project","text":"In Visual Studio 2019. Version 16.8+ is needed","title":"0. Create a new ASP.NET Core project"},{"location":"Getting-started-with-ASP.NET-Core-5/#1-add-dependency-in-csproj-manually-or-using-nuget","text":"Install the latest: - NLog.Web.AspNetCore 4.9+ - Update the NLog package if possible in csproj: ","title":"1. Add dependency in csproj manually or using NuGet"},{"location":"Getting-started-with-ASP.NET-Core-5/#2-create-a-nlogconfig-file","text":"Create nlog.config (lowercase all) file in the root of your project. We use this example: autoReload=\"true\" internalLogLevel=\"Info\" internalLogFile=\"c:\\temp\\internal-nlog-AspNetCore.txt\"> More details of the config file are here . Notice that one might have to pay special attention to the Hosting Lifetime Startup Messages , if removing all other LoggingProviders (Like Console) and only using NLog. As it can cause hosting environment (Visual Studio / Docker / Azure Container) to not see application as started.","title":"2. Create a nlog.config file."},{"location":"Getting-started-with-ASP.NET-Core-5/#3-update-programcs","text":"Update the program.cs to include UseNLog() : using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using NLog.Web; namespace ASP.NET_Core_5_NLog_Example { public class Program { public static void Main(string[] args) { // Early init of NLog to allow startup and exception logging, before host is built var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); try { logger.Debug(\"init main\"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, \"Stopped program because of exception\"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); }) .UseNLog(); // NLog: Register as Logging Provider } }","title":"3. Update program.cs"},{"location":"Getting-started-with-ASP.NET-Core-5/#4-configure-appsettingsjson","text":"The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel . So either remove \"Default\": or adjust it correctly to your needs. { \"Logging\": { \"LogLevel\": { \"Default\": \"Trace\", \"Microsoft\": \"Warning\", \"Microsoft.Hosting.Lifetime\": \"Information\" } }, \"AllowedHosts\": \"*\" } Remember to also update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json","title":"4. Configure appsettings.json"},{"location":"Getting-started-with-ASP.NET-Core-5/#5-write-logs","text":"Inject the ILogger in your controller: using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; _logger.LogDebug(1, \"NLog injected into HomeController\"); } public IActionResult Index() { _logger.LogInformation(\"Hello, this is the index!\"); return View(); }","title":"5. Write logs"},{"location":"Getting-started-with-ASP.NET-Core-5/#6-example-output","text":"When starting the ASP.NET Core website, we get two files:","title":"6. Example Output"},{"location":"Getting-started-with-ASP.NET-Core-5/#nlog-own-2020-12-29log","text":"2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main |url: |action: 2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index 2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index","title":"nlog-own-2020-12-29.log"},{"location":"Getting-started-with-ASP.NET-Core-5/#nlog-all-2020-12-29log","text":"2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Content root path: D:\\nlog\\NLog.Web\\examples\\ASP.NET Core 5\\ASP.NET Core 5 NLog Example 2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController 2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index!","title":"nlog-all-2020-12-29.log"},{"location":"Getting-started-with-ASP.NET-Core-5/#configure-nlog-targets-for-output","text":"Next step, see Configure NLog with nlog.config","title":"Configure NLog Targets for output"},{"location":"Getting-started-with-ASP.NET-Core-6/","text":"NLog integrates with the built-in ASP.NET Core logging infrastructure. Application code continues to use ILogger , while NLog handles log routing, formatting, and writing to configured targets. This guide shows how to configure NLog for a new or existing ASP.NET Core applications. 1. Install NLog Install the NLog ASP.NET Core NuGet package: dotnet add package NLog.Web.AspNetCore 2. Register NLog Logging Provider Update Program.cs to include UseNLog() : using NLog.Web; var builder = WebApplication.CreateBuilder(args); // Remove default Microsoft logging providers builder.Logging.ClearProviders(); // Register NLog builder.Host.UseNLog(); var app = builder.Build(); app.Run(); UseNLog() registers NLog as the logging provider for the ASP.NET Core host. From this point log messages will be processed by NLog. 3. Configure NLog NLog supports several configuration approaches: NLog.config - Classic NLog configuration style. appsettings.json - UseNLog() automatically loads the \"NLog\" section if present, with environment overrides. Fluent-Configuration-API - Configure NLog directly using C# at application startup. This guide uses an NLog.config XML file as the configuration example, but the alternatives above also work. Create a file named NLog.config in the application project root directory and add the following content: This configuration includes: Targets \u2014 Define output destinations for writing log messages. See NLog Targets Rules \u2014 Define how log messages are routed from loggers to output targets. Layout \u2014 Define how log messages are formatted. See NLog Layouts Layout Renderers - Provide additional details to include in log output. See NLog Layout Renderers The Console-target ensures that ASP.NET Core hosting lifetime startup messages are available on the console. The file-target writes newline-delimited JSON log events that capture structured logging properties and trace context ( TraceId and SpanId ) for correlating logs with traces in distributed systems. Ensure that the NLog.config file is copied to the output directory when building or publishing the application. In Visual Studio, set the Copy to Output Directory property to Copy if newer . 4. Start logging NLog is now configured in the application. Start the application, and existing ILogger calls will be processed by NLog and written to the configured targets. If NLog is not working as expected, see the NLog Logging troubleshooting guide to identify configuration issues. \u2139\ufe0f See also examples in GitHub","title":"Getting started with ASP.NET Core 6"},{"location":"Getting-started-with-ASP.NET-Core-6/#1-install-nlog","text":"Install the NLog ASP.NET Core NuGet package: dotnet add package NLog.Web.AspNetCore","title":"1. Install NLog"},{"location":"Getting-started-with-ASP.NET-Core-6/#2-register-nlog-logging-provider","text":"Update Program.cs to include UseNLog() : using NLog.Web; var builder = WebApplication.CreateBuilder(args); // Remove default Microsoft logging providers builder.Logging.ClearProviders(); // Register NLog builder.Host.UseNLog(); var app = builder.Build(); app.Run(); UseNLog() registers NLog as the logging provider for the ASP.NET Core host. From this point log messages will be processed by NLog.","title":"2. Register NLog Logging Provider"},{"location":"Getting-started-with-ASP.NET-Core-6/#3-configure-nlog","text":"NLog supports several configuration approaches: NLog.config - Classic NLog configuration style. appsettings.json - UseNLog() automatically loads the \"NLog\" section if present, with environment overrides. Fluent-Configuration-API - Configure NLog directly using C# at application startup. This guide uses an NLog.config XML file as the configuration example, but the alternatives above also work. Create a file named NLog.config in the application project root directory and add the following content: This configuration includes: Targets \u2014 Define output destinations for writing log messages. See NLog Targets Rules \u2014 Define how log messages are routed from loggers to output targets. Layout \u2014 Define how log messages are formatted. See NLog Layouts Layout Renderers - Provide additional details to include in log output. See NLog Layout Renderers The Console-target ensures that ASP.NET Core hosting lifetime startup messages are available on the console. The file-target writes newline-delimited JSON log events that capture structured logging properties and trace context ( TraceId and SpanId ) for correlating logs with traces in distributed systems. Ensure that the NLog.config file is copied to the output directory when building or publishing the application. In Visual Studio, set the Copy to Output Directory property to Copy if newer .","title":"3. Configure NLog"},{"location":"Getting-started-with-ASP.NET-Core-6/#4-start-logging","text":"NLog is now configured in the application. Start the application, and existing ILogger calls will be processed by NLog and written to the configured targets. If NLog is not working as expected, see the NLog Logging troubleshooting guide to identify configuration issues.","title":"4. Start logging"},{"location":"Getting-started-with-ASP.NET-Core-6/#i-see-also-examples-in-github","text":"","title":"\u2139\ufe0f See also examples in GitHub"},{"location":"GroupByWrapper-target/","text":"Allow one to to take an entire batch of logevents and group-by ex. request-identifier. Splitting the batch into individual emails / reports. Platforms Supported: All (Introduced with NLog 5.0) Configuration Syntax Parameters Key - Layout used for grouping the LogEvents into smaller batches. Example Creates a buffer of the last 50 LogEvents, and flushes when receiving LogEvent with LogLevel.Error. Then groups the LogEvents by their individual request (Using ${activity} other correlationid). Then generates output only containing the LogEvents matching the failed request. = LogLevel.Error\" flushOnConditionOnly=\"true\"> = LogLevel.Error\" filter=\"Log\"/> ","title":"GroupByWrapper target"},{"location":"GroupByWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"GroupByWrapper-target/#parameters","text":"Key - Layout used for grouping the LogEvents into smaller batches.","title":"Parameters"},{"location":"GroupByWrapper-target/#example","text":"Creates a buffer of the last 50 LogEvents, and flushes when receiving LogEvent with LogLevel.Error. Then groups the LogEvents by their individual request (Using ${activity} other correlationid). Then generates output only containing the LogEvents matching the failed request. = LogLevel.Error\" flushOnConditionOnly=\"true\"> = LogLevel.Error\" filter=\"Log\"/> ","title":"Example"},{"location":"Guid-layout-renderer/","text":"Globally-unique identifier (GUID). Platforms Supported: All Configuration Syntax ${guid:format=String} Parameters Rendering Options format - GUID format as accepted by Guid.ToString() method. Default: N GeneratedFromLogEvent - Creates a special GUID from the LogEvent, so if the LogEvent is written to multiple targets, then all targets will get the same GUID for the LogEvent (Like a CorrelationId). Default: False Introduced with NLog 4.5","title":"Guid layout renderer"},{"location":"Guid-layout-renderer/#configuration-syntax","text":"${guid:format=String}","title":"Configuration Syntax"},{"location":"Guid-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Guid-layout-renderer/#rendering-options","text":"format - GUID format as accepted by Guid.ToString() method. Default: N GeneratedFromLogEvent - Creates a special GUID from the LogEvent, so if the LogEvent is written to multiple targets, then all targets will get the same GUID for the LogEvent (Like a CorrelationId). Default: False Introduced with NLog 4.5","title":"Rendering Options"},{"location":"HTTP-target/","text":"NLog.Targets.HTTP NLog.Targets.HTTP is a HTTP POST target for NLog. Combined with JSON formatter it can be used to send events to an instance of Splunk and other HTTP based collectors. Getting started Add the library as an extension to nlog: ... Available Configuration Parameters Listed below are available configuration parameters with their default values URL The URL to send messages to (mandatory) Method HTTP method to use (GET, POST ,PUT, etc.) Authorization The Authorization Header value to pass. BatchSize Number of messages to be sent together in one call separated by an empty new line MaxQueueSize Maximum number of messages awaiting to be send. Please note, that if this value is set, the logger might be blocking. IgnoreSsslErrors Some SSL certificates might be invalid or not-trusted. FlushBeforeShutdown Force all messages to be delivered before shutting down. ContentType HTTP ContentType Header value. Accept HTTP Accept Header value. DefaultConnectionLimit How many connections might be used at the same time. Changes ServicePointManager.DefaultConnectionLimit, which might affect other parts of your system. Expect100Continue See this article . UseNagleAlgorithm The Nagle algorithm is used to buffer small packets of data and transmit them as a single packet. This process, referred to as \"nagling,\" is widely used because it reduces the number of packets transmitted and lowers the overhead per packet. The Nagle algorithm is fully described in IETF RFC 896. ConnectTimeout How long should the client wait to connect (default is 30 seconds). InMemoryCompression Reduces the amount of memory consumed at the expense of increased CPU usage. ProxyUrl Designates a proxy server to use. Must include protocol (http|https) and port ProxyUser If proxy authentication is needed, you can specify it with a domain prefix, i.e. DOMAIN\\USER. ProxyPassword Password to use for proxy authentication. Sample SPLUNK Configuration ","title":"NLog.Targets.HTTP"},{"location":"HTTP-target/#nlogtargetshttp","text":"NLog.Targets.HTTP is a HTTP POST target for NLog. Combined with JSON formatter it can be used to send events to an instance of Splunk and other HTTP based collectors.","title":"NLog.Targets.HTTP"},{"location":"HTTP-target/#getting-started","text":"Add the library as an extension to nlog: ...","title":"Getting started"},{"location":"HTTP-target/#available-configuration-parameters","text":"Listed below are available configuration parameters with their default values ","title":"Available Configuration Parameters"},{"location":"HTTP-target/#url","text":"The URL to send messages to (mandatory)","title":"URL"},{"location":"HTTP-target/#method","text":"HTTP method to use (GET, POST ,PUT, etc.)","title":"Method"},{"location":"HTTP-target/#authorization","text":"The Authorization Header value to pass.","title":"Authorization"},{"location":"HTTP-target/#batchsize","text":"Number of messages to be sent together in one call separated by an empty new line","title":"BatchSize"},{"location":"HTTP-target/#maxqueuesize","text":"Maximum number of messages awaiting to be send. Please note, that if this value is set, the logger might be blocking.","title":"MaxQueueSize"},{"location":"HTTP-target/#ignoressslerrors","text":"Some SSL certificates might be invalid or not-trusted.","title":"IgnoreSsslErrors"},{"location":"HTTP-target/#flushbeforeshutdown","text":"Force all messages to be delivered before shutting down.","title":"FlushBeforeShutdown"},{"location":"HTTP-target/#contenttype","text":"HTTP ContentType Header value.","title":"ContentType"},{"location":"HTTP-target/#accept","text":"HTTP Accept Header value.","title":"Accept"},{"location":"HTTP-target/#defaultconnectionlimit","text":"How many connections might be used at the same time. Changes ServicePointManager.DefaultConnectionLimit, which might affect other parts of your system.","title":"DefaultConnectionLimit"},{"location":"HTTP-target/#expect100continue","text":"See this article .","title":"Expect100Continue"},{"location":"HTTP-target/#usenaglealgorithm","text":"The Nagle algorithm is used to buffer small packets of data and transmit them as a single packet. This process, referred to as \"nagling,\" is widely used because it reduces the number of packets transmitted and lowers the overhead per packet. The Nagle algorithm is fully described in IETF RFC 896.","title":"UseNagleAlgorithm"},{"location":"HTTP-target/#connecttimeout","text":"How long should the client wait to connect (default is 30 seconds).","title":"ConnectTimeout"},{"location":"HTTP-target/#inmemorycompression","text":"Reduces the amount of memory consumed at the expense of increased CPU usage.","title":"InMemoryCompression"},{"location":"HTTP-target/#proxyurl","text":"Designates a proxy server to use. Must include protocol (http|https) and port","title":"ProxyUrl"},{"location":"HTTP-target/#proxyuser","text":"If proxy authentication is needed, you can specify it with a domain prefix, i.e. DOMAIN\\USER.","title":"ProxyUser"},{"location":"HTTP-target/#proxypassword","text":"Password to use for proxy authentication.","title":"ProxyPassword"},{"location":"HTTP-target/#sample-splunk-configuration","text":" ","title":"Sample SPLUNK Configuration"},{"location":"Home/","text":"Welcome to the NLog documentation! Just start with one of the tutorials to log messages within minutes! NLog supports the .NET Frameworks 3.5 - 4.8 along with ASP.NET Core using Microsoft dependency injection. See the getting started pages. For structured logging, introduced in NLog 4.5, see How to use structured logging There are many available output options: NLog Targets - Output destinations NLog Layout-Renderers - Output details NLog Layouts - Output formats Are you missing some targets or layouts in NLog? Check extending NLog or even better, contribute to NLog ! Issues with logging? Check the Troubleshooting Guide","title":"Home"},{"location":"Host-AppName-Layout-Renderer/","text":"HostEnvironment ApplicationName Platforms Supported: All Introduced with NLog.Extensions.Hostting v6.0 and NLog.Web.AspNetCore v6.0 Configuration Syntax ${host-appname}","title":"Host AppName Layout Renderer"},{"location":"Host-AppName-Layout-Renderer/#configuration-syntax","text":"${host-appname}","title":"Configuration Syntax"},{"location":"Host-Environment-Layout-Renderer/","text":"HostEnvironment EnvironmentName ( DOTNET_ENVIRONMENT / ASPNETCORE_ENVIRONMENT ) Platforms Supported: All Introduced with NLog.Extensions.Hostting v6.0 and NLog.Web.AspNetCore v6.0 Configuration Syntax ${host-environment} Remarks The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or \"environment\" as specified in any other configuration source.","title":"Host Environment Layout Renderer"},{"location":"Host-Environment-Layout-Renderer/#configuration-syntax","text":"${host-environment}","title":"Configuration Syntax"},{"location":"Host-Environment-Layout-Renderer/#remarks","text":"The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or \"environment\" as specified in any other configuration source.","title":"Remarks"},{"location":"Host-RootDir-Layout-Renderer/","text":"HostEnvironment Content Root Platforms Supported: All (Supported in Asp.NetCore and Asp.NET ) Introduced with NLog.Extensions.Hosting v6.0.0 and NLog.Web.AspNetCore v6.0.0 and NLog.Web v6.0.0 Configuration Syntax ${host-rootdir} Remarks Application base path is also known as the content root, while wwwroot -path is root directory for static content.","title":"Host RootDir Layout Renderer"},{"location":"Host-RootDir-Layout-Renderer/#configuration-syntax","text":"${host-rootdir}","title":"Configuration Syntax"},{"location":"Host-RootDir-Layout-Renderer/#remarks","text":"Application base path is also known as the content root, while wwwroot -path is root directory for static content.","title":"Remarks"},{"location":"HostName-Layout-Renderer/","text":"The computer DNS HostName that the process is running on. Platforms Supported: All Introduced with NLog 4.6 Configuration Syntax ${hostname} Remarks See also ${machinename} For NetBIOS name See also ${local-ip} For IP Address","title":"HostName Layout Renderer"},{"location":"HostName-Layout-Renderer/#configuration-syntax","text":"${hostname}","title":"Configuration Syntax"},{"location":"HostName-Layout-Renderer/#remarks","text":"See also ${machinename} For NetBIOS name See also ${local-ip} For IP Address","title":"Remarks"},{"location":"How-to-Log-Exceptions/","text":"Exceptions require special treatment in NLog. You need to call the method on the Logger class which takes an Exception as its first argument. The method name matches the log level. For instance, to log an exception using the Error loglevel, do: logger.Error(ex, \"Oops, an exception occured\"); Please note : the methods have been changed in NLog 4.0. Previous versions expected the exception after the message. Example You typically log exceptions inside a catch handler. An example of logging an exception with the Error LogLevel is seen in the following: try { // some code which may throw } catch (MyException ex) { logger.Error(ex, \"Got exception.\"); // NLog 4.0 and newer logger.Error(\"Got exception.\", ex); // Before NLog 4.0, and now obsolete } Exception Formatting To write the details of the exception, use the ${exception} in your layout. Depending on the desired output you may want to specify different value for the format argument. The following example displays the result of calling ToString() on the exception object. For simpler scenarios you may directly use the ${message:withException=true} , which is used in the default Layout in NLog v5.0: ","title":"How to Log Exceptions"},{"location":"How-to-Log-Exceptions/#example","text":"You typically log exceptions inside a catch handler. An example of logging an exception with the Error LogLevel is seen in the following: try { // some code which may throw } catch (MyException ex) { logger.Error(ex, \"Got exception.\"); // NLog 4.0 and newer logger.Error(\"Got exception.\", ex); // Before NLog 4.0, and now obsolete }","title":"Example"},{"location":"How-to-Log-Exceptions/#exception-formatting","text":"To write the details of the exception, use the ${exception} in your layout. Depending on the desired output you may want to specify different value for the format argument. The following example displays the result of calling ToString() on the exception object. For simpler scenarios you may directly use the ${message:withException=true} , which is used in the default Layout in NLog v5.0: ","title":"Exception Formatting"},{"location":"How-to-create-Logger-for-sub-classes/","text":"When we wish to expose the logger into sub classes the following pattern could be used. class BaseClass { protected BaseClass() { Log = LogManager.GetLogger(GetType().ToString()); } protected Logger Log { get; private set; } } class ExactClass : BaseClass { public ExactClass() : base() { } ... } Alternative solution could be this: class BaseClass { protected virtual Logger Log { get { return _logger; } } private static Logger _logger = LogManager.GetCurrentClassLogger(); } class ExactClass : BaseClass { protected override Logger Log { get { return _logger; } } private static Logger _logger = LogManager.GetCurrentClassLogger(); }","title":"How to create Logger for sub classes"},{"location":"How-to-use-structured-logging/","text":"NLog has always supported structured logging using LogEventInfo Properties with key-value pairs (aka. semantic logging). NLog 4.5 extended this by supporting message-templates and extracting named properties together with destructuring support. NLog supports the message templates syntax defined by: https://messagetemplates.org/ Why structured logging Structured logging makes it easier to store and query log-events, as the logevent message-template and message-parameters are preserved, instead of just transforming them into a formatted message. The normal .NET string.Format(...) will only accept input strings like this: logger.Info(\"Logon by user:{0} from ip_address:{1}\", \"Kenny\", \"127.0.0.1\"); logger.Debug(\"Shopitem:{0} added to basket by user:{1}\", \"Jacket\", \"Kenny\"); When storing these log-events in a database (or somewhere else), then it can be difficult to query all actions performed by a certain user. Also it could be hard to group similar events. The workaround would then be to perform RegEx-queries to recognize logevent messages and convert them into a more structured format, and register which parameter index is the user. The RegEx might even have to extract the needed details from the formatted message, making it even more fragile. Maintaining these RegEx-queries can become rather cumbersome. Instead of using the message-template to group LogEvents, then Microsoft recommends using EventId / EventName to make it easy to identify LogEvent patterns. This gives more freedom to change the message-template if needed, and the EventName provides a simple human-readable-identifier. Further history: messagetemplates.org Using structured logging NLog has always supported log-event metadata called event-properties , but it requires a little effort to generate a log-event with properties. See also the Fluent-Logger-API NLog 4.5 makes it possible to capture log-event-properties from the log-message-template, so they can be easily processed by the NLog destination target: logger.Info(\"Logon by {user} from {ip_address}\", \"Kenny\", \"127.0.0.1\"); // Logon by \"Kenny\" from \"127.0.0.1\" logger.Debug(\"{shopitem} added to basket by {user}\", new { Id=6, Name = \"Jacket\", Color = \"Orange\" }, \"Kenny\"); Any NLog destination target that is able to handle log-event-properties will automatically experience the benefit of doing structured logging. Formatting of the message The formatting of message depends on the datatype of the parameters. Example: logger.Info(\"Order {orderid} created for {user}\", 42, \"Kenny\"); Will be formatted as (Before NLog v6 strings would had quotes): Order 42 created for Kenny The formatting is controlled by the datatype of the parameter: - null: printed as NULL - list/ienumerable/array: item1, item2 - dictionary: key1=value1, key2=value2 - objects: ToString() It's possible to control formatting by preceding @ or $ : @ will format the object as JSON $ forces ToString() Examples Object o = null; logger.Info(\"Test {value1}\", o); // null case. Result: Test NULL logger.Info(\"Test {value1}\", new DateTime(2018,03, 25)); // datetime case. Result: Test 25-3-2018 00:00:00 (locale ToString) logger.Info(\"Test {value1}\", new List { \"a\", \"b\" }); // list of strings. Result: Test a, b logger.Info(\"Test {value1}\", new[] { \"a\", \"b\" }); // array. Result: Test a, b logger.Info(\"Test {value1}\", new Dictionary { { \"key1\", 1 }, { \"key2\", 2 } }); // dict. Result: Test key1=1, key2=2 var order = new Order { OrderId = 2, Status = OrderStatus.Processing }; logger.Info(\"Test {value1}\", order); // object Result: Test MyProgram.Program+Order logger.Info(\"Test {@value1}\", order); // object Result: Test {\"OrderId\":2, \"Status\":\"Processing\"} logger.Info(\"Test {value1}\", new { OrderId = 2, Status = \"Processing\"}); // anonymous object. Result: Test { OrderId = 2, Status = Processing } logger.Info(\"Test {@value1}\", new { OrderId = 2, Status = \"Processing\"}); // anonymous object. Result: Test {\"OrderId\":2, \"Status\":\"Processing\"} Output captured properties When formatting the log message, then it will automatically serialize the parameters (see Formatting of the message ). It is also possible to configure NLog Layout to serialize the individual properties. This can be done by using ${event-properties} or ${all-event-properties} , for example: ${longdate}|${level}|${logger}|${message}|${all-event-properties}{exception:format=tostring} NLog Layouts with option includeEventProperties=\"true\" (Before NLog 5.0 it was includeAllProperties=\"true\" ) will output captured properties from structured logging: Json Layout Log4JXml Layout Xml Layout It can be configured like this: NLog 4.5 adds support for rendering the raw message-template, instead of just the formatted message: * ${message:raw=true} NLog 4.5 extends the following NLog LayoutRenderers with support for serializing with property reflection into JSON when format=\"@\" ${event-properties} ${exception} ${gdc} - Global Context ${scopeproperty} - Thread Context (Before NLog 5.0 it was ${mdc} + ${mdlc} ) In code you can use LogEventInfo.Properties . If having special interest in format-options for the captured parameters then one can use LogEventInfo.MessageTemplateParameters NLog Target Support Any NLog destination target that handles event-properties will be able to take advantage of structured logging. Many targets already has support for the option includeEventProperties=\"true\" , that comes automatically when inheriting from TargetWithContext . NLog Targets with supports for NLog Layout as payload will automatically support structured logging: NLogViewer Target makes use of Log4JXml Layout . WebService Target can perform JSON-post with Json Layout . Network Target can publish both Json Layout and Xml Layout to any TCP/UDP-endpoint. Database Target can write to an XML column using Xml Layout There are already many custom NLog targets that provide the ability to store log-events in central storage, and allow a Web-Application to query the log-events along with their event-properties. These targets will automatically benefit from structured logging, and allow the Web-Application to perform effective queries. Transform captured properties Extract single property NLog 4.6.3 allows you to navigate into a complex object and extract a single property. Ex: logger.Debug(\"{shopitem} added to basket by {user}\", new { Id=6, Name = \"Jacket\", Color = \"Orange\" }, \"Kenny\"); Then one can extract specific details from shopItem -property: Customize Object Reflection To avoid object reflection for a custom type, then just implement the IFormattable -interface, and NLog will call ToString() instead of doing reflection of properties. NLog 4.7 allows you to transform large (or dangerous) objects into a more reduced/safe object: LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(ex => new { Type = ex.GetType().ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, InnerException = ex.InnerException, Status = ex.Status, Response = ex.Response.ToString(), // Call your custom method to render stream as string }) ); This can also be used to output object-fields, as the NLog Object Reflection only sees object-properties. By transforming into an Anonymous Type, and assigning the wanted object-fields to named properties. If more dynamic reflection is required, then one can also just return a Dictionary instead of returning an Anonymous Type (The performance hit is a little higher). Note when making an override for an object-type, then the returned object-type must be of a different object-type (Ex. anonymous object). Because NLog caches the reflection of the return object-type, and afterwards NLog skips checking for transformation for already cached object-types. Advanced How to override parameter value formatter Create a new class that NLog.IValueFormatter and set NLog.Config.ConfigurationItemFactory.Default.ValueFormatter How to override JSON formatter You can override the builtin NLog JSON converter with a different implementation. You need a custom NLog.IJsonConverter and set NLog.Config.ConfigurationItemFactory.Default.JsonConverter Example of using JSON.NET that supports JSON.NET object annotations like [JsonIgnore] : internal class JsonNetSerializer : NLog.IJsonConverter { readonly JsonSerializerSettings _settings; public JsonNetSerializer() { _settings = new JsonSerializerSettings { Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; } /// Serialization of an object into JSON format. /// The object to serialize to JSON. /// Output destination. /// Serialize succeeded (true/false) public bool SerializeObject(object value, StringBuilder builder) { try { var jsonSerializer = JsonSerializer.CreateDefault(_settings); var sw = new System.IO.StringWriter(builder, System.Globalization.CultureInfo.InvariantCulture); using (var jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonWriter, value, null); } } catch (Exception e) { NLog.Common.InternalLogger.Error(e, \"Error when custom JSON serialization\"); return false; } return true; } } Combine indexed and structured logging e.g. logging \"Hello {0} with {Message}\" For backward compatibility (and performance), then NLog will by default skip full parsing if it detects the first parameter as being positional index. This will ensure repeated positional-placeholders supported by string.Format will continue to work: string.Format(\"{1}{0}{2}{0}\", Environment.NewLine, \"Hello\", \"World\"); When parseMessageTemplates='true' then NLog will always parse all parameters, and if one is non-numeric, then all the parameters will be treated as structured parameters. Mixing and numeric and structured parameters is not recommended, as it hurts performance (backtrack) and numeric parameters are most of the time not so descriptive. Parameter Names The Names of the parameters should be unique I just need the template e.g. Order {orderId} Use ${message:raw=true} Disabling Message Template Support NLog will by default attempt to parse log-events as structured log-events. This gives a minor overhead, that will not be noticable by most. It is possible to disable this behavior, telling NLog it should not attempt to parse log-events as structured log-events, with this xml-setting: ... Restore String Quotes NLog v6 removed quotes for strings to behave like Microsoft Extensions Logging. To revert to old behavior with string-quotes: LogManager.Setup().SetupSerialization(s => s.RegisterValueFormatterWithStringQuotes()); Alternative one can use @ to add string-quotes: Logger.Info(\"Hello {@World}\", \"Earth\"); // Outputs Hello \"Earth\"","title":"How to use structured logging"},{"location":"How-to-use-structured-logging/#why-structured-logging","text":"Structured logging makes it easier to store and query log-events, as the logevent message-template and message-parameters are preserved, instead of just transforming them into a formatted message. The normal .NET string.Format(...) will only accept input strings like this: logger.Info(\"Logon by user:{0} from ip_address:{1}\", \"Kenny\", \"127.0.0.1\"); logger.Debug(\"Shopitem:{0} added to basket by user:{1}\", \"Jacket\", \"Kenny\"); When storing these log-events in a database (or somewhere else), then it can be difficult to query all actions performed by a certain user. Also it could be hard to group similar events. The workaround would then be to perform RegEx-queries to recognize logevent messages and convert them into a more structured format, and register which parameter index is the user. The RegEx might even have to extract the needed details from the formatted message, making it even more fragile. Maintaining these RegEx-queries can become rather cumbersome. Instead of using the message-template to group LogEvents, then Microsoft recommends using EventId / EventName to make it easy to identify LogEvent patterns. This gives more freedom to change the message-template if needed, and the EventName provides a simple human-readable-identifier. Further history: messagetemplates.org","title":"Why structured logging"},{"location":"How-to-use-structured-logging/#using-structured-logging","text":"NLog has always supported log-event metadata called event-properties , but it requires a little effort to generate a log-event with properties. See also the Fluent-Logger-API NLog 4.5 makes it possible to capture log-event-properties from the log-message-template, so they can be easily processed by the NLog destination target: logger.Info(\"Logon by {user} from {ip_address}\", \"Kenny\", \"127.0.0.1\"); // Logon by \"Kenny\" from \"127.0.0.1\" logger.Debug(\"{shopitem} added to basket by {user}\", new { Id=6, Name = \"Jacket\", Color = \"Orange\" }, \"Kenny\"); Any NLog destination target that is able to handle log-event-properties will automatically experience the benefit of doing structured logging.","title":"Using structured logging"},{"location":"How-to-use-structured-logging/#formatting-of-the-message","text":"The formatting of message depends on the datatype of the parameters. Example: logger.Info(\"Order {orderid} created for {user}\", 42, \"Kenny\"); Will be formatted as (Before NLog v6 strings would had quotes): Order 42 created for Kenny The formatting is controlled by the datatype of the parameter: - null: printed as NULL - list/ienumerable/array: item1, item2 - dictionary: key1=value1, key2=value2 - objects: ToString() It's possible to control formatting by preceding @ or $ : @ will format the object as JSON $ forces ToString()","title":"Formatting of the message"},{"location":"How-to-use-structured-logging/#examples","text":"Object o = null; logger.Info(\"Test {value1}\", o); // null case. Result: Test NULL logger.Info(\"Test {value1}\", new DateTime(2018,03, 25)); // datetime case. Result: Test 25-3-2018 00:00:00 (locale ToString) logger.Info(\"Test {value1}\", new List { \"a\", \"b\" }); // list of strings. Result: Test a, b logger.Info(\"Test {value1}\", new[] { \"a\", \"b\" }); // array. Result: Test a, b logger.Info(\"Test {value1}\", new Dictionary { { \"key1\", 1 }, { \"key2\", 2 } }); // dict. Result: Test key1=1, key2=2 var order = new Order { OrderId = 2, Status = OrderStatus.Processing }; logger.Info(\"Test {value1}\", order); // object Result: Test MyProgram.Program+Order logger.Info(\"Test {@value1}\", order); // object Result: Test {\"OrderId\":2, \"Status\":\"Processing\"} logger.Info(\"Test {value1}\", new { OrderId = 2, Status = \"Processing\"}); // anonymous object. Result: Test { OrderId = 2, Status = Processing } logger.Info(\"Test {@value1}\", new { OrderId = 2, Status = \"Processing\"}); // anonymous object. Result: Test {\"OrderId\":2, \"Status\":\"Processing\"}","title":"Examples"},{"location":"How-to-use-structured-logging/#output-captured-properties","text":"When formatting the log message, then it will automatically serialize the parameters (see Formatting of the message ). It is also possible to configure NLog Layout to serialize the individual properties. This can be done by using ${event-properties} or ${all-event-properties} , for example: ${longdate}|${level}|${logger}|${message}|${all-event-properties}{exception:format=tostring} NLog Layouts with option includeEventProperties=\"true\" (Before NLog 5.0 it was includeAllProperties=\"true\" ) will output captured properties from structured logging: Json Layout Log4JXml Layout Xml Layout It can be configured like this: NLog 4.5 adds support for rendering the raw message-template, instead of just the formatted message: * ${message:raw=true} NLog 4.5 extends the following NLog LayoutRenderers with support for serializing with property reflection into JSON when format=\"@\" ${event-properties} ${exception} ${gdc} - Global Context ${scopeproperty} - Thread Context (Before NLog 5.0 it was ${mdc} + ${mdlc} ) In code you can use LogEventInfo.Properties . If having special interest in format-options for the captured parameters then one can use LogEventInfo.MessageTemplateParameters","title":"Output captured properties"},{"location":"How-to-use-structured-logging/#nlog-target-support","text":"Any NLog destination target that handles event-properties will be able to take advantage of structured logging. Many targets already has support for the option includeEventProperties=\"true\" , that comes automatically when inheriting from TargetWithContext . NLog Targets with supports for NLog Layout as payload will automatically support structured logging: NLogViewer Target makes use of Log4JXml Layout . WebService Target can perform JSON-post with Json Layout . Network Target can publish both Json Layout and Xml Layout to any TCP/UDP-endpoint. Database Target can write to an XML column using Xml Layout There are already many custom NLog targets that provide the ability to store log-events in central storage, and allow a Web-Application to query the log-events along with their event-properties. These targets will automatically benefit from structured logging, and allow the Web-Application to perform effective queries.","title":"NLog Target Support"},{"location":"How-to-use-structured-logging/#transform-captured-properties","text":"","title":"Transform captured properties"},{"location":"How-to-use-structured-logging/#extract-single-property","text":"NLog 4.6.3 allows you to navigate into a complex object and extract a single property. Ex: logger.Debug(\"{shopitem} added to basket by {user}\", new { Id=6, Name = \"Jacket\", Color = \"Orange\" }, \"Kenny\"); Then one can extract specific details from shopItem -property: ","title":"Extract single property"},{"location":"How-to-use-structured-logging/#customize-object-reflection","text":"To avoid object reflection for a custom type, then just implement the IFormattable -interface, and NLog will call ToString() instead of doing reflection of properties. NLog 4.7 allows you to transform large (or dangerous) objects into a more reduced/safe object: LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(ex => new { Type = ex.GetType().ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, InnerException = ex.InnerException, Status = ex.Status, Response = ex.Response.ToString(), // Call your custom method to render stream as string }) ); This can also be used to output object-fields, as the NLog Object Reflection only sees object-properties. By transforming into an Anonymous Type, and assigning the wanted object-fields to named properties. If more dynamic reflection is required, then one can also just return a Dictionary instead of returning an Anonymous Type (The performance hit is a little higher). Note when making an override for an object-type, then the returned object-type must be of a different object-type (Ex. anonymous object). Because NLog caches the reflection of the return object-type, and afterwards NLog skips checking for transformation for already cached object-types.","title":"Customize Object Reflection"},{"location":"How-to-use-structured-logging/#advanced","text":"","title":"Advanced"},{"location":"How-to-use-structured-logging/#how-to-override-parameter-value-formatter","text":"Create a new class that NLog.IValueFormatter and set NLog.Config.ConfigurationItemFactory.Default.ValueFormatter","title":"How to override parameter value formatter"},{"location":"How-to-use-structured-logging/#how-to-override-json-formatter","text":"You can override the builtin NLog JSON converter with a different implementation. You need a custom NLog.IJsonConverter and set NLog.Config.ConfigurationItemFactory.Default.JsonConverter Example of using JSON.NET that supports JSON.NET object annotations like [JsonIgnore] : internal class JsonNetSerializer : NLog.IJsonConverter { readonly JsonSerializerSettings _settings; public JsonNetSerializer() { _settings = new JsonSerializerSettings { Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; } /// Serialization of an object into JSON format. /// The object to serialize to JSON. /// Output destination. /// Serialize succeeded (true/false) public bool SerializeObject(object value, StringBuilder builder) { try { var jsonSerializer = JsonSerializer.CreateDefault(_settings); var sw = new System.IO.StringWriter(builder, System.Globalization.CultureInfo.InvariantCulture); using (var jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonWriter, value, null); } } catch (Exception e) { NLog.Common.InternalLogger.Error(e, \"Error when custom JSON serialization\"); return false; } return true; } }","title":"How to override JSON formatter"},{"location":"How-to-use-structured-logging/#combine-indexed-and-structured-logging","text":"e.g. logging \"Hello {0} with {Message}\" For backward compatibility (and performance), then NLog will by default skip full parsing if it detects the first parameter as being positional index. This will ensure repeated positional-placeholders supported by string.Format will continue to work: string.Format(\"{1}{0}{2}{0}\", Environment.NewLine, \"Hello\", \"World\"); When parseMessageTemplates='true' then NLog will always parse all parameters, and if one is non-numeric, then all the parameters will be treated as structured parameters. Mixing and numeric and structured parameters is not recommended, as it hurts performance (backtrack) and numeric parameters are most of the time not so descriptive.","title":"Combine indexed and structured logging"},{"location":"How-to-use-structured-logging/#parameter-names","text":"The Names of the parameters should be unique","title":"Parameter Names"},{"location":"How-to-use-structured-logging/#i-just-need-the-template","text":"e.g. Order {orderId} Use ${message:raw=true}","title":"I just need the template"},{"location":"How-to-use-structured-logging/#disabling-message-template-support","text":"NLog will by default attempt to parse log-events as structured log-events. This gives a minor overhead, that will not be noticable by most. It is possible to disable this behavior, telling NLog it should not attempt to parse log-events as structured log-events, with this xml-setting: ... ","title":"Disabling Message Template Support"},{"location":"How-to-use-structured-logging/#restore-string-quotes","text":"NLog v6 removed quotes for strings to behave like Microsoft Extensions Logging. To revert to old behavior with string-quotes: LogManager.Setup().SetupSerialization(s => s.RegisterValueFormatterWithStringQuotes()); Alternative one can use @ to add string-quotes: Logger.Info(\"Hello {@World}\", \"Earth\"); // Outputs Hello \"Earth\"","title":"Restore String Quotes"},{"location":"How-to-write-a-Target/","text":"See How to write a custom target","title":"How to write a Target"},{"location":"How-to-write-a-custom-async-target/","text":"Introduced with NLog 4.6 It is really easy: Create a class that inherits from NLog.Targets.AsyncTaskTarget Override the WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) method. In the body of this method invoke this.RenderLogEvent(this.Layout, logEvent) to get the message text, and invoke this.GetAllProperties(logEvent) to get structured properties. \u26a0\ufe0f Don't forget to Register-your-custom-component when loading NLog config! Example using NLog; using NLog.Config; using NLog.Targets; namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget : AsyncTaskTarget { public MyFirstTarget() { this.IncludeEventProperties = true; // Include LogEvent Properties by default } public Layout Host { get; set; } = \"localhost\"; protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) { string logMessage = this.RenderLogEvent(this.Layout, logEvent); string hostName = this.RenderLogEvent(this.Host, logEvent); IDictionary logProperties = this.GetAllProperties(logEvent); return SendTheMessageToRemoteHost(hostName, logMessage, logProperties); } private async Task SendTheMessageToRemoteHost(string hostName, string message, IDictionary properties) { // TODO - write me } } } AsyncTaskTarget Features AsyncTaskTarget has an internal queue (Initial capacity is 10000), so if the Tasks constantly performs timeout then at one point the queue will be filled. The OverflowAction will then take over (Default = Discard to avoid eating all memory). Timeout and Retry Logic There are several options: TaskTimeoutSeconds - How many seconds a Task is allowed to run before it is cancelled (Default 150 secs) RetryDelayMilliseconds - How many milliseconds to wait before next retry (Default 500ms, and will be doubled on each retry). RetryCount - How many attempts to retry the same Task, before it is aborted (Default 0) If wanting to have more control of when to retry (Checking the Exception ), or perform connection recovery on failure, then override this method: protected override bool RetryFailedAsyncTask(Exception exception, CancellationToken cancellationToken, int retryCountRemaining, out TimeSpan retryDelay) { return base.RetryFailedAsyncTask(exception, cancellationToken, retryCountRemaining, out retryDelay); // Default behavior } Batch Logic Activated when overriding this method: protected override Task WriteAsyncTask(IList logEvents, CancellationToken cancellationToken) { // TODO - write batch } There are several options: - BatchSize - Gets or sets the number of log events that should be processed in a batch by the lazy writer thread. (Default 1) - TaskDelayMilliseconds - How many milliseconds to delay the actual write operation to optimize for batching (Default 1 ms) - QueueLimit - Gets or sets the limit on the number of requests in the lazy writer thread request queue (Default 10000) - OverflowAction - Gets or sets the action to be taken when the lazy writer thread request queue count exceeds the set limit (Default Discard). TargetWithContext Features AsyncTaskTarget inherits the TargetWithContext features , that allows one to configure additional context properties for extended structured logging capabilities. The structured properties can be retrieved inside WriteAsyncTask -method by calling this.GetAllProperties(logEvent) .","title":"How to write a custom async target"},{"location":"How-to-write-a-custom-async-target/#example","text":"using NLog; using NLog.Config; using NLog.Targets; namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget : AsyncTaskTarget { public MyFirstTarget() { this.IncludeEventProperties = true; // Include LogEvent Properties by default } public Layout Host { get; set; } = \"localhost\"; protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) { string logMessage = this.RenderLogEvent(this.Layout, logEvent); string hostName = this.RenderLogEvent(this.Host, logEvent); IDictionary logProperties = this.GetAllProperties(logEvent); return SendTheMessageToRemoteHost(hostName, logMessage, logProperties); } private async Task SendTheMessageToRemoteHost(string hostName, string message, IDictionary properties) { // TODO - write me } } }","title":"Example"},{"location":"How-to-write-a-custom-async-target/#asynctasktarget-features","text":"AsyncTaskTarget has an internal queue (Initial capacity is 10000), so if the Tasks constantly performs timeout then at one point the queue will be filled. The OverflowAction will then take over (Default = Discard to avoid eating all memory).","title":"AsyncTaskTarget Features"},{"location":"How-to-write-a-custom-async-target/#timeout-and-retry-logic","text":"There are several options: TaskTimeoutSeconds - How many seconds a Task is allowed to run before it is cancelled (Default 150 secs) RetryDelayMilliseconds - How many milliseconds to wait before next retry (Default 500ms, and will be doubled on each retry). RetryCount - How many attempts to retry the same Task, before it is aborted (Default 0) If wanting to have more control of when to retry (Checking the Exception ), or perform connection recovery on failure, then override this method: protected override bool RetryFailedAsyncTask(Exception exception, CancellationToken cancellationToken, int retryCountRemaining, out TimeSpan retryDelay) { return base.RetryFailedAsyncTask(exception, cancellationToken, retryCountRemaining, out retryDelay); // Default behavior }","title":"Timeout and Retry Logic"},{"location":"How-to-write-a-custom-async-target/#batch-logic","text":"Activated when overriding this method: protected override Task WriteAsyncTask(IList logEvents, CancellationToken cancellationToken) { // TODO - write batch } There are several options: - BatchSize - Gets or sets the number of log events that should be processed in a batch by the lazy writer thread. (Default 1) - TaskDelayMilliseconds - How many milliseconds to delay the actual write operation to optimize for batching (Default 1 ms) - QueueLimit - Gets or sets the limit on the number of requests in the lazy writer thread request queue (Default 10000) - OverflowAction - Gets or sets the action to be taken when the lazy writer thread request queue count exceeds the set limit (Default Discard).","title":"Batch Logic"},{"location":"How-to-write-a-custom-async-target/#targetwithcontext-features","text":"AsyncTaskTarget inherits the TargetWithContext features , that allows one to configure additional context properties for extended structured logging capabilities. The structured properties can be retrieved inside WriteAsyncTask -method by calling this.GetAllProperties(logEvent) .","title":"TargetWithContext Features"},{"location":"How-to-write-a-custom-layout-renderer/","text":"Layout renderers can capture, format and output additional context details that can be used by NLog Layouts . There are 2 ways to create a custom layout renderer. 1) Register custom lambda-delegate-function with a symbol-name (Introduced with NLog v4.4) 2) Register custom class that inherits from LayoutRenderer that also supports additional configuration options. \u26a0\ufe0f Don't forget to Register-your-custom-component when loading NLog config! Lambda Function NLog 4.7 introduces a fluent registration API using LogManager.Setup() , where you create a layout renderer with a lambda: NLog.LogManager.Setup().SetupExtensions(s => s.RegisterLayoutRenderer(\"trace_id\", (logevent) => CorrelationIdentifier.TraceId.ToString()) ); NLog 4.4 was the first edition to support lambda function will accept 1 or 2 parameters and should return a string . 1 parameter: the logEventInfo . 2 parameters: logEventInfo and the current NLog config. Examples //register ${text-fixed} LayoutRenderer.Register(\"text-fixed\", (logEvent) => \"2\"); //register ${trace-identifier} LayoutRenderer.Register(\"trace-identifier\", (logEvent) => HttpContext.Current.TraceIdentifier); //Using logEventInfo, ${message-length} LayoutRenderer.Register(\"message-length\", (logEvent) => logEvent.FormattedMessage.Length); //Using config, ${targetCount} LayoutRenderer.Register(\"targetCount\",(logEvent, config) => config.AllTargets.Count); ASP.NET HttpContext Need the HTTP-context (e.g. Request, Session etc) for ASP.NET or ASP.NET Core? Include the NLog.Web (ASP.NET Classic) or NLog.Web.AspNetCore nuget-package. And usage: using NLog; LogManager.Setup().SetupExtensions(builder => { builder.RegisterAspNetLayoutRenderer(\"SessionItem1\", (logEventInfo, httpContext, loggingConfiguration) => httpContext.Session.GetString(\"SessionItem\")); // usage ${SessionItem1} }); Class Create a class that inherits from NLog.LayoutRenderers.LayoutRenderer , set the [LayoutRenderer(\"your-name\")] on the class and override the Append(StringBuilder builder, LogEventInfo logEvent) method. Invoke in this method builder.Append(..) to render your custom layout renderer. Example We create a ${hello-world} layout renderer, which renders...\"hello world!\". [LayoutRenderer(\"hello-world\")] public class HelloWorldLayoutRenderer : LayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(\"hello world!\"); } } How to pass configuration options to the layout render? Use public class-properties for configuring the LayoutRenderer: [LayoutRenderer(\"hello-world\")] public class HelloWorldLayoutRenderer : LayoutRenderer { /// /// New special option /// [DefaultParameter] public string SpecialOption{ get; set; } /// /// New extra option /// public bool ExtraOption{ get; set; } The [DefaultParameter] -attribute can only be assigned to one class-property, and gives the ability to assign the class-property-value without specifying the class-property-name. Example usages: ${hello-world:Bonus} - Assigns SpecialOption = Bonus . ${hello-world:SpecialOption=Bonus} - Assigns SpecialOption = Bonus . ${hello-world:ExtraOption=true} - Assigns ExtraOption = true . ${hello-world:Bonus:ExtraOption=true} - Assigns SpecialOption = Bonus and ExtraOption = true . If additional option-validation are required, then override void InitializeLayoutRenderer() and implement the necessary validation, and throw NLogConfigurationException(\"...\") when issues are detected. How to optimize performance for the layout renderer NLog will automatically capture relevant context state, when using AsyncWrapper-target to perform actual writing on background-thread (to avoid logging objects after they have been disposed). The following class-attributes can used for the LayoutRenderer that enables additional performance: [ThreadAgnostic] LayoutRenderer does not capture state from the application-thread logging. Ex. ${threadid} cannot be [ThreadAgnostic] . For LayoutRenderer marked as [ThreadAgnostic] then NLog can skip the overhead of capturing state. If just a single LayoutRenderer in a Layout is not marked as [ThreadAgnostic] , then NLog introduces the overhead of state capture. [ThreadSafe] Introduced with NLog 4.5.3, and made obsolete with NLog 5.0 that expects all to be threadsafe. LayoutRenderer will render correct output regardless of the number of application-threads running inside. For LayoutRenderer marked as [ThreadSafe] then NLog will skip using \"global\" locks when capturing state, thus application-threads will not experience lock-congestion inside NLog. If just a single LayoutRenderer in a Layout is not marked as [ThreadSafe] , then NLog introduces the overhead of \"global\" lock when doing state capture. Example of class-attributes for LayoutRenderer: using NLog.Config; [LayoutRenderer(\"hello-world\")] [ThreadAgnostic] public class HelloWorldLayoutRenderer : LayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(\"hello world!\"); } } Multiple type-alias attributes NLog 5.0 enables you to have multiple type-aliases for a single class. Before one had to inherit from the same class to provide additional type-names. [LayoutRenderer(\"hello-world\")] // ${hello-world} [LayoutRenderer(\"hello-earth\")] // ${hello-earth} public class HelloWorldLayoutRenderer : LayoutRenderer { The type-alias can then be used when wanting to use the LayoutRenderer in NLog SimpleLayout. Notice NLog 5.0 automatically ignores dashes - in type-alias, so no extra alias is needed for this: Ex. ${helloworld}","title":"How to write a custom layout renderer"},{"location":"How-to-write-a-custom-layout-renderer/#lambda-function","text":"NLog 4.7 introduces a fluent registration API using LogManager.Setup() , where you create a layout renderer with a lambda: NLog.LogManager.Setup().SetupExtensions(s => s.RegisterLayoutRenderer(\"trace_id\", (logevent) => CorrelationIdentifier.TraceId.ToString()) ); NLog 4.4 was the first edition to support lambda function will accept 1 or 2 parameters and should return a string . 1 parameter: the logEventInfo . 2 parameters: logEventInfo and the current NLog config. Examples //register ${text-fixed} LayoutRenderer.Register(\"text-fixed\", (logEvent) => \"2\"); //register ${trace-identifier} LayoutRenderer.Register(\"trace-identifier\", (logEvent) => HttpContext.Current.TraceIdentifier); //Using logEventInfo, ${message-length} LayoutRenderer.Register(\"message-length\", (logEvent) => logEvent.FormattedMessage.Length); //Using config, ${targetCount} LayoutRenderer.Register(\"targetCount\",(logEvent, config) => config.AllTargets.Count);","title":"Lambda Function"},{"location":"How-to-write-a-custom-layout-renderer/#aspnet-httpcontext","text":"Need the HTTP-context (e.g. Request, Session etc) for ASP.NET or ASP.NET Core? Include the NLog.Web (ASP.NET Classic) or NLog.Web.AspNetCore nuget-package. And usage: using NLog; LogManager.Setup().SetupExtensions(builder => { builder.RegisterAspNetLayoutRenderer(\"SessionItem1\", (logEventInfo, httpContext, loggingConfiguration) => httpContext.Session.GetString(\"SessionItem\")); // usage ${SessionItem1} });","title":"ASP.NET HttpContext"},{"location":"How-to-write-a-custom-layout-renderer/#class","text":"Create a class that inherits from NLog.LayoutRenderers.LayoutRenderer , set the [LayoutRenderer(\"your-name\")] on the class and override the Append(StringBuilder builder, LogEventInfo logEvent) method. Invoke in this method builder.Append(..) to render your custom layout renderer.","title":"Class"},{"location":"How-to-write-a-custom-layout-renderer/#example","text":"We create a ${hello-world} layout renderer, which renders...\"hello world!\". [LayoutRenderer(\"hello-world\")] public class HelloWorldLayoutRenderer : LayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(\"hello world!\"); } }","title":"Example"},{"location":"How-to-write-a-custom-layout-renderer/#how-to-pass-configuration-options-to-the-layout-render","text":"Use public class-properties for configuring the LayoutRenderer: [LayoutRenderer(\"hello-world\")] public class HelloWorldLayoutRenderer : LayoutRenderer { /// /// New special option /// [DefaultParameter] public string SpecialOption{ get; set; } /// /// New extra option /// public bool ExtraOption{ get; set; } The [DefaultParameter] -attribute can only be assigned to one class-property, and gives the ability to assign the class-property-value without specifying the class-property-name. Example usages: ${hello-world:Bonus} - Assigns SpecialOption = Bonus . ${hello-world:SpecialOption=Bonus} - Assigns SpecialOption = Bonus . ${hello-world:ExtraOption=true} - Assigns ExtraOption = true . ${hello-world:Bonus:ExtraOption=true} - Assigns SpecialOption = Bonus and ExtraOption = true . If additional option-validation are required, then override void InitializeLayoutRenderer() and implement the necessary validation, and throw NLogConfigurationException(\"...\") when issues are detected.","title":"How to pass configuration options to the layout render?"},{"location":"How-to-write-a-custom-layout-renderer/#how-to-optimize-performance-for-the-layout-renderer","text":"NLog will automatically capture relevant context state, when using AsyncWrapper-target to perform actual writing on background-thread (to avoid logging objects after they have been disposed). The following class-attributes can used for the LayoutRenderer that enables additional performance: [ThreadAgnostic] LayoutRenderer does not capture state from the application-thread logging. Ex. ${threadid} cannot be [ThreadAgnostic] . For LayoutRenderer marked as [ThreadAgnostic] then NLog can skip the overhead of capturing state. If just a single LayoutRenderer in a Layout is not marked as [ThreadAgnostic] , then NLog introduces the overhead of state capture. [ThreadSafe] Introduced with NLog 4.5.3, and made obsolete with NLog 5.0 that expects all to be threadsafe. LayoutRenderer will render correct output regardless of the number of application-threads running inside. For LayoutRenderer marked as [ThreadSafe] then NLog will skip using \"global\" locks when capturing state, thus application-threads will not experience lock-congestion inside NLog. If just a single LayoutRenderer in a Layout is not marked as [ThreadSafe] , then NLog introduces the overhead of \"global\" lock when doing state capture. Example of class-attributes for LayoutRenderer: using NLog.Config; [LayoutRenderer(\"hello-world\")] [ThreadAgnostic] public class HelloWorldLayoutRenderer : LayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(\"hello world!\"); } }","title":"How to optimize performance for the layout renderer"},{"location":"How-to-write-a-custom-layout-renderer/#multiple-type-alias-attributes","text":"NLog 5.0 enables you to have multiple type-aliases for a single class. Before one had to inherit from the same class to provide additional type-names. [LayoutRenderer(\"hello-world\")] // ${hello-world} [LayoutRenderer(\"hello-earth\")] // ${hello-earth} public class HelloWorldLayoutRenderer : LayoutRenderer { The type-alias can then be used when wanting to use the LayoutRenderer in NLog SimpleLayout. Notice NLog 5.0 automatically ignores dashes - in type-alias, so no extra alias is needed for this: Ex. ${helloworld}","title":"Multiple type-alias attributes"},{"location":"How-to-write-a-custom-target-for-structured-logging/","text":"Introduced with NLog 4.5 It is really easy: Create a class that inherits from NLog.Targets.TargetWithContext Override the Write(LogEventInfo logEvent) method. In the body of this method invoke this.RenderLogEvent(this.Layout, logEvent) to get the message text, and invoke this.GetAllProperties(logEvent) to get structured properties . \u26a0\ufe0f Don't forget to Register-your-custom-component when loading NLog config! See also the updated How to write a custom async target Example using NLog; using NLog.Config; using NLog.Targets; namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget : TargetWithContext { public MyFirstTarget() { this.IncludeEventProperties = true; // Include LogEvent Properties by default } public Layout Host { get; set; } = \"localhost\"; protected override void Write(LogEventInfo logEvent) { string logMessage = this.RenderLogEvent(this.Layout, logEvent); string hostName = this.RenderLogEvent(this.Host, logEvent); IDictionary logProperties = this.GetAllProperties(logEvent); SendTheMessageToRemoteHost(hostName, logMessage, logProperties); } private void SendTheMessageToRemoteHost(string hostName, string message, IDictionary properties) { // TODO - write me } } } TargetWithContext Features Additional Context Properties Users can easily configure additional context information: Without needing to inject the details upfront when doing the logging. It is automatically captured by the NLog engine. Include ScopeContext ScopeContext Properties can be used to provide context-specific details (Ex. request-correlationid from ILogger.BeginScope ). To automatically capture properties injected into ScopeContext (Before NLog 5.0 it was called IncludeMDLC ) ... Custom Merge Properties TargetWithContext will by default ensure that all captured property-values are included in output, and will automatically generate new unique key-name when name-collission. If wanting to merge properties, so one context can override another context, then one can do it like this: Instead of DefaultValue then you could also use one of the NLog LayoutRenderers available . Ex. ${aspnet-TraceIdentifier} or ${activity:property=TraceId} . Or alternative skip whenEmpty=DefaultValue and rely on IncludeEmptyValue=\"false\" (default).","title":"How to write a custom target for structured logging"},{"location":"How-to-write-a-custom-target-for-structured-logging/#example","text":"using NLog; using NLog.Config; using NLog.Targets; namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget : TargetWithContext { public MyFirstTarget() { this.IncludeEventProperties = true; // Include LogEvent Properties by default } public Layout Host { get; set; } = \"localhost\"; protected override void Write(LogEventInfo logEvent) { string logMessage = this.RenderLogEvent(this.Layout, logEvent); string hostName = this.RenderLogEvent(this.Host, logEvent); IDictionary logProperties = this.GetAllProperties(logEvent); SendTheMessageToRemoteHost(hostName, logMessage, logProperties); } private void SendTheMessageToRemoteHost(string hostName, string message, IDictionary properties) { // TODO - write me } } }","title":"Example"},{"location":"How-to-write-a-custom-target-for-structured-logging/#targetwithcontext-features","text":"","title":"TargetWithContext Features"},{"location":"How-to-write-a-custom-target-for-structured-logging/#additional-context-properties","text":"Users can easily configure additional context information: Without needing to inject the details upfront when doing the logging. It is automatically captured by the NLog engine.","title":"Additional Context Properties"},{"location":"How-to-write-a-custom-target-for-structured-logging/#include-scopecontext","text":"ScopeContext Properties can be used to provide context-specific details (Ex. request-correlationid from ILogger.BeginScope ). To automatically capture properties injected into ScopeContext (Before NLog 5.0 it was called IncludeMDLC ) ... ","title":"Include ScopeContext"},{"location":"How-to-write-a-custom-target-for-structured-logging/#custom-merge-properties","text":"TargetWithContext will by default ensure that all captured property-values are included in output, and will automatically generate new unique key-name when name-collission. If wanting to merge properties, so one context can override another context, then one can do it like this: Instead of DefaultValue then you could also use one of the NLog LayoutRenderers available . Ex. ${aspnet-TraceIdentifier} or ${activity:property=TraceId} . Or alternative skip whenEmpty=DefaultValue and rely on IncludeEmptyValue=\"false\" (default).","title":"Custom Merge Properties"},{"location":"How-to-write-a-custom-target/","text":"It\u2019s really easy: Create a class that inherits from NLog.Targets.TargetWithLayout Override the Write() method. In the body of the method invoke this.Layout.Render() to get the message text, then send the text to the destination media. \u26a0\ufe0f Don't forget to Register-your-custom-component when loading NLog config! See also the updated How to write a custom target for structured logging See also the updated How to write a custom async target Example This is a skeleton target that writes messages to the specified host: using NLog; using NLog.Config; using NLog.Targets; namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget: TargetWithLayout { public Layout Host { get; set; } = \"localhost\"; protected override void Write(LogEventInfo logEvent) { string logMessage = RenderLogEvent(this.Layout, logEvent); string hostName = RenderLogEvent(this.Host, logEvent); SendTheMessageToRemoteHost(hostName, logMessage); } private void SendTheMessageToRemoteHost(string hostName, string message) { // TODO - write me } } } How to pass configuration options to the target? In the example above then one can see how the Host -property is used. Having a public property that sets the required configuration parameters is enough for NLog to use it. Each attribute that you put in the definition gets passed to the appropriate public property. NLog takes care of the appropriate conversions necessary so that you can use integer, string, datetime, boolean parameters. Check also Properties-constraints-for-custom-extensions It is recommended to use NLog Layouts or NLog Layout for NLog Target Configuration options, as it will allow users to provide configuration-values from NLog LayoutRenderers (Ex. from appsettings.json , app.config or environment-variables) How to handle object lifetime When needing to create interfaces to external framework or start background-threads, then it is recommended to override InitializeTarget and close/release resources again in CloseTarget . namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget: TargetWithLayout { protected override void InitializeTarget() { base.InitializeTarget(); // TODO Custom Init Logic } protected override void CloseTarget() { // TODO Custom Close Logic base.CloseTarget(); } } } It is possible for the same target object to be initialized and closed many times during the lifetime of the application. It is recommended not to use the constructor to start background-threads or initialize interfaces, but merely focus on setting up initial state without starting anything. It is possible to override the Dispose-method, but this method will only be called at the end of application-lifetime. Multiple type-alias attributes NLog 5.0 enables you to have multiple type-aliases for a single class. Before one had to inherit from the same class to provide additional type-aliases. [Target(\"MyFirst\")] [Target(\"MyInitial\")] public sealed class MyFirstTarget: TargetWithLayout { The type-alias can then be used when wanting to use the target in the NLog Configuration File. Ex. Notice NLog 5.0 automatically ignores dashes - in type-aliases, so no extra alias is needed for this: Ex. ","title":"How to write a custom target"},{"location":"How-to-write-a-custom-target/#example","text":"This is a skeleton target that writes messages to the specified host: using NLog; using NLog.Config; using NLog.Targets; namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget: TargetWithLayout { public Layout Host { get; set; } = \"localhost\"; protected override void Write(LogEventInfo logEvent) { string logMessage = RenderLogEvent(this.Layout, logEvent); string hostName = RenderLogEvent(this.Host, logEvent); SendTheMessageToRemoteHost(hostName, logMessage); } private void SendTheMessageToRemoteHost(string hostName, string message) { // TODO - write me } } }","title":"Example"},{"location":"How-to-write-a-custom-target/#how-to-pass-configuration-options-to-the-target","text":"In the example above then one can see how the Host -property is used. Having a public property that sets the required configuration parameters is enough for NLog to use it. Each attribute that you put in the definition gets passed to the appropriate public property. NLog takes care of the appropriate conversions necessary so that you can use integer, string, datetime, boolean parameters. Check also Properties-constraints-for-custom-extensions It is recommended to use NLog Layouts or NLog Layout for NLog Target Configuration options, as it will allow users to provide configuration-values from NLog LayoutRenderers (Ex. from appsettings.json , app.config or environment-variables)","title":"How to pass configuration options to the target?"},{"location":"How-to-write-a-custom-target/#how-to-handle-object-lifetime","text":"When needing to create interfaces to external framework or start background-threads, then it is recommended to override InitializeTarget and close/release resources again in CloseTarget . namespace MyNamespace { [Target(\"MyFirst\")] public sealed class MyFirstTarget: TargetWithLayout { protected override void InitializeTarget() { base.InitializeTarget(); // TODO Custom Init Logic } protected override void CloseTarget() { // TODO Custom Close Logic base.CloseTarget(); } } } It is possible for the same target object to be initialized and closed many times during the lifetime of the application. It is recommended not to use the constructor to start background-threads or initialize interfaces, but merely focus on setting up initial state without starting anything. It is possible to override the Dispose-method, but this method will only be called at the end of application-lifetime.","title":"How to handle object lifetime"},{"location":"How-to-write-a-custom-target/#multiple-type-alias-attributes","text":"NLog 5.0 enables you to have multiple type-aliases for a single class. Before one had to inherit from the same class to provide additional type-aliases. [Target(\"MyFirst\")] [Target(\"MyInitial\")] public sealed class MyFirstTarget: TargetWithLayout { The type-alias can then be used when wanting to use the target in the NLog Configuration File. Ex. Notice NLog 5.0 automatically ignores dashes - in type-aliases, so no extra alias is needed for this: Ex. ","title":"Multiple type-alias attributes"},{"location":"IIS-site-name-Layout-Renderer/","text":"IIS site name - printing HostingEnvironment.SiteName Platforms Supported: All (Supported in AspNet and AspNetCore ) Configuration Syntax ${iis-site-name}","title":"IIS site name Layout Renderer"},{"location":"IIS-site-name-Layout-Renderer/#configuration-syntax","text":"${iis-site-name}","title":"Configuration Syntax"},{"location":"Identity-layout-renderer/","text":"Thread identity information (name and authentication information). Platforms Supported: All Configuration Syntax ${identity:authType=Boolean:separator=String:name=Boolean :isAuthenticated=Boolean} Parameters Rendering Options authType - Indicates whether to render Thread.CurrentPrincipal.Identity.AuthenticationType.Boolean Default: True separator - Separator to be used when concatenating parts of identity information. Default: : name - Indicates whether to render Thread.CurrentPrincipal.Identity.Name.Boolean Default: True isAuthenticated - Indicates whether to render Thread.CurrentPrincipal.Identity.IsAuthenticated.Boolean Default: True Notes ${environment-user} is an alternative that depends on Environment.UserName , which is compatible with both Windows/Linux (and less overhead). ${windows-identity} is an alternative that depends on WindowsIdentity.Getcurrent() ${aspnet-user-identity} is an alternative that only works on ASP.NET Applications with identity enabled. Note .NET Core 3 Set AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal) in the Main method of your application, otherwise this renderer could render empty unexpectedly. ( Read more )","title":"Identity layout renderer"},{"location":"Identity-layout-renderer/#configuration-syntax","text":"${identity:authType=Boolean:separator=String:name=Boolean :isAuthenticated=Boolean}","title":"Configuration Syntax"},{"location":"Identity-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Identity-layout-renderer/#rendering-options","text":"authType - Indicates whether to render Thread.CurrentPrincipal.Identity.AuthenticationType.Boolean Default: True separator - Separator to be used when concatenating parts of identity information. Default: : name - Indicates whether to render Thread.CurrentPrincipal.Identity.Name.Boolean Default: True isAuthenticated - Indicates whether to render Thread.CurrentPrincipal.Identity.IsAuthenticated.Boolean Default: True","title":"Rendering Options"},{"location":"Identity-layout-renderer/#notes","text":"${environment-user} is an alternative that depends on Environment.UserName , which is compatible with both Windows/Linux (and less overhead). ${windows-identity} is an alternative that depends on WindowsIdentity.Getcurrent() ${aspnet-user-identity} is an alternative that only works on ASP.NET Applications with identity enabled.","title":"Notes"},{"location":"Identity-layout-renderer/#note-net-core-3","text":"Set AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal) in the Main method of your application, otherwise this renderer could render empty unexpectedly. ( Read more )","title":"Note .NET Core 3"},{"location":"ImpersonatingWrapper-target/","text":"Impersonates another user for the duration of the write (Ex. give access-permission to file-target) Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsIdentity since NLog 5.0 Configuration Syntax Parameters General Options name - Name of the target. Impersonation Options userName - Username to change context to. NLog.WindowsIdentity v5.3 changed data-type from String to Layout password - User account password. NLog.WindowsIdentity v5.3 changed data-type from String to Layout domain - Windows domain name for user account. Default: . NLog.WindowsIdentity v5.3 changed data-type from String to Layout revertToSelf - Indicates whether to revert to the credentials of the process instead of impersonating another user. Boolean Default: False impersonationLevel - Required impersonation level. Possible values: Anonymous - Anonymous Level. Delegation - Delegation Level. Identification - Identification Level. Impersonation - Impersonation Level. logOnType - Logon Type. Possible values: Batch - Batch Logon. Interactive - Interactive Logon. Network - Network Logon. NetworkClearText - Network Clear Text Logon. NewCredentials - New Network Credentials. Service - Logon as a Service. logOnProvider - Type of the logon provider. Possible values: Default - Use the standard logon provider for the system.","title":"ImpersonatingWrapper target"},{"location":"ImpersonatingWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"ImpersonatingWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"ImpersonatingWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"ImpersonatingWrapper-target/#impersonation-options","text":"userName - Username to change context to. NLog.WindowsIdentity v5.3 changed data-type from String to Layout password - User account password. NLog.WindowsIdentity v5.3 changed data-type from String to Layout domain - Windows domain name for user account. Default: . NLog.WindowsIdentity v5.3 changed data-type from String to Layout revertToSelf - Indicates whether to revert to the credentials of the process instead of impersonating another user. Boolean Default: False impersonationLevel - Required impersonation level. Possible values: Anonymous - Anonymous Level. Delegation - Delegation Level. Identification - Identification Level. Impersonation - Impersonation Level. logOnType - Logon Type. Possible values: Batch - Batch Logon. Interactive - Interactive Logon. Network - Network Logon. NetworkClearText - Network Clear Text Logon. NewCredentials - New Network Credentials. Service - Logon as a Service. logOnProvider - Type of the logon provider. Possible values: Default - Use the standard logon provider for the system.","title":"Impersonation Options"},{"location":"InstallContext-layout-renderer/","text":"Installation Context Parameter Value. Platforms Supported: All Configuration Syntax ${install-context:parameter=String} See also Installing targets See also InstallNLogConfig Parameters Rendering Options parameter - Name of the parameter. Required","title":"InstallContext layout renderer"},{"location":"InstallContext-layout-renderer/#configuration-syntax","text":"${install-context:parameter=String} See also Installing targets See also InstallNLogConfig","title":"Configuration Syntax"},{"location":"InstallContext-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"InstallContext-layout-renderer/#rendering-options","text":"parameter - Name of the parameter. Required","title":"Rendering Options"},{"location":"Installing-targets/","text":"Some targets support installing. Current the following targets support installing Database target EventLogger target PerformanceCounter target Install Install all targets used in the config: LogManager.Configuration.Install(new InstallationContext()); Uninstall Uninstall all targets used in the config: LogManager.Configuration.Uninstall(new InstallationContext()); Example install database target CREATE TABLE ${var:logTableName} ( Id bigint primary key not null identity(1,1), Logged datetime2, Level nvarchar(10), LogMessage nvarchar(max), MessageUid uniqueidentifier, MessagePartUid uniqueidentifier, MessagePartDataUid uniqueidentifier, ) false Troubleshooting installation issues Installation log You can enable the installation log by overriding the default output stream in your InstallationContext . For example, to have the installation log printed out to console, you can use: LogManager.Configuration.Install(new InstallationContext(Console.Out)); You can also redirect the installation log to a string in memory: var stringWriter = new StringWriter(); LogManager.Configuration.Install(new InstallationContext(stringWriter)); var installationLog = stringWriter.ToString(); // retrieve the installation output Note that the log output can also be accessed via InstallationContext.LogOutput : // This is equivalent to the previous example var installationContext = new InstallationContext(new StringWriter()) LogManager.Configuration.Install(installationContext); var installationLog = installationContext.LogOutput.ToString(); A note on exceptions Except for application critical exceptions (OutOfMemoryException. StackOverflowException and ThreadAbortException), LogManager.Configuration.Install() will not rethrow any other exception, even when NLog is Logging-troubleshooting#troubleshooting-steps .","title":"Installing targets"},{"location":"Installing-targets/#install","text":"Install all targets used in the config: LogManager.Configuration.Install(new InstallationContext());","title":"Install"},{"location":"Installing-targets/#uninstall","text":"Uninstall all targets used in the config: LogManager.Configuration.Uninstall(new InstallationContext());","title":"Uninstall"},{"location":"Installing-targets/#example-install-database-target","text":" CREATE TABLE ${var:logTableName} ( Id bigint primary key not null identity(1,1), Logged datetime2, Level nvarchar(10), LogMessage nvarchar(max), MessageUid uniqueidentifier, MessagePartUid uniqueidentifier, MessagePartDataUid uniqueidentifier, ) false ","title":"Example install database target"},{"location":"Installing-targets/#troubleshooting-installation-issues","text":"","title":"Troubleshooting installation issues"},{"location":"Installing-targets/#installation-log","text":"You can enable the installation log by overriding the default output stream in your InstallationContext . For example, to have the installation log printed out to console, you can use: LogManager.Configuration.Install(new InstallationContext(Console.Out)); You can also redirect the installation log to a string in memory: var stringWriter = new StringWriter(); LogManager.Configuration.Install(new InstallationContext(stringWriter)); var installationLog = stringWriter.ToString(); // retrieve the installation output Note that the log output can also be accessed via InstallationContext.LogOutput : // This is equivalent to the previous example var installationContext = new InstallationContext(new StringWriter()) LogManager.Configuration.Install(installationContext); var installationLog = installationContext.LogOutput.ToString();","title":"Installation log"},{"location":"Installing-targets/#a-note-on-exceptions","text":"Except for application critical exceptions (OutOfMemoryException. StackOverflowException and ThreadAbortException), LogManager.Configuration.Install() will not rethrow any other exception, even when NLog is Logging-troubleshooting#troubleshooting-steps .","title":"A note on exceptions"},{"location":"Internal-Logging/","text":"When Troubleshooting NLog logging issues , then it is a good idea to enable internal logging, which often helps to identify where the problem is. Internal log output can be sent to a file, console window or both. Enabling internal logging using configuration file When you configure NLog using Configuration File , you can enable internal logging by setting the following attribute on the element: internalLogLevel=\"Off|Trace|Debug|Info|Warn|Error|Fatal\" \u2013 determines internal log level. The higher the level, the less verbose the internal log output. internalLogFile=\"file.txt\" - adding internalLogFile cause NLog to write its internal debugging messages to the specified file. This includes any exceptions that may be thrown during logging. Notice only basic layouts are supported, as the internal log needs to be as simple/stable as possible: - Environment Variables e.g. %APPDATA% or %HOME% or %PROGRAMDATA% (Introduced with NLog 4.6+). - ${currentdir} (Introduced with NLog 4.6+ but without options). - ${basedir} (Introduced with NLog 4.6+ but without options). - ${tempdir} (Introduced with NLog 4.6+ but without options). - ${processdir} (Introduced with NLog 4.7.1+ but without options). - ${commonApplicationDataDir} , ${userApplicationDataDir} , ${userLocalApplicationDataDir} (Introduced with NLog v5 but without options) * internalLogToConsole=\"false|true\" \u2013 sends internal logging messages to the console. * internalLogToConsoleError=\"false|true\" \u2013 sends internal logging messages to the console error output (stderr). * internalLogIncludeTimestamp=\"false|true\" - indicates whether timestamps should be included in the internal log output (NLog 4.3+) Here is an example of a configuration file which enables internal logging to a file: If not getting internal logger output, then make sure the NLog.config file has Build Action set to Copy if newer . See also Logging-troubleshooting . Alternative try to activate Internal Logging programmatically. Enabling internal logging programmatically Internal logging can be configured through code by setting the following properties on InternalLogger class: * NLog.Common.InternalLogger.LogLevel - specifies internal logging level * NLog.Common.InternalLogger.LogFile - specifies name of the log file (null will disable logging to a file) * NLog.Common.InternalLogger.LogToConsole - enables or disables logging to the console * NLog.Common.InternalLogger.LogToConsoleError - enables or disables logging to the console error stream * NLog.Common.InternalLogger.LogWriter - specifies a TextWriter object to use for logging. * NLog.Common.InternalLogger.IncludeTimestamp - enables or disables whether timestamps should be included in the internal log output Introduced with NLog 4.3 * NLog.Common.InternalLogger.InternalEventOccurred - event-callback for every internal logger event. Introduced with NLog 6.0 and replaces the now obsolete LogMessageReceived For best diagnostic output then make sure to enable NLog InternalLogger, before creating the first NLog Logger-object. Here is an example of activating internal logging from code: using NLog; class Program { static void Main() { // enable internal logging to the console NLog.Common.InternalLogger.LogToConsole = true; // enable internal logging to a file NLog.Common.InternalLogger.LogFile = \"c:\\\\nlog-internal.txt\"; // On Linux \"/home/nlog-internal.txt\" // enable internal logging to a custom TextWriter. Ex. TextWriter writer = File.CreateText(\"C:\\\\perl.txt\") NLog.Common.InternalLogger.LogWriter = new StringWriter(); // set internal log level NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Debug; // Perform test output, ensure first NLog Logger is created after InternalLogger is enabled. NLog.LogManager.GetLogger(\"Test\").Info(\"Hello World\"); } } Enabling internal logging using environment variables Before NLog 5.0 then environment variables and app.config settings would be automatically be applied on startup. But because of the startup overhead, then this has been disabled. Instead one now have to explicitly activate this behavior: NLog.LogFactory.Setup().SetupInternalLogger(b => b.SetupFromEnvironmentVariables()) These are environment variables which control internal logging: * NLOG_INTERNAL_LOG_LEVEL - sets the internal logging level. The available values are Trace, Debug, Info, Warn, Error or Fatal - the default is Info which should be appropriate for most cases, to get more detailed logging - set it to Debug or Trace. * NLOG_INTERNAL_LOG_FILE - if this variable is found in the environment NLog will save internal log to the specified file. The file must be writable by the current user or it will not be created. * NLOG_INTERNAL_LOG_TO_CONSOLE - if this variable is found in the environment, will outputs internal diagnostic information to the console * NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR - sets internalLogToConsoleError * NLOG_INTERNAL_INCLUDE_TIMESTAMP - sets internalLogIncludeTimestamp (introduced in NLog 4.3) Description of InternalLogger LogLevels LogLevel.Fatal - Just before application is going to crash. LogLevel.Error - Logging pipeline has failed, and logevents has been discarded. LogLevel.Warn - Detected invalid configuration but can recover. Detected connection lost but can recover. LogLevel.Info - Application lifetime events like logging configuration loaded, and shutting down logging engine. LogLevel.Debug - Reporting interesting events for detailed diagnostics. Having reflection issues when serializing logevents. LogLevel.Trace - Dumping verbose configuration details.","title":"Internal Logging"},{"location":"Internal-Logging/#enabling-internal-logging-using-configuration-file","text":"When you configure NLog using Configuration File , you can enable internal logging by setting the following attribute on the element: internalLogLevel=\"Off|Trace|Debug|Info|Warn|Error|Fatal\" \u2013 determines internal log level. The higher the level, the less verbose the internal log output. internalLogFile=\"file.txt\" - adding internalLogFile cause NLog to write its internal debugging messages to the specified file. This includes any exceptions that may be thrown during logging. Notice only basic layouts are supported, as the internal log needs to be as simple/stable as possible: - Environment Variables e.g. %APPDATA% or %HOME% or %PROGRAMDATA% (Introduced with NLog 4.6+). - ${currentdir} (Introduced with NLog 4.6+ but without options). - ${basedir} (Introduced with NLog 4.6+ but without options). - ${tempdir} (Introduced with NLog 4.6+ but without options). - ${processdir} (Introduced with NLog 4.7.1+ but without options). - ${commonApplicationDataDir} , ${userApplicationDataDir} , ${userLocalApplicationDataDir} (Introduced with NLog v5 but without options) * internalLogToConsole=\"false|true\" \u2013 sends internal logging messages to the console. * internalLogToConsoleError=\"false|true\" \u2013 sends internal logging messages to the console error output (stderr). * internalLogIncludeTimestamp=\"false|true\" - indicates whether timestamps should be included in the internal log output (NLog 4.3+) Here is an example of a configuration file which enables internal logging to a file: If not getting internal logger output, then make sure the NLog.config file has Build Action set to Copy if newer . See also Logging-troubleshooting . Alternative try to activate Internal Logging programmatically.","title":"Enabling internal logging using configuration file"},{"location":"Internal-Logging/#enabling-internal-logging-programmatically","text":"Internal logging can be configured through code by setting the following properties on InternalLogger class: * NLog.Common.InternalLogger.LogLevel - specifies internal logging level * NLog.Common.InternalLogger.LogFile - specifies name of the log file (null will disable logging to a file) * NLog.Common.InternalLogger.LogToConsole - enables or disables logging to the console * NLog.Common.InternalLogger.LogToConsoleError - enables or disables logging to the console error stream * NLog.Common.InternalLogger.LogWriter - specifies a TextWriter object to use for logging. * NLog.Common.InternalLogger.IncludeTimestamp - enables or disables whether timestamps should be included in the internal log output Introduced with NLog 4.3 * NLog.Common.InternalLogger.InternalEventOccurred - event-callback for every internal logger event. Introduced with NLog 6.0 and replaces the now obsolete LogMessageReceived For best diagnostic output then make sure to enable NLog InternalLogger, before creating the first NLog Logger-object. Here is an example of activating internal logging from code: using NLog; class Program { static void Main() { // enable internal logging to the console NLog.Common.InternalLogger.LogToConsole = true; // enable internal logging to a file NLog.Common.InternalLogger.LogFile = \"c:\\\\nlog-internal.txt\"; // On Linux \"/home/nlog-internal.txt\" // enable internal logging to a custom TextWriter. Ex. TextWriter writer = File.CreateText(\"C:\\\\perl.txt\") NLog.Common.InternalLogger.LogWriter = new StringWriter(); // set internal log level NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Debug; // Perform test output, ensure first NLog Logger is created after InternalLogger is enabled. NLog.LogManager.GetLogger(\"Test\").Info(\"Hello World\"); } }","title":"Enabling internal logging programmatically"},{"location":"Internal-Logging/#enabling-internal-logging-using-environment-variables","text":"Before NLog 5.0 then environment variables and app.config settings would be automatically be applied on startup. But because of the startup overhead, then this has been disabled. Instead one now have to explicitly activate this behavior: NLog.LogFactory.Setup().SetupInternalLogger(b => b.SetupFromEnvironmentVariables()) These are environment variables which control internal logging: * NLOG_INTERNAL_LOG_LEVEL - sets the internal logging level. The available values are Trace, Debug, Info, Warn, Error or Fatal - the default is Info which should be appropriate for most cases, to get more detailed logging - set it to Debug or Trace. * NLOG_INTERNAL_LOG_FILE - if this variable is found in the environment NLog will save internal log to the specified file. The file must be writable by the current user or it will not be created. * NLOG_INTERNAL_LOG_TO_CONSOLE - if this variable is found in the environment, will outputs internal diagnostic information to the console * NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR - sets internalLogToConsoleError * NLOG_INTERNAL_INCLUDE_TIMESTAMP - sets internalLogIncludeTimestamp (introduced in NLog 4.3)","title":"Enabling internal logging using environment variables"},{"location":"Internal-Logging/#description-of-internallogger-loglevels","text":"LogLevel.Fatal - Just before application is going to crash. LogLevel.Error - Logging pipeline has failed, and logevents has been discarded. LogLevel.Warn - Detected invalid configuration but can recover. Detected connection lost but can recover. LogLevel.Info - Application lifetime events like logging configuration loaded, and shutting down logging engine. LogLevel.Debug - Reporting interesting events for detailed diagnostics. Having reflection issues when serializing logevents. LogLevel.Trace - Dumping verbose configuration details.","title":"Description of InternalLogger LogLevels"},{"location":"JSON-Encode-Layout-Renderer/","text":"Escapes output of another layout using JSON rules. Platforms Supported: All Configuration Syntax ${json-encode:jsonEncode=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:jsonEncode=Boolean} Parameters Transformation Options jsonEncode - Indicates whether to apply JSON encoding. Boolean Default: True escapeUnicode - Indicates whether it should escape unicode characters (non-ascii) using \\u . Boolean Default: True Introduced in NLog 4.4.7 inner - Wrapped layout. Layout EscapeForwardSlash - Should forward slashes be escaped? If true, / will be converted to \\/ . Default true Introduced in NLog 4.6.8 Example ${event-properties:item=MyValue:jsonEncode=true}","title":"JSON Encode Layout Renderer"},{"location":"JSON-Encode-Layout-Renderer/#configuration-syntax","text":"${json-encode:jsonEncode=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:jsonEncode=Boolean}","title":"Configuration Syntax"},{"location":"JSON-Encode-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"JSON-Encode-Layout-Renderer/#transformation-options","text":"jsonEncode - Indicates whether to apply JSON encoding. Boolean Default: True escapeUnicode - Indicates whether it should escape unicode characters (non-ascii) using \\u . Boolean Default: True Introduced in NLog 4.4.7 inner - Wrapped layout. Layout EscapeForwardSlash - Should forward slashes be escaped? If true, / will be converted to \\/ . Default true Introduced in NLog 4.6.8","title":"Transformation Options"},{"location":"JSON-Encode-Layout-Renderer/#example","text":"${event-properties:item=MyValue:jsonEncode=true}","title":"Example"},{"location":"JsonArrayLayout/","text":"A specialized layout that renders to JSON-Array. See also JsonLayout Platforms Supported: All Introduced with NLog 5.0 Example output: [ \"2010-01-01T12:34:56Z\", \"Info\", \"hello world\" ] Parameters Items type - Required. The type of Layout (Ex. SimpleLayout , JsonLayout , etc.) suppressSpaces - Enable to suppress extra spaces in the output JSON. Default: false . renderEmptyObject - When no array-items, then it should still render empty array-value [] . Default: true .","title":"JsonArrayLayout"},{"location":"JsonArrayLayout/#parameters","text":"Items type - Required. The type of Layout (Ex. SimpleLayout , JsonLayout , etc.) suppressSpaces - Enable to suppress extra spaces in the output JSON. Default: false . renderEmptyObject - When no array-items, then it should still render empty array-value [] . Default: true .","title":"Parameters"},{"location":"JsonLayout/","text":"A specialized layout that renders to JSON. Platforms Supported: All Introduced with NLog 4.0 Example output: { \"time\": \"2010-01-01 12:34:56.0000\", \"level\": \"ERROR\", \"message\": \"hello, world\" } Added in NLog 4.1 Optional encode parameter. You can disable JSON encoding by setting encode=\"false\" . This will let you to write any string without JSON encoding. Including custom JSON (Ex. boolean/numeric values) Parameters Attribute name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout) encode - Enable or disable JSON encoding for the attribute. Default = true > Introduced in NLog 4.1 escapeUnicode - Escape unicode-characters (non-ascii) using \\u . Default = true > Introduced in NLog 4.4.7 IncludeEmptyValue - Include attribute when Layout output is empty. Default = false > Introduced in NLog 4.5 EscapeForwardSlash - Should forward slashes also be escaped. Default = false , > Introduced in NLog 4.6.8. Before NLog 5.0 the default was true. After NLog 6.0 it has no effect. suppressSpaces - Enable to suppress extra spaces in the output JSON. Default = true . Introduced in NLog 4.1. Before NLog 6.0 the default was false indentJson - Enables indent for JSON pretty format with newlines. Default = false . Introduced in NLog v5.1.4 renderEmptyObject - When no json-attributes, then it should still render empty object-value {} . Default = true . Introduced in NLog 4.3.7 IncludeGdc - Indicates whether to include contents of the GDC-Layout-Renderer (GDC) dictionary. Default = false . Introduced in NLog 4.4.10 IncludeEventProperties - Include LogEvent Properties dictionary? Default = false . Before NLog 5.0 option was named IncludeAllProperties IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default = false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc excludeProperties - comma separated string with names which properties to exclude. Only used when includeEventProperties is true . Case insensitive. Default empty When a name contains a comma, single quote the value. E.g. 'value,withquote',value2 . Introduced in NLog 4.4 excludeEmptyProperties - Exclude event properties with value null or empty (Also checks GDC, MDC, MDLC). Introduced in NLog 4.7.7 EscapeUnicode - escape non-ascii characters? Boolean. Default true . Introduced in NLog 4.4.7 MaxRecursionLimit - How far should the JSON serializer follow object references before backing off. Integer. Default 1 (0 = No object reflection) Introduced in NLog 4.5. Before NLog 5.0 the default was 0 (No object reflection) EscapeForwardSlash - Should forward slashes be escaped? If true, / will be converted to \\/ . Default = false . Introduced in NLog 4.6.8. Before NLog 5.0 the default was true DottedRecursion - Flatten object-property-names when using IncludeEventProperties for compact Json-documents. Default = false . Introduced in NLog 6.1 Advanced examples From the API: var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute(\"time\", \"${longdate}\"), new JsonAttribute(\"level\", \"${level}\"), new JsonAttribute(\"message\", \"${message}\"), new JsonAttribute(\"properties\", new JsonLayout { IncludeEventProperties = true, MaxRecursionLimit = 2 }, encode: false), new JsonAttribute(\"exception\", new JsonLayout { Attributes = { new JsonAttribute(\"type\", \"${exception:format=type}\"), new JsonAttribute(\"message\", \"${exception:format=message}\"), new JsonAttribute(\"stacktrace\", \"${exception:format=tostring}\"), } }, encode: false) // don't escape layout } }; From XML will render: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"Info\", \"message\": \"this is message\", \"properties\": { \"myProperty\": \"myValue\" }, \"exception\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } } pretty printed: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"Info\", \"message\": \"this is message\", \"properties\": { \"myProperty\": \"myValue\" }, \"exception\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } }","title":"JsonLayout"},{"location":"JsonLayout/#parameters","text":"Attribute name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout) encode - Enable or disable JSON encoding for the attribute. Default = true > Introduced in NLog 4.1 escapeUnicode - Escape unicode-characters (non-ascii) using \\u . Default = true > Introduced in NLog 4.4.7 IncludeEmptyValue - Include attribute when Layout output is empty. Default = false > Introduced in NLog 4.5 EscapeForwardSlash - Should forward slashes also be escaped. Default = false , > Introduced in NLog 4.6.8. Before NLog 5.0 the default was true. After NLog 6.0 it has no effect. suppressSpaces - Enable to suppress extra spaces in the output JSON. Default = true . Introduced in NLog 4.1. Before NLog 6.0 the default was false indentJson - Enables indent for JSON pretty format with newlines. Default = false . Introduced in NLog v5.1.4 renderEmptyObject - When no json-attributes, then it should still render empty object-value {} . Default = true . Introduced in NLog 4.3.7 IncludeGdc - Indicates whether to include contents of the GDC-Layout-Renderer (GDC) dictionary. Default = false . Introduced in NLog 4.4.10 IncludeEventProperties - Include LogEvent Properties dictionary? Default = false . Before NLog 5.0 option was named IncludeAllProperties IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default = false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc excludeProperties - comma separated string with names which properties to exclude. Only used when includeEventProperties is true . Case insensitive. Default empty When a name contains a comma, single quote the value. E.g. 'value,withquote',value2 . Introduced in NLog 4.4 excludeEmptyProperties - Exclude event properties with value null or empty (Also checks GDC, MDC, MDLC). Introduced in NLog 4.7.7 EscapeUnicode - escape non-ascii characters? Boolean. Default true . Introduced in NLog 4.4.7 MaxRecursionLimit - How far should the JSON serializer follow object references before backing off. Integer. Default 1 (0 = No object reflection) Introduced in NLog 4.5. Before NLog 5.0 the default was 0 (No object reflection) EscapeForwardSlash - Should forward slashes be escaped? If true, / will be converted to \\/ . Default = false . Introduced in NLog 4.6.8. Before NLog 5.0 the default was true DottedRecursion - Flatten object-property-names when using IncludeEventProperties for compact Json-documents. Default = false . Introduced in NLog 6.1","title":"Parameters"},{"location":"JsonLayout/#advanced-examples","text":"","title":"Advanced examples"},{"location":"JsonLayout/#from-the-api","text":"var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute(\"time\", \"${longdate}\"), new JsonAttribute(\"level\", \"${level}\"), new JsonAttribute(\"message\", \"${message}\"), new JsonAttribute(\"properties\", new JsonLayout { IncludeEventProperties = true, MaxRecursionLimit = 2 }, encode: false), new JsonAttribute(\"exception\", new JsonLayout { Attributes = { new JsonAttribute(\"type\", \"${exception:format=type}\"), new JsonAttribute(\"message\", \"${exception:format=message}\"), new JsonAttribute(\"stacktrace\", \"${exception:format=tostring}\"), } }, encode: false) // don't escape layout } };","title":"From the API:"},{"location":"JsonLayout/#from-xml","text":" will render: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"Info\", \"message\": \"this is message\", \"properties\": { \"myProperty\": \"myValue\" }, \"exception\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } } pretty printed: { \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"Info\", \"message\": \"this is message\", \"properties\": { \"myProperty\": \"myValue\" }, \"exception\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } }","title":"From XML"},{"location":"Layout-Renderers/","text":"Layout renderers are template macros that are used in Layouts , e.g. ${message} , ${level} etc Layout Renderers List of available layout renderers can be found here: https://nlog-project.org/config/?tab=layout-renderers NLog can also be extended with new custom layout renderers. See also: Extending NLog 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} Passing Custom Values to a Layout Even though the layout renderers provide many pre-defined values, you may need to pass application specific values to your Layouts . You can provide own Context state, that can then be rendered by different Layouts. For example by using LogEvent Properties, that can be rendered using using the ${event-properties} renderer.","title":"Layout Renderers"},{"location":"Layout-Renderers/#layout-renderers","text":"List of available layout renderers can be found here: https://nlog-project.org/config/?tab=layout-renderers NLog can also be extended with new custom layout renderers. See also: Extending NLog 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}","title":"Layout Renderers"},{"location":"Layout-Renderers/#passing-custom-values-to-a-layout","text":"Even though the layout renderers provide many pre-defined values, you may need to pass application specific values to your Layouts . You can provide own Context state, that can then be rendered by different Layouts. For example by using LogEvent Properties, that can be rendered using using the ${event-properties} renderer.","title":"Passing Custom Values to a Layout"},{"location":"Layout/","text":"See Layouts","title":"Layout"},{"location":"LayoutWithHeaderAndFooter/","text":"A specialized layout that supports header and footer. Platforms Supported: All Configuration Syntax Layout
Layout
Layout
Parameters Layout Options layout - Body layout (can be repeated multiple times). Layout header - Header layout. Layout footer - Footer layout. Layout","title":"LayoutWithHeaderAndFooter"},{"location":"LayoutWithHeaderAndFooter/#configuration-syntax","text":" Layout
Layout
Layout
","title":"Configuration Syntax"},{"location":"LayoutWithHeaderAndFooter/#parameters","text":"","title":"Parameters"},{"location":"LayoutWithHeaderAndFooter/#layout-options","text":"layout - Body layout (can be repeated multiple times). Layout header - Header layout. Layout footer - Footer layout. Layout","title":"Layout Options"},{"location":"Layouts/","text":"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 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 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 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: ","title":"Layouts"},{"location":"Layouts/#target-configuration-with-layout","text":"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\", } }","title":"Target Configuration with Layout"},{"location":"Layouts/#typed-layout","text":"NLog 5.0 introduces Layout 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 then one can do this: int eventId = EventIdLayout.RenderValue(logEvent, defaultValue: 42);","title":"Typed Layout"},{"location":"Layouts/#example","text":"An example of a simple layout looks like: layout=\"${machinename} ${message}\" This layout is used in the NLog.config file like: ","title":"Example"},{"location":"Left-layout-renderer/","text":"Left part of a text. Platforms Supported: All Introduced in NLog 4.6 Related: ${substring} ${right} Configuration Syntax Explicit usage: ${left:inner=Layout:length=Integer} Ambient property truncate can be used as a shortcut (Introduced with NLog ver. 4.6.3) ${message:truncate=80} Read more about using the Configuration File . Parameters Transformation Options inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout length - Length in characters. Integer Required.","title":"Left layout renderer"},{"location":"Left-layout-renderer/#configuration-syntax","text":"Explicit usage: ${left:inner=Layout:length=Integer} Ambient property truncate can be used as a shortcut (Introduced with NLog ver. 4.6.3) ${message:truncate=80} Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Left-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Left-layout-renderer/#transformation-options","text":"inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout length - Length in characters. Integer Required.","title":"Transformation Options"},{"location":"Level-layout-renderer/","text":"The log level . Platforms Supported: All Configuration Syntax ${level:format=Ordinal} Alternatively, add padding to align the message. ${pad:padding=5:inner=${level:uppercase=true}} Alternatively, truncate to align the message: ${level:format=TriLetter:uppercase=true} Parameters uppercase - Output level in upper-case. Default: false Introduced with NLog v5.0 to simplify default Layout, instead of using the ambient uppercase -property format - Output format of the level. Introduced in 4.4.6 Default: Name Possible values: Name - Render the standard level name. > Introduced in NLog 4.4.6 FullName - Render the full level name (Expands \"Info\" and \"Warn\") > Introduced in NLog 4.7 FirstCharacter - Render the first character of the level. > Introduced in NLog 4.4.6 Ordinal - Render the ordinal (aka number) for the level. > Introduced in NLog 4.4.6 TriLetter - Renders LogLevel as 3 letter abbreviations (Trc, Dbg, Inf, Wrn, Err, Ftl) > Introduced in NLog 5.0.5 Name FullName TriLetter FirstCharacter Ordinal Trace Trace Trc T 0 Debug Debug Dbg D 1 Info Information Inf I 2 Warn Warning Wrn W 3 Error Error Err E 4 Fatal Fatal Ftl F 5 Off Off Off O 6 Examples Basic Configuration: ${level} Code: logger.Debug(\"Test Message\") Result: Debug Format Configuration: ${level:format=FirstCharacter} Code: logger.Debug(\"Test Message\") Result: D","title":"Level layout renderer"},{"location":"Level-layout-renderer/#configuration-syntax","text":"${level:format=Ordinal} Alternatively, add padding to align the message. ${pad:padding=5:inner=${level:uppercase=true}} Alternatively, truncate to align the message: ${level:format=TriLetter:uppercase=true}","title":"Configuration Syntax"},{"location":"Level-layout-renderer/#parameters","text":"uppercase - Output level in upper-case. Default: false Introduced with NLog v5.0 to simplify default Layout, instead of using the ambient uppercase -property format - Output format of the level. Introduced in 4.4.6 Default: Name Possible values: Name - Render the standard level name. > Introduced in NLog 4.4.6 FullName - Render the full level name (Expands \"Info\" and \"Warn\") > Introduced in NLog 4.7 FirstCharacter - Render the first character of the level. > Introduced in NLog 4.4.6 Ordinal - Render the ordinal (aka number) for the level. > Introduced in NLog 4.4.6 TriLetter - Renders LogLevel as 3 letter abbreviations (Trc, Dbg, Inf, Wrn, Err, Ftl) > Introduced in NLog 5.0.5 Name FullName TriLetter FirstCharacter Ordinal Trace Trace Trc T 0 Debug Debug Dbg D 1 Info Information Inf I 2 Warn Warning Wrn W 3 Error Error Err E 4 Fatal Fatal Ftl F 5 Off Off Off O 6","title":"Parameters"},{"location":"Level-layout-renderer/#examples","text":"","title":"Examples"},{"location":"Level-layout-renderer/#basic","text":"Configuration: ${level} Code: logger.Debug(\"Test Message\") Result: Debug","title":"Basic"},{"location":"Level-layout-renderer/#format","text":"Configuration: ${level:format=FirstCharacter} Code: logger.Debug(\"Test Message\") Result: D","title":"Format"},{"location":"LimitingWrapper-target/","text":"Limits the number of logs written to the wrapped target in a given time interval. Platforms Supported: All Introduced in NLog 4.4. Configuration Syntax Parameters General Options name - Name of the target. Limiting Options messageLimit - Indicates the maximum number of log events written per Interval. Log events in the current interval received after the message limit has been reached will be discarded. Integer Default: 1000 interval - Indicates a time interval in which messages will be written up to the maximum number of messages ( messageLimit ). TimeSpan Default: \"01:00\" (1 hour)","title":"LimitingWrapper target"},{"location":"LimitingWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"LimitingWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"LimitingWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"LimitingWrapper-target/#limiting-options","text":"messageLimit - Indicates the maximum number of log events written per Interval. Log events in the current interval received after the message limit has been reached will be discarded. Integer Default: 1000 interval - Indicates a time interval in which messages will be written up to the maximum number of messages ( messageLimit ). TimeSpan Default: \"01:00\" (1 hour)","title":"Limiting Options"},{"location":"Literal-Layout-Renderer/","text":"A string literal. Platforms Supported: All Configuration Syntax ${literal:text=String} Parameters Rendering Options text - Literal text. Remarks This is used to escape '${' sequence as ;${literal:text=${}' . Examples Basic Configuration: ${literal:text=Some Text with ${ in it} Code: logger.Debug(\"Test Message\") Result: Some Text with ${ in it","title":"Literal Layout Renderer"},{"location":"Literal-Layout-Renderer/#configuration-syntax","text":"${literal:text=String}","title":"Configuration Syntax"},{"location":"Literal-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Literal-Layout-Renderer/#rendering-options","text":"text - Literal text.","title":"Rendering Options"},{"location":"Literal-Layout-Renderer/#remarks","text":"This is used to escape '${' sequence as ;${literal:text=${}' .","title":"Remarks"},{"location":"Literal-Layout-Renderer/#examples","text":"","title":"Examples"},{"location":"Literal-Layout-Renderer/#basic","text":"Configuration: ${literal:text=Some Text with ${ in it} Code: logger.Debug(\"Test Message\") Result: Some Text with ${ in it","title":"Basic"},{"location":"Local-IP-Address-Layout-Renderer/","text":"The local IP address whether IPv4 or IPv6 from NetworkInterface.GetAllNetworkInterfaces Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6 Introduced with NLog 4.6.8 Configuration Syntax ${local-ip:addressFamily=InterNetwork} Parameters AddressFamily - Explicitly prioritize IP addresses from a certain AddressFamily (Ex. InterNetwork / InterNetworkV6) Improving Performance The lookup of the active IP-address on the local machine has a performance hit. For better performance then it is recommended to use it with cachedSeconds like this: ${local-ip:cachedSeconds=60}","title":"Local IP Address Layout Renderer"},{"location":"Local-IP-Address-Layout-Renderer/#configuration-syntax","text":"${local-ip:addressFamily=InterNetwork}","title":"Configuration Syntax"},{"location":"Local-IP-Address-Layout-Renderer/#parameters","text":"AddressFamily - Explicitly prioritize IP addresses from a certain AddressFamily (Ex. InterNetwork / InterNetworkV6)","title":"Parameters"},{"location":"Local-IP-Address-Layout-Renderer/#improving-performance","text":"The lookup of the active IP-address on the local machine has a performance hit. For better performance then it is recommended to use it with cachedSeconds like this: ${local-ip:cachedSeconds=60}","title":"Improving Performance"},{"location":"Log-levels/","text":"See Configuration-file","title":"Log levels"},{"location":"Log4JXMLEvent-Layout-Renderer/","text":"XML event description compatible with log4j, Chainsaw and NLogViewer. Platforms Supported: All (Since NLog v6 then it has been replaced by Log4JXmlEventLayout ) Notice that Log4JXml-target works as a combined solution for sending Log4j-XML events over TCP / UDP / HTTP. Configuration Syntax ${log4jxmlevent:includeEventProperties=Boolean:includeSourceInfo=Boolean:includeCallSite=Boolean :includeNdc=Boolean:ndcItemSeparator=String:appInfo=String:indentXml=Boolean} Parameters Payload Options appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 4.5 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean IncludeEventProperties - Include all events properties of a logevent? Default: true . Before NLog 5.0 option was named IncludeAllProperties with Default: false IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: WriteThrowableCData - Write Exception as CDATA in log4j:throwable xml-element (Not supported by all viewers). Default: false Introduced in NLog 5.0 indentXml - Indicates whether to enable XmlWriterSettings.Indent for XML indentation. Default: false . includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: false . Before NLog 5.0 option had Default: true .","title":"Log4JXMLEvent Layout Renderer"},{"location":"Log4JXMLEvent-Layout-Renderer/#configuration-syntax","text":"${log4jxmlevent:includeEventProperties=Boolean:includeSourceInfo=Boolean:includeCallSite=Boolean :includeNdc=Boolean:ndcItemSeparator=String:appInfo=String:indentXml=Boolean}","title":"Configuration Syntax"},{"location":"Log4JXMLEvent-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Log4JXMLEvent-Layout-Renderer/#payload-options","text":"appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 4.5 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean IncludeEventProperties - Include all events properties of a logevent? Default: true . Before NLog 5.0 option was named IncludeAllProperties with Default: false IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: WriteThrowableCData - Write Exception as CDATA in log4j:throwable xml-element (Not supported by all viewers). Default: false Introduced in NLog 5.0 indentXml - Indicates whether to enable XmlWriterSettings.Indent for XML indentation. Default: false . includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: false . Before NLog 5.0 option had Default: true .","title":"Payload Options"},{"location":"Log4JXml-Target/","text":"Sends log messages to the remote instance of Log4J XML Viewer applications (Like Chainsaw). Platforms Supported: All - Requires nuget-package NLog.Targets.Network Introduced with NLog 6.0 where Chainsaw-Target and NLogViewer-Target was merged together into this. This target inherits from the Network Target , and so it has also all the properties of the Network Target available. Using the Log4JXmlEventLayout to produce Log4J XML output. Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default) Connection Options connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb For SOAP-based webservice support over HTTP use WebService target. keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: Discard - Discard new messages when reaching limit (Default) Grow - Send message and ignore limit Block - Block until pending connections has beeen freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6 Payload Options IncludeEventProperties - Include all events properties of a logevent? Default: true . IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . ScopeNestedSeparator - NDC item separator. Default: includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} formattedMessage - Message field. By default it's the output of ${message} parameter - Additional context properties that should be included. name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required. Example Available Log4J-XML viewers (See also LogViewer Tools ) - Sentinel - Avoid using TCP since not complete. - Log2Console - Logazmic - Loginator - Logbert - LogViewer - Lilith - OtrosLogViewer Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this: ","title":"Log4JXml Target"},{"location":"Log4JXml-Target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Log4JXml-Target/#parameters","text":"","title":"Parameters"},{"location":"Log4JXml-Target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Log4JXml-Target/#layout-options","text":"layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default)","title":"Layout Options"},{"location":"Log4JXml-Target/#connection-options","text":"connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb For SOAP-based webservice support over HTTP use WebService target. keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: Discard - Discard new messages when reaching limit (Default) Grow - Send message and ignore limit Block - Block until pending connections has beeen freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6","title":"Connection Options"},{"location":"Log4JXml-Target/#payload-options","text":"IncludeEventProperties - Include all events properties of a logevent? Default: true . IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Boolean includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Boolean IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . ScopeNestedSeparator - NDC item separator. Default: includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} formattedMessage - Message field. By default it's the output of ${message} parameter - Additional context properties that should be included. name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required.","title":"Payload Options"},{"location":"Log4JXml-Target/#example","text":" Available Log4J-XML viewers (See also LogViewer Tools ) - Sentinel - Avoid using TCP since not complete. - Log2Console - Logazmic - Loginator - Logbert - LogViewer - Lilith - OtrosLogViewer Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this: ","title":"Example"},{"location":"Log4JXmlEventLayout/","text":"A specialized layout that renders Log4j-compatible XML events. Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6 Notice that Log4JXml-target works as a combined solution for sending Log4j-XML events over TCP / UDP / HTTP. Configuration Syntax Parameters appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. Introduced in NLog 5.0 loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 5.0 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 IncludeEventProperties - Include all events properties of a logevent as log4j:data ? Default: true . Before NLog 5.0 option was named IncludeAllProperties with Default: false IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer as log4j:data . Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: includeSourceInfo - Indicates whether to include source info (file name and line number). Default: false . Introduced in NLog 4.6.5 includeCallSite - Indicates whether to include call site (class and method name). Default: false . Introduced in NLog 4.6.5 includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: false . Before NLog 5.0 option had Default: true . WriteThrowableCData - Write Exception as CDATA in log4j:throwable xml-element (Not supported by all viewers). Default: false . Introduced in NLog 5.0 parameter - Additional context properties that should be included as log4j:data Introduced in NLog 4.6.4 name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required.","title":"Log4JXmlEventLayout"},{"location":"Log4JXmlEventLayout/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"Log4JXmlEventLayout/#parameters","text":"appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. Introduced in NLog 5.0 loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 5.0 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 IncludeEventProperties - Include all events properties of a logevent as log4j:data ? Default: true . Before NLog 5.0 option was named IncludeAllProperties with Default: false IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer as log4j:data . Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: includeSourceInfo - Indicates whether to include source info (file name and line number). Default: false . Introduced in NLog 4.6.5 includeCallSite - Indicates whether to include call site (class and method name). Default: false . Introduced in NLog 4.6.5 includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: false . Before NLog 5.0 option had Default: true . WriteThrowableCData - Write Exception as CDATA in log4j:throwable xml-element (Not supported by all viewers). Default: false . Introduced in NLog 5.0 parameter - Additional context properties that should be included as log4j:data Introduced in NLog 4.6.4 name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required.","title":"Parameters"},{"location":"LogEvent-Context-Information/","text":"Moved to https://github.com/NLog/NLog/wiki/Context","title":"LogEvent Context Information"},{"location":"LogReceiverService-target/","text":"Sends log messages to a NLog Receiver Service (using WCF or Web Services). Platforms Supported: All - Requires nuget-package NLog.Wcf since NLog 5.0 Configuration Syntax Read more about using the Configuration File . Note it is recommended to also apply BufferingWrapper-target with a FlushTimeout of 200ms (or higher), as LogReceiverService-target will by default create/open new connection for each batch of LogEvents. Parameters General Options name - Name of the target. Connection Options endpointAddress - Endpoint address. Required. endpointConfigurationName - Name of the endpoint configuration in WCF configuration file Only supported on .NET Framework platform with app.config . Trying to enable on .NET Core fails with: System.PlatformNotSupportedException: Configuration files are not supported. Payload Options useBinaryEncoding - Indicates whether to use binary message encoding. Boolean parameters - The list of parameters. Collection Each collection item is represented by \\ element with the following attributes: layout - Layout that should be use to calculate the value for the parameter. Layout Required. name - Name of the parameter. type - Type of the parameter.System.Type clientId - Application Client Identifier, translates into NLogEvents.ClientName Layout includeEventProperties - Indicates whether to include per-event properties in the payload sent to the server. Boolean Examples Passing Parameters Parameters are passed to the WCF LogReceiverService target using one or more configuration lines such as: These parameters are passed over the network to the service and can be accessed by emitting events from your receiver application. Application for receiving events namespace MyLogReceiverApp { using System; using NLog; using NLog.LogReceiverService; /// /// Log service server object that logs messages. /// public class LogReceiverServer : ILogReceiverServer { public void ProcessLogMessages(NLogEvents nevents) { var events = nevents.ToEventInfo(\"Client.\"); Console.WriteLine(\"in: {0} {1}\", nevents.Events.Length, events.Count); foreach (var ev in events) { var logger = LogManager.GetLogger(ev.LoggerName); logger.Log(ev); } } } }","title":"LogReceiverService target"},{"location":"LogReceiverService-target/#configuration-syntax","text":" Read more about using the Configuration File . Note it is recommended to also apply BufferingWrapper-target with a FlushTimeout of 200ms (or higher), as LogReceiverService-target will by default create/open new connection for each batch of LogEvents.","title":"Configuration Syntax"},{"location":"LogReceiverService-target/#parameters","text":"","title":"Parameters"},{"location":"LogReceiverService-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"LogReceiverService-target/#connection-options","text":"endpointAddress - Endpoint address. Required. endpointConfigurationName - Name of the endpoint configuration in WCF configuration file Only supported on .NET Framework platform with app.config . Trying to enable on .NET Core fails with: System.PlatformNotSupportedException: Configuration files are not supported.","title":"Connection Options"},{"location":"LogReceiverService-target/#payload-options","text":"useBinaryEncoding - Indicates whether to use binary message encoding. Boolean parameters - The list of parameters. Collection Each collection item is represented by \\ element with the following attributes: layout - Layout that should be use to calculate the value for the parameter. Layout Required. name - Name of the parameter. type - Type of the parameter.System.Type clientId - Application Client Identifier, translates into NLogEvents.ClientName Layout includeEventProperties - Indicates whether to include per-event properties in the payload sent to the server. Boolean","title":"Payload Options"},{"location":"LogReceiverService-target/#examples","text":"","title":"Examples"},{"location":"LogReceiverService-target/#passing-parameters","text":"Parameters are passed to the WCF LogReceiverService target using one or more configuration lines such as: These parameters are passed over the network to the service and can be accessed by emitting events from your receiver application.","title":"Passing Parameters"},{"location":"LogReceiverService-target/#application-for-receiving-events","text":"namespace MyLogReceiverApp { using System; using NLog; using NLog.LogReceiverService; /// /// Log service server object that logs messages. /// public class LogReceiverServer : ILogReceiverServer { public void ProcessLogMessages(NLogEvents nevents) { var events = nevents.ToEventInfo(\"Client.\"); Console.WriteLine(\"in: {0} {1}\", nevents.Events.Length, events.Count); foreach (var ev in events) { var logger = LogManager.GetLogger(ev.LoggerName); logger.Log(ev); } } } }","title":"Application for receiving events"},{"location":"Logger-Layout-Renderer/","text":"Renders name of the Logger that produced the LogEvent. The Logger name is assigned when it is created using NLog.LogManager.GetLogger(\"myLoggerName\") or NLog.LogManger.GetCurrentClassLogger() (capture class-type-name as Logger-name) The Logger-name is often used to describe the source-location where the LogEvent was produced. The NLog Logging-Rules are optimized for doing filtering / redirection of LogEvents based on the Logger-name. It is not recommended to generate Logger-name from Guid or Timestamp, as it can lead to memory-leak with huge Logger-cache. Platforms Supported: All Configuration Syntax ${logger:shortName=Boolean} Parameters Rendering Options shortName - Indicates whether to render short logger name (the part after the last trailing dot character). Boolean Default: False prefixName - Indicates whether to render prefix-part of logger name (the part before the last trailing dot character). Boolean Default: False Introduced with NLog v5.3","title":"Logger Layout Renderer"},{"location":"Logger-Layout-Renderer/#configuration-syntax","text":"${logger:shortName=Boolean}","title":"Configuration Syntax"},{"location":"Logger-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Logger-Layout-Renderer/#rendering-options","text":"shortName - Indicates whether to render short logger name (the part after the last trailing dot character). Boolean Default: False prefixName - Indicates whether to render prefix-part of logger name (the part before the last trailing dot character). Boolean Default: False Introduced with NLog v5.3","title":"Rendering Options"},{"location":"Logging-Rules-FinalMinLevel/","text":"finalMinLevel is an option for Logging Rules , that have been introduced with NLog ver 5.0. It is conceptually similar to the combination of the maxLevel and final option. The main reason for the finalMinLevel option is to easily silence all noisy loggers from one subcomponent (like Microsoft.* ), while overriding this behavior for a single logger of that subcomponent (like Microsoft.Hosting.Lifetime ). This is similar to how the filtering works in Microsoft Extension Logging. finalMinLevel is intended for configurations that have catch-all log-targets at the bottom of the logging rules. Here's a small example to start with: if logs coming from Microsoft.* should only be logged if the log level is Warn or higher, and all other logs should be logged if the level is Info or higher, then the following configuration could be used: This can also be implemented using maxLevel and final in NLog v4: In both examples, the first rule is a \"black hole\" that swallows the applicable logs. Also keep in mind that the order of the logger-rules are always very important. The advantage of finalMinLevel is that it is easier to read, comprehend and reduces the configuration required, especially with more complex configurations. Additionally, it allows overriding previous finalMinLevel filters, such a pattern is not possible otherwise. Levels The following table describes which log levels are enabled depending on the finalMinLevel value: FinalMinLevel Ordinal Enabled log levels Trace 0 Trace, Debug, Info, Warn, Error and Fatal Debug 1 Debug, Info, Warn, Error and Fatal Info 2 Info, Warn, Error and Fatal Warn 3 Warn, Error and Fatal Error 4 Error and Fatal Fatal 5 Fatal Off 6 NLog includes LogLevel Off , that can be used to suppress all output from a noisy logger: This can also be implemented using maxLevel and final in NLog v4: Overrides As mentioned before, finalMinLevel can override previous rules. For example, if we want Warn logs of higher from Microsoft.* , but Info logs or higher from Microsoft.Hosting.Lifetime , then this is a possible configuration: Keep in mind that the order is still important. If the \"Microsoft.* and Microsoft.Hosting.Lifetime* were reversed, then Microsoft.* would override Microsoft.Hosting.Lifetime* and both would be set to Warn . Microsoft Extensions Logging Filters The Microsoft Logging filters specified in appsettings.json are ignored by default when using NLog 5.0. This is to avoid that new users think NLog Logging Rules are not working, because Microsoft LoggerFactory filters are interfering. The default logging logging configuration in appsettings.json : { \"Logging\": { \"LogLevel\": { \"Default\": \"Information\", \"Microsoft\": \"Warning\", \"Microsoft.Hosting.Lifetime\": \"Information\" } } } Can be configured through NLog.config like this: Notice that the logger named Microsoft.Hosting.Lifetime* overrides the Microsoft.* logger. See also Microsoft Hosting Lifetime Startup Messages See also Tutorial for using NLog with ASP.NET Core Complete example This example also filters logs from System.* and separates informative logs and error logs between the stdout and stderr output streams. It is a good configuration for new ASP.NET projects. FinalMinLevel in combination with minLevel It can be useful to combine finalMinLevel with MinLevel . Suppose there's a sub-module RequestLogger that should have its own dedicated log-target, but at the same time all Error or higher logs should flow to the catch-all log-target. This can be achieved through: It can also be configured like this if using NLog v4: All logs coming from RequestLogger with a level between Debug and higher will be logged to requestTarget . All other logs with a level Info or higher will be logged to catchAllTarget , including Error and Fatal logs from RequestLogger .","title":"Logging Rules FinalMinLevel"},{"location":"Logging-Rules-FinalMinLevel/#levels","text":"The following table describes which log levels are enabled depending on the finalMinLevel value: FinalMinLevel Ordinal Enabled log levels Trace 0 Trace, Debug, Info, Warn, Error and Fatal Debug 1 Debug, Info, Warn, Error and Fatal Info 2 Info, Warn, Error and Fatal Warn 3 Warn, Error and Fatal Error 4 Error and Fatal Fatal 5 Fatal Off 6 NLog includes LogLevel Off , that can be used to suppress all output from a noisy logger: This can also be implemented using maxLevel and final in NLog v4: ","title":"Levels"},{"location":"Logging-Rules-FinalMinLevel/#overrides","text":"As mentioned before, finalMinLevel can override previous rules. For example, if we want Warn logs of higher from Microsoft.* , but Info logs or higher from Microsoft.Hosting.Lifetime , then this is a possible configuration: Keep in mind that the order is still important. If the \"Microsoft.* and Microsoft.Hosting.Lifetime* were reversed, then Microsoft.* would override Microsoft.Hosting.Lifetime* and both would be set to Warn .","title":"Overrides"},{"location":"Logging-Rules-FinalMinLevel/#microsoft-extensions-logging-filters","text":"The Microsoft Logging filters specified in appsettings.json are ignored by default when using NLog 5.0. This is to avoid that new users think NLog Logging Rules are not working, because Microsoft LoggerFactory filters are interfering. The default logging logging configuration in appsettings.json : { \"Logging\": { \"LogLevel\": { \"Default\": \"Information\", \"Microsoft\": \"Warning\", \"Microsoft.Hosting.Lifetime\": \"Information\" } } } Can be configured through NLog.config like this: Notice that the logger named Microsoft.Hosting.Lifetime* overrides the Microsoft.* logger. See also Microsoft Hosting Lifetime Startup Messages See also Tutorial for using NLog with ASP.NET Core","title":"Microsoft Extensions Logging Filters"},{"location":"Logging-Rules-FinalMinLevel/#complete-example","text":"This example also filters logs from System.* and separates informative logs and error logs between the stdout and stderr output streams. It is a good configuration for new ASP.NET projects. ","title":"Complete example"},{"location":"Logging-Rules-FinalMinLevel/#finalminlevel-in-combination-with-minlevel","text":"It can be useful to combine finalMinLevel with MinLevel . Suppose there's a sub-module RequestLogger that should have its own dedicated log-target, but at the same time all Error or higher logs should flow to the catch-all log-target. This can be achieved through: It can also be configured like this if using NLog v4: All logs coming from RequestLogger with a level between Debug and higher will be logged to requestTarget . All other logs with a level Info or higher will be logged to catchAllTarget , including Error and Fatal logs from RequestLogger .","title":"FinalMinLevel in combination with minLevel"},{"location":"Logging-Troubleshooting/","text":"Possible causes When no log output is produced, the issue may originate in NLog configuration, the application, or the runtime environment. Common causes include: NLog cannot find the configuration file. Ensure NLog.config has: Build Action = Content Copy to Output Directory = Copy if newer The configuration file contains invalid XML or NLog configuration errors. Logging rules do not match the logger name or log level. The logging code is never executed. The application exits before logs are flushed. Call NLog.LogManager.Shutdown() during application shutdown to flush pending events . The logging target fails at runtime (e.g., missing file permissions). Log output is written to an unexpected location. A different configuration is used at deployment time (overriding the expected NLog.config ). Environment differences (hosting, container, or filesystem) compared to local development. Troubleshooting steps These steps help isolate the problem area: configuration loading \u2192 initialization \u2192 rule matching \u2192 target writing \u2192 application execution 1. Verify configuration file loading Ensure NLog.config xml-file is located in the application\u2019s base directory, as the primary location of the multiple file location scanned by NLog at startup. Ensure NLog.config has: Build Action = Content Copy to Output Directory = Copy if newer On Linux, file name must be nlog.config (all lowercase as case-sensitive) Some NuGet packages may modify Web.config or App.config and override logging configuration Do NOT use the deprecated NLog.Config NuGet-package, which may overwrite or reset configuration during deployment. Verify that the deployed configuration matches the expected version. 2. Enable configuration exception reporting NLog will by default suppress any configuration errors, instead of causing the application to fail. But this also means that application will not produce any logging output. Enabling throwConfigExceptions will make NLog throw exceptions to report any issues detected in the NLog Configuration at startup: ... ... 3. Enable InternalLogger Enable the NLog InternalLogger and use the output to help diagnose: - Configuration loading issues - Logger rules decisions - Target initialization failures - Target writing failures (File permission problems, File path issues, Ex.) - Etc. ... ... 4. Enable InternalLogger early in startup If no InternalLogger output appears, then it either NLog.config could not be found or failed to load. It can also be that the InternalLogger was enabled after initial attempt to load the NLog logging configuration. Try to enable NLog InternalLogger from code at application startup. Ensure it happens before any logger usage (like static Logger objects), as configuration is initially loaded when first Logger is created. class Program { // Temporarily disable static logger initialization // readonly static Logger = LogManager.GetCurrentClassLogger(); static void Main() { NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Debug; NLog.Common.InternalLogger.LogToConsole = true; NLog.Common.InternalLogger.LogFile = @\"c:\\temp\\nlog-internal.txt\"; var logger = LogManager.GetLogger(\"foo\"); logger.Info(\"Program started\"); LogManager.Shutdown(); } } 5. Simplify logging rules Reduce logging rule complexity to eliminate matching issues, by adding catch-all rule that matches all loggers and all levels at the beginning of your section: If still no logs appear: Verify that the logging call is actually executed in the application code. Ensure explicit flush is made before application shutdown, in case NLog target is having delays in network communication. Ex. by calling NLog.LogManager.Shutdown() . If using file-target then make sure to use absolute file-path as more predictable. 6. Enable runtime exception reporting (last resort) Enable runtime exception propagation only for diagnostics: NLog.LogManager.ThrowExceptions = true; \u26a0\ufe0f Use only ThrowExceptions = true for troubleshooting and unit-testing. Should never be kept enabled in production, as it can cause application runtime crashes. Different from throwConfigExceptions=\"true\" that only enables configuration verification at startup. class Program { static void Main() { NLog.LogManager.ThrowExceptions = true; // TODO Remove after troubleshooting NLog.Common.InternalLogger.LogLevel = LogLevel.Debug; NLog.Common.InternalLogger.LogToConsole = true; NLog.Common.InternalLogger.LogFile = @\"c:\\temp\\nlog-internal.txt\"; var logger = LogManager.GetLogger(\"foo\"); logger.Info(\"Program started\"); LogManager.Shutdown(); } } Other tools and techniques External tools can help determine whether the issue is inside NLog or the environment: Process Monitor \u2014 file access, permission, and I/O tracing Process Explorer \u2014 handles, threads, and runtime diagnostics These help distinguish between \"NLog not writing\" vs \"Operating System prevented writing\". Key questions to guide troubleshooting Focus on observable behavior: Is the configuration loaded? Is the logger initialized? Is the logging call executed? Is the log event routed? Is the target writing successfully? Answering these typically identifies the failing component quickly.","title":"Logging Troubleshooting"},{"location":"Logging-Troubleshooting/#possible-causes","text":"When no log output is produced, the issue may originate in NLog configuration, the application, or the runtime environment. Common causes include: NLog cannot find the configuration file. Ensure NLog.config has: Build Action = Content Copy to Output Directory = Copy if newer The configuration file contains invalid XML or NLog configuration errors. Logging rules do not match the logger name or log level. The logging code is never executed. The application exits before logs are flushed. Call NLog.LogManager.Shutdown() during application shutdown to flush pending events . The logging target fails at runtime (e.g., missing file permissions). Log output is written to an unexpected location. A different configuration is used at deployment time (overriding the expected NLog.config ). Environment differences (hosting, container, or filesystem) compared to local development.","title":"Possible causes"},{"location":"Logging-Troubleshooting/#troubleshooting-steps","text":"These steps help isolate the problem area: configuration loading \u2192 initialization \u2192 rule matching \u2192 target writing \u2192 application execution","title":"Troubleshooting steps"},{"location":"Logging-Troubleshooting/#1-verify-configuration-file-loading","text":"Ensure NLog.config xml-file is located in the application\u2019s base directory, as the primary location of the multiple file location scanned by NLog at startup. Ensure NLog.config has: Build Action = Content Copy to Output Directory = Copy if newer On Linux, file name must be nlog.config (all lowercase as case-sensitive) Some NuGet packages may modify Web.config or App.config and override logging configuration Do NOT use the deprecated NLog.Config NuGet-package, which may overwrite or reset configuration during deployment. Verify that the deployed configuration matches the expected version.","title":"1. Verify configuration file loading"},{"location":"Logging-Troubleshooting/#2-enable-configuration-exception-reporting","text":"NLog will by default suppress any configuration errors, instead of causing the application to fail. But this also means that application will not produce any logging output. Enabling throwConfigExceptions will make NLog throw exceptions to report any issues detected in the NLog Configuration at startup: ... ... ","title":"2. Enable configuration exception reporting"},{"location":"Logging-Troubleshooting/#3-enable-internallogger","text":"Enable the NLog InternalLogger and use the output to help diagnose: - Configuration loading issues - Logger rules decisions - Target initialization failures - Target writing failures (File permission problems, File path issues, Ex.) - Etc. ... ... ","title":"3. Enable InternalLogger"},{"location":"Logging-Troubleshooting/#4-enable-internallogger-early-in-startup","text":"If no InternalLogger output appears, then it either NLog.config could not be found or failed to load. It can also be that the InternalLogger was enabled after initial attempt to load the NLog logging configuration. Try to enable NLog InternalLogger from code at application startup. Ensure it happens before any logger usage (like static Logger objects), as configuration is initially loaded when first Logger is created. class Program { // Temporarily disable static logger initialization // readonly static Logger = LogManager.GetCurrentClassLogger(); static void Main() { NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Debug; NLog.Common.InternalLogger.LogToConsole = true; NLog.Common.InternalLogger.LogFile = @\"c:\\temp\\nlog-internal.txt\"; var logger = LogManager.GetLogger(\"foo\"); logger.Info(\"Program started\"); LogManager.Shutdown(); } }","title":"4. Enable InternalLogger early in startup"},{"location":"Logging-Troubleshooting/#5-simplify-logging-rules","text":"Reduce logging rule complexity to eliminate matching issues, by adding catch-all rule that matches all loggers and all levels at the beginning of your section: If still no logs appear: Verify that the logging call is actually executed in the application code. Ensure explicit flush is made before application shutdown, in case NLog target is having delays in network communication. Ex. by calling NLog.LogManager.Shutdown() . If using file-target then make sure to use absolute file-path as more predictable.","title":"5. Simplify logging rules"},{"location":"Logging-Troubleshooting/#6-enable-runtime-exception-reporting-last-resort","text":"Enable runtime exception propagation only for diagnostics: NLog.LogManager.ThrowExceptions = true; \u26a0\ufe0f Use only ThrowExceptions = true for troubleshooting and unit-testing. Should never be kept enabled in production, as it can cause application runtime crashes. Different from throwConfigExceptions=\"true\" that only enables configuration verification at startup. class Program { static void Main() { NLog.LogManager.ThrowExceptions = true; // TODO Remove after troubleshooting NLog.Common.InternalLogger.LogLevel = LogLevel.Debug; NLog.Common.InternalLogger.LogToConsole = true; NLog.Common.InternalLogger.LogFile = @\"c:\\temp\\nlog-internal.txt\"; var logger = LogManager.GetLogger(\"foo\"); logger.Info(\"Program started\"); LogManager.Shutdown(); } }","title":"6. Enable runtime exception reporting (last resort)"},{"location":"Logging-Troubleshooting/#other-tools-and-techniques","text":"External tools can help determine whether the issue is inside NLog or the environment: Process Monitor \u2014 file access, permission, and I/O tracing Process Explorer \u2014 handles, threads, and runtime diagnostics These help distinguish between \"NLog not writing\" vs \"Operating System prevented writing\".","title":"Other tools and techniques"},{"location":"Logging-Troubleshooting/#key-questions-to-guide-troubleshooting","text":"Focus on observable behavior: Is the configuration loaded? Is the logger initialized? Is the logging call executed? Is the log event routed? Is the target writing successfully? Answering these typically identifies the failing component quickly.","title":"Key questions to guide troubleshooting"},{"location":"Longdate-Layout-Renderer/","text":"The date and time in a long, sortable format yyyy-MM-dd HH:mm:ss.ffff . Platforms Supported: All Alternative ${date:format=yyyy-MM-dd_HH} can be used to customize the DateTime-format. Configuration Syntax ${longdate:universalTime=Boolean} Parameters Rendering Options universalTime - Indicates whether to output UTC time instead of local time.Boolean Default: False Time Source Precision NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Longdate Layout Renderer"},{"location":"Longdate-Layout-Renderer/#configuration-syntax","text":"${longdate:universalTime=Boolean}","title":"Configuration Syntax"},{"location":"Longdate-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Longdate-Layout-Renderer/#rendering-options","text":"universalTime - Indicates whether to output UTC time instead of local time.Boolean Default: False","title":"Rendering Options"},{"location":"Longdate-Layout-Renderer/#time-source-precision","text":"NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Time Source Precision"},{"location":"Lowercase-Layout-Renderer/","text":"Converts the result of another layout output to lower case. Platforms Supported: All Configuration Syntax ${lowercase:lowercase=Boolean:inner=Layout:culture=Culture} or by using ambient property to modify output of other layout renderer: ${other:lowercase=Boolean} Parameters Transformation Options lowercase - Indicates whether lower case conversion should be applied. Boolean Default: True. Required when using as ambient. inner - Wrapped layout. Layout culture - Culture used for rendering. Culture Examples ${lowercase:${level}} ${lowercase:Inner=${level}} ${level:lowercase=true}","title":"Lowercase Layout Renderer"},{"location":"Lowercase-Layout-Renderer/#configuration-syntax","text":"${lowercase:lowercase=Boolean:inner=Layout:culture=Culture} or by using ambient property to modify output of other layout renderer: ${other:lowercase=Boolean}","title":"Configuration Syntax"},{"location":"Lowercase-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Lowercase-Layout-Renderer/#transformation-options","text":"lowercase - Indicates whether lower case conversion should be applied. Boolean Default: True. Required when using as ambient. inner - Wrapped layout. Layout culture - Culture used for rendering. Culture","title":"Transformation Options"},{"location":"Lowercase-Layout-Renderer/#examples","text":"${lowercase:${level}} ${lowercase:Inner=${level}} ${level:lowercase=true}","title":"Examples"},{"location":"MDC-Layout-Renderer/","text":"\u26a0\ufe0f NLog 5.0 introduces ScopeContext that replaces MDLC + MDC Mapped Diagnostics Context (MDC) - a thread-local structure that keeps a dictionary of strings and provides methods to output them in layouts. Platforms Supported: All (NLog 4.1 supports any Object type, not just String ) MDC is considered legacy, and instead is recommended to use MDLC that includes support for async Tasks. See also NLog Context Configuration Syntax ${mdc:item=String} Parameters Rendering Options item - Name of the item. Required. Note : case sensitive! Example Simple Properties The following example demonstrates the basic usage of the Mapped Diagnostics Context. MappedDiagnosticsContext.Set(\"PropertyName\", \"PropertyValue\"); MappedDiagnosticsContext.Set(\"Property2\", new { Part1 = 2.0m, Part2 = \"Two parts\" }); MappedDiagnosticsContext.Set(\"Property3\", AnyObjectOrString); Add the following to your logger configuration to reference the above properties. ${mdc:item=PropertyName} ${mdc:item=Property2} ${mdc:item=Property3} Dynamic Properties The following example demonstrates a Mapped Diagnostics Context property that renders the value of Environment.TickCount at the time that the context item is rendered. public class MdcTickProperty { public static readonly MdcTickProperty Default = new MdcTickProperty(); private MdcTickProperty () { } public override string ToString () { return Environment.TickCount.ToString(); } } Add the MdcTickProperty instance to the Mapped Diagnostics Context. This will only affect the current thread, as the Mapped Diagnostics Context is thread-local. MappedDiagnosticsContext.Set(\"TickCount\", MdcTickProperty.Default); In the logging configuration, include: ${mdc:item=TickCount} Scoped item The SetScoped method returns an IDisposable that removes the added item when disposed. It can be used in conjunction with the using statement to limit the scope during which the item will be present in the context. using (MappedDiagnosticsContext.SetScoped(\"Property\", \"PropertyValue\")) { // \"Property\" item is present in current context } // \"Property\" item has been removed from current context Notes When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.","title":"MDC Layout Renderer"},{"location":"MDC-Layout-Renderer/#configuration-syntax","text":"${mdc:item=String}","title":"Configuration Syntax"},{"location":"MDC-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"MDC-Layout-Renderer/#rendering-options","text":"item - Name of the item. Required. Note : case sensitive!","title":"Rendering Options"},{"location":"MDC-Layout-Renderer/#example","text":"","title":"Example"},{"location":"MDC-Layout-Renderer/#simple-properties","text":"The following example demonstrates the basic usage of the Mapped Diagnostics Context. MappedDiagnosticsContext.Set(\"PropertyName\", \"PropertyValue\"); MappedDiagnosticsContext.Set(\"Property2\", new { Part1 = 2.0m, Part2 = \"Two parts\" }); MappedDiagnosticsContext.Set(\"Property3\", AnyObjectOrString); Add the following to your logger configuration to reference the above properties. ${mdc:item=PropertyName} ${mdc:item=Property2} ${mdc:item=Property3}","title":"Simple Properties"},{"location":"MDC-Layout-Renderer/#dynamic-properties","text":"The following example demonstrates a Mapped Diagnostics Context property that renders the value of Environment.TickCount at the time that the context item is rendered. public class MdcTickProperty { public static readonly MdcTickProperty Default = new MdcTickProperty(); private MdcTickProperty () { } public override string ToString () { return Environment.TickCount.ToString(); } } Add the MdcTickProperty instance to the Mapped Diagnostics Context. This will only affect the current thread, as the Mapped Diagnostics Context is thread-local. MappedDiagnosticsContext.Set(\"TickCount\", MdcTickProperty.Default); In the logging configuration, include: ${mdc:item=TickCount}","title":"Dynamic Properties"},{"location":"MDC-Layout-Renderer/#scoped-item","text":"The SetScoped method returns an IDisposable that removes the added item when disposed. It can be used in conjunction with the using statement to limit the scope during which the item will be present in the context. using (MappedDiagnosticsContext.SetScoped(\"Property\", \"PropertyValue\")) { // \"Property\" item is present in current context } // \"Property\" item has been removed from current context","title":"Scoped item"},{"location":"MDC-Layout-Renderer/#notes","text":"When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.","title":"Notes"},{"location":"MDLC-Layout-Renderer/","text":"\u26a0\ufe0f NLog 5.0 introduces ScopeContext that replaces MDLC + MDC Mapped Diagnostic Logical Context (MDLC) acts like a dictionary of named properties with values, that are stored in an Async-Local structure (Similar to \"Thread Context Map\" in Log4j). It is the async version of MDC Layout Renderer . Platforms Supported: All Introduced with NLog 4.1 (NLog 4.1.1 add support for any Object type, not just String ) It enables one to assign one or more named properties to the active scope (Ex. a request CorrelationId). Then all logger-events created within the scoped logical context, can automatically capture the scope-properties without needing to specify it with each LogEvent. The specified scope properties will automatically flow together with async Tasks. See also NLog Context . Configuration Syntax ${mdlc:item=String} Parameters Rendering Options item - Name of the item. Required. Note : case sensitive! Example Simple Properties The following example demonstrates the basic usage of the Mapped Diagnostic Logical Context. MappedDiagnosticsLogicalContext.Set(\"PropertyName\", \"PropertyValue\"); MappedDiagnosticsLogicalContext.Set(\"PropertyName2\", \"AnotherPropertyValue\"); Add the following to your logger configuration to reference the above properties. ${mdlc:item=PropertyName} ${mdlc:item=PropertyName2} Scoped item The SetScoped method returns an IDisposable that removes the added item when disposed. It can be used in conjunction with the using statement to limit the scope during which the item will be present in the context. using (MappedDiagnosticsLogicalContext.SetScoped(\"Property\", \"PropertyValue\")) { // \"Property\" item is present in current context } // \"Property\" item has been removed from current context .NET Core logging When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : //note: render userId via ${mdlc:userid} using (_logger.BeginScope(new[] { new KeyValuePair(\"userid\", request.UserId) })) { _logger.LogDebug(\"Start process {ProccessName}, \"Main\"); }","title":"MDLC Layout Renderer"},{"location":"MDLC-Layout-Renderer/#configuration-syntax","text":"${mdlc:item=String}","title":"Configuration Syntax"},{"location":"MDLC-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"MDLC-Layout-Renderer/#rendering-options","text":"item - Name of the item. Required. Note : case sensitive!","title":"Rendering Options"},{"location":"MDLC-Layout-Renderer/#example","text":"","title":"Example"},{"location":"MDLC-Layout-Renderer/#simple-properties","text":"The following example demonstrates the basic usage of the Mapped Diagnostic Logical Context. MappedDiagnosticsLogicalContext.Set(\"PropertyName\", \"PropertyValue\"); MappedDiagnosticsLogicalContext.Set(\"PropertyName2\", \"AnotherPropertyValue\"); Add the following to your logger configuration to reference the above properties. ${mdlc:item=PropertyName} ${mdlc:item=PropertyName2}","title":"Simple Properties"},{"location":"MDLC-Layout-Renderer/#scoped-item","text":"The SetScoped method returns an IDisposable that removes the added item when disposed. It can be used in conjunction with the using statement to limit the scope during which the item will be present in the context. using (MappedDiagnosticsLogicalContext.SetScoped(\"Property\", \"PropertyValue\")) { // \"Property\" item is present in current context } // \"Property\" item has been removed from current context","title":"Scoped item"},{"location":"MDLC-Layout-Renderer/#net-core-logging","text":"When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : //note: render userId via ${mdlc:userid} using (_logger.BeginScope(new[] { new KeyValuePair(\"userid\", request.UserId) })) { _logger.LogDebug(\"Start process {ProccessName}, \"Main\"); }","title":".NET Core logging"},{"location":"MSMQ-target/","text":"Writes log messages to the Microsoft Message Queue (MSMQ). Platforms Supported: Limited - Windows only as it depends on mqrt.dll, and requires nuget-package NLog.MSMQ Configuration Syntax Read more about using the Configuration File . Parameters name - Name of the target. useXmlEncoding - Indicates whether to use the XML format when serializing message. Boolean Default: False encoding - Encoding to be used when writing text to the queue. Encoding layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withException=true} Queue Options: * queue - Name of the queue to write to. Layout Required . To write to a private queue on a local machine use .\\private$\\QueueName. For other available queue names, consult MSMQ documentation. label - Label to associate with each message. Layout Default: \"\" Changed default value from \"NLog\" to \"\" with NLog.MSMQ ver. 5.3 recoverable - Indicates whether to use recoverable messages (with guaranteed delivery). Boolean Default: False singleTransaction - Indicates whether to send single-transaction-style to transactional queue. Boolean Default: False Introduced with NLog.MSMQ ver. 5.3 checkIfQueueExists - If true then it will check if queue exists for every message sent, which can be useful if troubleshooting. The queue exist check might cause Exception to be thrown when private-remote-queue, and prevent message send. Boolean Default: False Changed default value from true to false with NLog.MSMQ ver. 5.3 createQueueIfNotExists - Indicates whether to create the queue if it doesn't exists. Notice this means it will check if queue exists for every message sent. Boolean Default: False Notes The MSMQ target requires that: * Installing Nuget-package NLog.MSMQ (Before NLog 5.0 it was NLog.Extended ) * The machine doing the logging have MSMQ installed with the Active Directory Domain Services Integration option. If the option is not installed, the target will throw an exception. * The queue being written to is NOT transactional. Introduced SingleTransaction with NLog.MSMQ ver. 5.3, that should support transactional queues.","title":"MSMQ target"},{"location":"MSMQ-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"MSMQ-target/#parameters","text":"name - Name of the target. useXmlEncoding - Indicates whether to use the XML format when serializing message. Boolean Default: False encoding - Encoding to be used when writing text to the queue. Encoding layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withException=true} Queue Options: * queue - Name of the queue to write to. Layout Required . To write to a private queue on a local machine use .\\private$\\QueueName. For other available queue names, consult MSMQ documentation. label - Label to associate with each message. Layout Default: \"\" Changed default value from \"NLog\" to \"\" with NLog.MSMQ ver. 5.3 recoverable - Indicates whether to use recoverable messages (with guaranteed delivery). Boolean Default: False singleTransaction - Indicates whether to send single-transaction-style to transactional queue. Boolean Default: False Introduced with NLog.MSMQ ver. 5.3 checkIfQueueExists - If true then it will check if queue exists for every message sent, which can be useful if troubleshooting. The queue exist check might cause Exception to be thrown when private-remote-queue, and prevent message send. Boolean Default: False Changed default value from true to false with NLog.MSMQ ver. 5.3 createQueueIfNotExists - Indicates whether to create the queue if it doesn't exists. Notice this means it will check if queue exists for every message sent. Boolean Default: False","title":"Parameters"},{"location":"MSMQ-target/#notes","text":"The MSMQ target requires that: * Installing Nuget-package NLog.MSMQ (Before NLog 5.0 it was NLog.Extended ) * The machine doing the logging have MSMQ installed with the Active Directory Domain Services Integration option. If the option is not installed, the target will throw an exception. * The queue being written to is NOT transactional. Introduced SingleTransaction with NLog.MSMQ ver. 5.3, that should support transactional queues.","title":"Notes"},{"location":"Machinename-Layout-Renderer/","text":"The NetBIOS Machine name that the process is running on. Platforms Supported: All Configuration Syntax ${machinename} Remarks NetBIOS name is limited to MAX_COMPUTERNAME_LENGTH which is 15 for Windows. ${hostname} has support for the full DNS-name.","title":"Machinename Layout Renderer"},{"location":"Machinename-Layout-Renderer/#configuration-syntax","text":"${machinename}","title":"Configuration Syntax"},{"location":"Machinename-Layout-Renderer/#remarks","text":"NetBIOS name is limited to MAX_COMPUTERNAME_LENGTH which is 15 for Windows. ${hostname} has support for the full DNS-name.","title":"Remarks"},{"location":"Mail-target/","text":"Sends log messages by email using SMTP protocol. Platforms Supported: All - Requires nuget-package NLog.Targets.Mail since NLog v6, or alternative MailKit Combine with FallbackGroup to fallback to alternative SMTP-server on error. See example here . Combine with BufferingWrapper and AutoFlushWrapper to group multiple logevents into a single email. Combine with LimitingWrapper to throttle the number of emails. Combine with FilteringWrapper to avoid repeating identical emails. Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options header - Header for the message-body. Layout footer - Footer for the message-body. Layout layout - Text to be rendered for message-body. Layout Required. Default: ${message}${newline} . html - Indicates whether to send message as HTML instead of plain text. Boolean Default: false addNewLines - Indicates whether to add new lines between log entries. Boolean replaceNewlineWithBrTagInHtml - Indicates whether NewLine characters in the body should be replaced with
tags. Boolean Default: false encoding - Encoding to be used for sending e-mail. Encoding Default: UTF-8 Message Options subject - Mail subject. Layout Required. Default: Message from NLog on ${machinename} to - Recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout . bcc - BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout cc - CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout from - Sender's email address (e.g. joe@domain.com). Layout Required. body - Same as Layout property. Mail message body (repeated for each log message send in one mail). Layout Default: ${message}${newline} priority - The mail message priority. Low / Normal / High NLog.MailKit v3.2 (and newer) accepts NonUrgent / Low , Normal , Urgent / High (Supports MimeKit.MessagePriority ) SMTP Options smtpServer - SMTP Server to be used for sending. Layout Required. smtpPort - Port number that SMTP Server is listening on. Integer Default: 25. Note: port 465 isn't working with SSL. See issue 1226 smtpAuthentication - SMTP Authentication mode. Default: None Possible values: Basic - Basic - username and password. None - No authentication. Ntlm - NTLM Authentication using network credentials of user currently logged on (Same as SmtpClient.UseDefaultCredentials = true ) OAuth2 - NLog.Mailkit ver. 6.1.3 (and newer) supports OAuth2 authentication where SmtpUserName provides clientid, and SmtpPassword provides clientSecret/accessToken. smtpUserName - Username used to connect to SMTP server (used when SmtpAuthentication is set to \"basic\"). Layout smtpPassword - Password used to authenticate against SMTP server (used when SmtpAuthentication is set to \"basic\"). Layout enableSsl - Indicates whether SSL (secure sockets layer) should be used when communicating with SMTP server. Boolean Default: False. Notice SMTP/SSL, SMTP over SSL, or SMTPS with port 465 is only supported by NLog.MailKit . See issue 1226 secureSocketOption - NLog.Mailkit ver. 2.1 (and newer) supports both SSL / TLS encryption. Default: StartTlsWhenAvailable. Possible values: None - No SSL or TLS encryption should be used. Auto - Allow the MailKit.IMailService to decide which SSL or TLS options to use. If the server does not support SSL or TLS, then no encryption. SslOnConnect - The connection should use SSL or TLS encryption immediately. StartTls - The connection should use TLS encryption immediately. StartTlsWhenAvailable - Elevates the connection to use TLS encryption immediately, when supported by server. useSystemNetMailSettings - Force using smtp configuration from system.net/mailSettings. Boolean Default: False timeout - Indicates the SMTP client timeout in milliseconds. Integer Default: 10000 (10 seconds) pickupDirectoryLocation - Gets or sets the folder where applications save mail messages to be processed by the local SMTP server ( introduced in NLog 4.2 ). deliveryMethod - Specifies how outgoing email messages will be handled ( introduced in NLog 4.2 ). Default: Network Possible values: Network - Email is sent through the network to an SMTP server. PickupDirectoryFromIis - Email is copied to the pickup directory used by a local Internet Information Services (IIS) for delivery. SpecifiedPickupDirectory - Email is copied to the directory specified by the PickupDirectoryLocation property for delivery by an external application. skipCertificateValidation - NLog.Mailkit ver. 1.1 (and newer) can skip SSL certificate validation check. Maybe useful for self-signed certificates, but not recommended for production. mailheader - Specify one or more email-message-headers (Ex. Message-Id ) Introduced with NLog v5.1.3 and NLog.MailKit v5.1 Remarks .NET Standard 1.x / MailKit package The SmtpClient is not part of .NET Standard 1.x. Also notice that the original SmtpClient of .NET is obsolete in favor of MailKit: The NLog.MailKit is the Mail target implementation which uses MailKit. Including the NLog.MailKit package will replace the original mail target and has the same options as the original mail target Install-Package NLog.MailKit or use And add to your nlog.config: ... Bug/feature requests for NLog.MailKit please on the NLog.MailKit repo Application Configuration File If the application config file contains mail settings, fx.: These values will be used, if target doesn't override them (see useSystemNetMailSettings attribute). * NetStandard2.X does not support mail settings in the application config file. Email Address Format It is possible to use an address in format \"John Doe \" but the special characters < and > must be escaped. The result would be John Doe <john.doe@example.com> MailKit Target using Amazon AWS SMTP: Mail Target wrapped by FallbackGroup Target Example configuration for a Mailserver Fallback with multiple hosts. Mail Target send LogEvent history on error Example configuration that buffers LogEvents and sends entire batch on error LogEvent: = LogLevel.Error\" flushOnConditionOnly=\"true\"> Using Mail-Target with GMail smtpAuthentication=\"Basic\" enables use of NetworkCredentials for login, which can be used for sending OAuth ClientId ( smtpUserName ) and OAuth ClientSecret/AccessToken ( smtpPassword ). Consider to set From -address same as the username to reduce chance to be seen as spam. ","title":"Mail target"},{"location":"Mail-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Mail-target/#parameters","text":"","title":"Parameters"},{"location":"Mail-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Mail-target/#layout-options","text":"header - Header for the message-body. Layout footer - Footer for the message-body. Layout layout - Text to be rendered for message-body. Layout Required. Default: ${message}${newline} . html - Indicates whether to send message as HTML instead of plain text. Boolean Default: false addNewLines - Indicates whether to add new lines between log entries. Boolean replaceNewlineWithBrTagInHtml - Indicates whether NewLine characters in the body should be replaced with
tags. Boolean Default: false encoding - Encoding to be used for sending e-mail. Encoding Default: UTF-8","title":"Layout Options"},{"location":"Mail-target/#message-options","text":"subject - Mail subject. Layout Required. Default: Message from NLog on ${machinename} to - Recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout . bcc - BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout cc - CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). Layout from - Sender's email address (e.g. joe@domain.com). Layout Required. body - Same as Layout property. Mail message body (repeated for each log message send in one mail). Layout Default: ${message}${newline} priority - The mail message priority. Low / Normal / High NLog.MailKit v3.2 (and newer) accepts NonUrgent / Low , Normal , Urgent / High (Supports MimeKit.MessagePriority )","title":"Message Options"},{"location":"Mail-target/#smtp-options","text":"smtpServer - SMTP Server to be used for sending. Layout Required. smtpPort - Port number that SMTP Server is listening on. Integer Default: 25. Note: port 465 isn't working with SSL. See issue 1226 smtpAuthentication - SMTP Authentication mode. Default: None Possible values: Basic - Basic - username and password. None - No authentication. Ntlm - NTLM Authentication using network credentials of user currently logged on (Same as SmtpClient.UseDefaultCredentials = true ) OAuth2 - NLog.Mailkit ver. 6.1.3 (and newer) supports OAuth2 authentication where SmtpUserName provides clientid, and SmtpPassword provides clientSecret/accessToken. smtpUserName - Username used to connect to SMTP server (used when SmtpAuthentication is set to \"basic\"). Layout smtpPassword - Password used to authenticate against SMTP server (used when SmtpAuthentication is set to \"basic\"). Layout enableSsl - Indicates whether SSL (secure sockets layer) should be used when communicating with SMTP server. Boolean Default: False. Notice SMTP/SSL, SMTP over SSL, or SMTPS with port 465 is only supported by NLog.MailKit . See issue 1226 secureSocketOption - NLog.Mailkit ver. 2.1 (and newer) supports both SSL / TLS encryption. Default: StartTlsWhenAvailable. Possible values: None - No SSL or TLS encryption should be used. Auto - Allow the MailKit.IMailService to decide which SSL or TLS options to use. If the server does not support SSL or TLS, then no encryption. SslOnConnect - The connection should use SSL or TLS encryption immediately. StartTls - The connection should use TLS encryption immediately. StartTlsWhenAvailable - Elevates the connection to use TLS encryption immediately, when supported by server. useSystemNetMailSettings - Force using smtp configuration from system.net/mailSettings. Boolean Default: False timeout - Indicates the SMTP client timeout in milliseconds. Integer Default: 10000 (10 seconds) pickupDirectoryLocation - Gets or sets the folder where applications save mail messages to be processed by the local SMTP server ( introduced in NLog 4.2 ). deliveryMethod - Specifies how outgoing email messages will be handled ( introduced in NLog 4.2 ). Default: Network Possible values: Network - Email is sent through the network to an SMTP server. PickupDirectoryFromIis - Email is copied to the pickup directory used by a local Internet Information Services (IIS) for delivery. SpecifiedPickupDirectory - Email is copied to the directory specified by the PickupDirectoryLocation property for delivery by an external application. skipCertificateValidation - NLog.Mailkit ver. 1.1 (and newer) can skip SSL certificate validation check. Maybe useful for self-signed certificates, but not recommended for production. mailheader - Specify one or more email-message-headers (Ex. Message-Id ) Introduced with NLog v5.1.3 and NLog.MailKit v5.1","title":"SMTP Options"},{"location":"Mail-target/#remarks","text":"","title":"Remarks"},{"location":"Mail-target/#net-standard-1x-mailkit-package","text":"The SmtpClient is not part of .NET Standard 1.x. Also notice that the original SmtpClient of .NET is obsolete in favor of MailKit: The NLog.MailKit is the Mail target implementation which uses MailKit. Including the NLog.MailKit package will replace the original mail target and has the same options as the original mail target Install-Package NLog.MailKit or use And add to your nlog.config: ... Bug/feature requests for NLog.MailKit please on the NLog.MailKit repo","title":".NET Standard 1.x / MailKit package"},{"location":"Mail-target/#application-configuration-file","text":"If the application config file contains mail settings, fx.: These values will be used, if target doesn't override them (see useSystemNetMailSettings attribute). * NetStandard2.X does not support mail settings in the application config file.","title":"Application Configuration File"},{"location":"Mail-target/#email-address-format","text":"It is possible to use an address in format \"John Doe \" but the special characters < and > must be escaped. The result would be John Doe <john.doe@example.com>","title":"Email Address Format"},{"location":"Mail-target/#mailkit-target-using-amazon-aws-smtp","text":"","title":"MailKit Target using Amazon AWS SMTP:"},{"location":"Mail-target/#mail-target-wrapped-by-fallbackgroup-target","text":"Example configuration for a Mailserver Fallback with multiple hosts. ","title":"Mail Target wrapped by FallbackGroup Target"},{"location":"Mail-target/#mail-target-send-logevent-history-on-error","text":"Example configuration that buffers LogEvents and sends entire batch on error LogEvent: = LogLevel.Error\" flushOnConditionOnly=\"true\"> ","title":"Mail Target send LogEvent history on error"},{"location":"Mail-target/#using-mail-target-with-gmail","text":"smtpAuthentication=\"Basic\" enables use of NetworkCredentials for login, which can be used for sending OAuth ClientId ( smtpUserName ) and OAuth ClientSecret/AccessToken ( smtpPassword ). Consider to set From -address same as the username to reduce chance to be seen as spam. ","title":"Using Mail-Target with GMail"},{"location":"Memory-target/","text":"Writes log messages to an ArrayList in memory for programmatic retrieval. Platforms Supported: All Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} MaxLogsCount Max count, will remove first if over this threshold. Default: 0 (No limit). Introduced with NLog v4.6 Examples Setup MemoryTarget and enumerate messages var config = new NLog.Config.LoggingConfiguration(); var memoryTarget = new NLog.Targets.MemoryTarget(); memoryTarget.Layout = \"${message}\"; // Message format config.AddRuleForAllLevels(memoryTarget); LogManager.Configuration = config; Logger logger = LogManager.GetLogger(\"Example\"); logger.Debug(\"log message\"); foreach (string logMsg in memoryTarget.Logs) { Console.Write(\"logged: {0}\", logMsg); } See also Memory Target Tests See also Memory Simple Example.cs Reading from existing target var target = LogManager.Configuration.FindTargetByName(\"target1\"); var logEvents = target.Logs;","title":"Memory target"},{"location":"Memory-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Memory-target/#parameters","text":"","title":"Parameters"},{"location":"Memory-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Memory-target/#layout-options","text":"layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} MaxLogsCount Max count, will remove first if over this threshold. Default: 0 (No limit). Introduced with NLog v4.6","title":"Layout Options"},{"location":"Memory-target/#examples","text":"","title":"Examples"},{"location":"Memory-target/#setup-memorytarget-and-enumerate-messages","text":"var config = new NLog.Config.LoggingConfiguration(); var memoryTarget = new NLog.Targets.MemoryTarget(); memoryTarget.Layout = \"${message}\"; // Message format config.AddRuleForAllLevels(memoryTarget); LogManager.Configuration = config; Logger logger = LogManager.GetLogger(\"Example\"); logger.Debug(\"log message\"); foreach (string logMsg in memoryTarget.Logs) { Console.Write(\"logged: {0}\", logMsg); } See also Memory Target Tests See also Memory Simple Example.cs","title":"Setup MemoryTarget and enumerate messages"},{"location":"Memory-target/#reading-from-existing-target","text":"var target = LogManager.Configuration.FindTargetByName(\"target1\"); var logEvents = target.Logs;","title":"Reading from existing target"},{"location":"Message-Layout-Renderer/","text":"The formatted log message. Platforms Supported: All Configuration Syntax ${message:exceptionSeparator=String:withException=Boolean:raw=Boolean} Parameters Layout Options exceptionSeparator - String that separates message from the exception. withException - Indicates whether to log exception along with message. Boolean raw - Render the unformatted input message without using input parameters (Message-Template for structured logging ). Boolean Introduced with NLog 4.5 Text tranformations NLog provides several text transformations , that can be useful. Ex: - Truncate - ${message:truncate=1000} - Replace Newlines - ${replace-newlines:${message}} - Replace with RegEx support - ${replace:${message}:searchFor=abc:replaceWith=xyz}","title":"Message Layout Renderer"},{"location":"Message-Layout-Renderer/#configuration-syntax","text":"${message:exceptionSeparator=String:withException=Boolean:raw=Boolean}","title":"Configuration Syntax"},{"location":"Message-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Message-Layout-Renderer/#layout-options","text":"exceptionSeparator - String that separates message from the exception. withException - Indicates whether to log exception along with message. Boolean raw - Render the unformatted input message without using input parameters (Message-Template for structured logging ). Boolean Introduced with NLog 4.5","title":"Layout Options"},{"location":"Message-Layout-Renderer/#text-tranformations","text":"NLog provides several text transformations , that can be useful. Ex: - Truncate - ${message:truncate=1000} - Replace Newlines - ${replace-newlines:${message}} - Replace with RegEx support - ${replace:${message}:searchFor=abc:replaceWith=xyz}","title":"Text tranformations"},{"location":"MessageBox-target/","text":"Page move to MessageBoxTarget - NLog/NLog.Windows.Forms","title":"MessageBox target"},{"location":"MethodCall-target/","text":"Calls the specified static method on each log message and passes contextual parameters to it. Platforms Supported: All Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Invocation Options methodName - Method name. The method must be public and static . className - Class name. Do include the assembly name, e.g. \"NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests\" Parameter Options parameters - The array of parameters to be passed. Collection Each collection item is represented by element with the following attributes: layout - Layout that should be use to calculate the value for the parameter. Layout Required. name - Name of the parameter. type - Type of the parameter. System.Type Note: Since NLog 4.3 these parameters can be optional. Examples Configure call of lambda at runtime Introduced with NLog ver. 4.5.8 One can make it call a user defined delegate using Configuration API : public class Example { static void Main(string[] args) { MethodCallTarget target = new MethodCallTarget(\"MyTarget\", (logEvent, args) => Console.WriteLine(logEvent.FormattedMessage)); NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; Logger logger = LogManager.GetLogger(\"Example\"); logger.Info(\"log message\"); } } Or using the Fluent-Configuration-API introduced with NLog v5: public class Example { static void Main(string[] args) { var logger = LogManager.Setup().LoadConfiguration(c => { c.ForLogger().WriteToMethodCall((logEvent, args) => Console.WriteLine(logEvent.FormattedMessage)); }).GetCurrentClassLogger(); logger.Info(\"log message\"); } } Configure call of static method with NLog.config In order to send all logs to a static method, use the following configuration file: Per the configuration, the log method needs to be called \"LogMethod\" be declared in \"SomeNamespace.MyClass\" class. The class must be compiled to MyAssembly.dll. Each parameter of the log method must correspond to \\ entry in the target configuration. namespace SomeNamespace { using System; public class MyClass { public static void LogMethod(string level, string message) { Console.WriteLine(\"l: {0} m: {1}\", level, message); } } } Names of parameters are not important, only their order is. The default type of each parameter is string, but it can be overridden by adding type attribute to element. Configure call of static method at runtime It is also possible to configure logging using Configuration API : using System; using NLog; using NLog.Targets; using System.Diagnostics; public class Example { public static void LogMethod(string level, string message) { Console.WriteLine(\"l: {0} m: {1}\", level, message); } static void Main(string[] args) { MethodCallTarget target = new MethodCallTarget() { Name = \"MyTarget\" }; target.ClassName = typeof(Example).AssemblyQualifiedName; target.MethodName = \"LogMethod\"; target.Parameters.Add(new MethodCallParameter(\"${level}\")); target.Parameters.Add(new MethodCallParameter(\"${message}\")); NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; Logger logger = LogManager.GetLogger(\"Example\"); logger.Debug(\"log message\"); logger.Error(\"error message\"); } }","title":"MethodCall target"},{"location":"MethodCall-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"MethodCall-target/#parameters","text":"","title":"Parameters"},{"location":"MethodCall-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"MethodCall-target/#invocation-options","text":"methodName - Method name. The method must be public and static . className - Class name. Do include the assembly name, e.g. \"NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests\"","title":"Invocation Options"},{"location":"MethodCall-target/#parameter-options","text":"parameters - The array of parameters to be passed. Collection Each collection item is represented by element with the following attributes: layout - Layout that should be use to calculate the value for the parameter. Layout Required. name - Name of the parameter. type - Type of the parameter. System.Type Note: Since NLog 4.3 these parameters can be optional.","title":"Parameter Options"},{"location":"MethodCall-target/#examples","text":"","title":"Examples"},{"location":"MethodCall-target/#configure-call-of-lambda-at-runtime","text":"Introduced with NLog ver. 4.5.8 One can make it call a user defined delegate using Configuration API : public class Example { static void Main(string[] args) { MethodCallTarget target = new MethodCallTarget(\"MyTarget\", (logEvent, args) => Console.WriteLine(logEvent.FormattedMessage)); NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; Logger logger = LogManager.GetLogger(\"Example\"); logger.Info(\"log message\"); } } Or using the Fluent-Configuration-API introduced with NLog v5: public class Example { static void Main(string[] args) { var logger = LogManager.Setup().LoadConfiguration(c => { c.ForLogger().WriteToMethodCall((logEvent, args) => Console.WriteLine(logEvent.FormattedMessage)); }).GetCurrentClassLogger(); logger.Info(\"log message\"); } }","title":"Configure call of lambda at runtime"},{"location":"MethodCall-target/#configure-call-of-static-method-with-nlogconfig","text":"In order to send all logs to a static method, use the following configuration file: Per the configuration, the log method needs to be called \"LogMethod\" be declared in \"SomeNamespace.MyClass\" class. The class must be compiled to MyAssembly.dll. Each parameter of the log method must correspond to \\ entry in the target configuration. namespace SomeNamespace { using System; public class MyClass { public static void LogMethod(string level, string message) { Console.WriteLine(\"l: {0} m: {1}\", level, message); } } } Names of parameters are not important, only their order is. The default type of each parameter is string, but it can be overridden by adding type attribute to element.","title":"Configure call of static method with NLog.config"},{"location":"MethodCall-target/#configure-call-of-static-method-at-runtime","text":"It is also possible to configure logging using Configuration API : using System; using NLog; using NLog.Targets; using System.Diagnostics; public class Example { public static void LogMethod(string level, string message) { Console.WriteLine(\"l: {0} m: {1}\", level, message); } static void Main(string[] args) { MethodCallTarget target = new MethodCallTarget() { Name = \"MyTarget\" }; target.ClassName = typeof(Example).AssemblyQualifiedName; target.MethodName = \"LogMethod\"; target.Parameters.Add(new MethodCallParameter(\"${level}\")); target.Parameters.Add(new MethodCallParameter(\"${message}\")); NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); config.AddRuleForAllLevels(target) NLog.LogManager.Configuration = config; Logger logger = LogManager.GetLogger(\"Example\"); logger.Debug(\"log message\"); logger.Error(\"error message\"); } }","title":"Configure call of static method at runtime"},{"location":"MicrosoftConsoleJsonLayout/","text":"A custom NLog JsonLayout that renders to JSON to simulate Microsoft Logging AddJsonConsole . Platforms Supported: All - Requires nuget-package NLog.Extensions.Logging Introduced with NLog.Extensions.Logging ver. 5.0 This would write: { \"Timestamp\": \"2010-01-01 12:34:56.0000Z\", \"EventId\": 110, \"LogLevel\": \"Debug\", \"Category\": \"ConsoleApp.Program\", \"message\": \"hello, world\", \"State\": { \"location:\" \"world\", \"{OriginalFormat}\": \"hello, {location}\" } } Parameters Attribute - Additional attributes. State - Additional state attributes, besides the message properties. IncludeScopes - Include ScopeContext Nested states as additional Scopes-attribute. IncludeActivityIds - Includes TraceId + SpanId + ParentId from System.Diagnostics.Activity.Current Introduced with NLog.Extensions.Logging ver. 6.1.3 - Simulates ActivityTrackingOptions.TraceId | ActivityTrackingOptions.SpanId | ActivityTrackingOptions.ParentId TimestampFormat - Override the format of the UTC Timestamp. Default = \"O\" IndentJson - Enables indent for JSON pretty format with newlines (From JsonLayout ). Default = false DottedRecursion - Flatten object-property-names (From JsonLayout ). Default = false Introduced with NLog.Extensions.Logging ver. 6.1.1","title":"MicrosoftConsoleJsonLayout"},{"location":"MicrosoftConsoleJsonLayout/#parameters","text":"Attribute - Additional attributes. State - Additional state attributes, besides the message properties. IncludeScopes - Include ScopeContext Nested states as additional Scopes-attribute. IncludeActivityIds - Includes TraceId + SpanId + ParentId from System.Diagnostics.Activity.Current Introduced with NLog.Extensions.Logging ver. 6.1.3 - Simulates ActivityTrackingOptions.TraceId | ActivityTrackingOptions.SpanId | ActivityTrackingOptions.ParentId TimestampFormat - Override the format of the UTC Timestamp. Default = \"O\" IndentJson - Enables indent for JSON pretty format with newlines (From JsonLayout ). Default = false DottedRecursion - Flatten object-property-names (From JsonLayout ). Default = false Introduced with NLog.Extensions.Logging ver. 6.1.1","title":"Parameters"},{"location":"MicrosoftConsoleLayout/","text":"A specialized layout that renders like default Microsoft Console Logger with Microsoft AddConsole Formatter. Platforms Supported: All - Requires nuget-package NLog.Extensions.Logging Introduced with NLog.Extensions.Logging ver. 1.7.2 This would write: info: Microsoft.Hosting.Lifetime[0] Application started. Press CTRL-C to shut down. Parameters TimestampFormat - Override the format to output the LogEvent Timestamp. Default (null) means skip timestamp. Can be any argument accepted by DateTime.ToString(format) . Introduced with NLog.Extensions.Logging ver. 5.0 UseUtcTimestamp - Configure whether to use UTC timezone for the LogEvent Timestamp. Default false . Introduced with NLog.Extensions.Logging ver. 5.0 Notes MicrosoftConsoleJsonLayout is also available and matches Microsoft AddJsonConsole Formatter.","title":"MicrosoftConsoleLayout"},{"location":"MicrosoftConsoleLayout/#parameters","text":"TimestampFormat - Override the format to output the LogEvent Timestamp. Default (null) means skip timestamp. Can be any argument accepted by DateTime.ToString(format) . Introduced with NLog.Extensions.Logging ver. 5.0 UseUtcTimestamp - Configure whether to use UTC timezone for the LogEvent Timestamp. Default false . Introduced with NLog.Extensions.Logging ver. 5.0","title":"Parameters"},{"location":"MicrosoftConsoleLayout/#notes","text":"MicrosoftConsoleJsonLayout is also available and matches Microsoft AddJsonConsole Formatter.","title":"Notes"},{"location":"MicrosoftILogger-Target/","text":"Forwards messages to Microsoft Extensions Logging (MEL) ILogger-interface. Introduced with NLog.Extensions.Logging ver. 1.5.0 Target can be used in Azure functions for capturing output from existing components that already uses NLog Loggers. Target can also be used for transforming standard log-messages into Json-output. Configuration Parameters EventId - Layout for rendering ILogger EventId Layout EventName - Layout for rendering ILogger EventName Layout includeMdlc - Include contents of the async MDLC-Layout-Renderer dictionary. Boolean ContextProperties - Collection of additional context properties Name - Name of context property Layout - Value for the context property Layout Example var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger); var nlogConfig = new NLog.Config.LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(loggerTarget); NLog.LogManager.Configuration = nlogConfig; var nlogLogger = NLog.LogManager.GetCurrentClassLogger(); nlogLogger.Info(\"Hello {planet}\", \"Earth\"); Example with extra context properties var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger); loggerTarget.IncludeMdlc = true; loggerTarget.ContextProperties.Add(new TargetPropertyWithContext(\"threadid\", \"${threadid}\")); loggerTarget.ContextProperties.Add(new TargetPropertyWithContext(\"hostname\", \"${hostname}\")); var nlogConfig = new NLog.Config.LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(loggerTarget); NLog.LogManager.Configuration = nlogConfig; var nlogLogger = NLog.LogManager.GetCurrentClassLogger(); using (NLog.MappedDiagnosticsLogicalContext.SetScoped(\"TraceId\", Guid.NewGuid()) { nlogLogger.Info(\"Hello {planet}\", \"Earth\"); } Example with JsonLayout var jsonLayout = new NLog.Layouts.JsonLayout(); jsonLayout.IncludeEventProperties = true; var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger) { Layout = jsonLayout }; var nlogConfig = new NLog.Config.LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(loggerTarget); NLog.LogManager.Configuration = nlogConfig; var nlogLogger = NLog.LogManager.GetCurrentClassLogger(); nlogLogger.Info(\"Hello {planet}\", \"Earth\");","title":"MicrosoftILogger Target"},{"location":"MicrosoftILogger-Target/#configuration-parameters","text":"EventId - Layout for rendering ILogger EventId Layout EventName - Layout for rendering ILogger EventName Layout includeMdlc - Include contents of the async MDLC-Layout-Renderer dictionary. Boolean ContextProperties - Collection of additional context properties Name - Name of context property Layout - Value for the context property Layout","title":"Configuration Parameters"},{"location":"MicrosoftILogger-Target/#example","text":"var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger); var nlogConfig = new NLog.Config.LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(loggerTarget); NLog.LogManager.Configuration = nlogConfig; var nlogLogger = NLog.LogManager.GetCurrentClassLogger(); nlogLogger.Info(\"Hello {planet}\", \"Earth\");","title":"Example"},{"location":"MicrosoftILogger-Target/#example-with-extra-context-properties","text":"var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger); loggerTarget.IncludeMdlc = true; loggerTarget.ContextProperties.Add(new TargetPropertyWithContext(\"threadid\", \"${threadid}\")); loggerTarget.ContextProperties.Add(new TargetPropertyWithContext(\"hostname\", \"${hostname}\")); var nlogConfig = new NLog.Config.LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(loggerTarget); NLog.LogManager.Configuration = nlogConfig; var nlogLogger = NLog.LogManager.GetCurrentClassLogger(); using (NLog.MappedDiagnosticsLogicalContext.SetScoped(\"TraceId\", Guid.NewGuid()) { nlogLogger.Info(\"Hello {planet}\", \"Earth\"); }","title":"Example with extra context properties"},{"location":"MicrosoftILogger-Target/#example-with-jsonlayout","text":"var jsonLayout = new NLog.Layouts.JsonLayout(); jsonLayout.IncludeEventProperties = true; var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger) { Layout = jsonLayout }; var nlogConfig = new NLog.Config.LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(loggerTarget); NLog.LogManager.Configuration = nlogConfig; var nlogLogger = NLog.LogManager.GetCurrentClassLogger(); nlogLogger.Info(\"Hello {planet}\", \"Earth\");","title":"Example with JsonLayout"},{"location":"NDC-Layout-Renderer/","text":"\u26a0\ufe0f NLog 5.0 introduces ScopeContext that replaces NDLC + NDC Nested Diagnostics Context - a thread-local structure that keeps a stack of strings and provides methods to output them in layouts. Platforms Supported: All NDC is considered legacy, and instead is recommended to use NDLC-Layout-Renderer that includes support for async Tasks. See also NLog Context Configuration Syntax ${ndc:bottomFrames=Integer:topFrames=Integer:separator=String} Parameters Rendering Options bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer . Default -1 . topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer . Default -1 separator - Separator to be used for concatenating nested diagnostics context output. string . Default (space) Examples One level NestedDiagnosticsContext.Push(\"entering method X\"); ... // log here NestedDiagnosticsContext.Pop(); //leaving methods Then in the log config: ${ndc} logs entering method X if logged between push() and pop() Multiple levels c# NestedDiagnosticsContext.Push(\"entering method X1\"); NestedDiagnosticsContext.Push(\"entering method X2\"); ... // log here NestedDiagnosticsContext.Pop(); //leaving method X2 NestedDiagnosticsContext.Pop(); //leaving method X1 logs entering method X1 entering method X2","title":"NDC Layout Renderer"},{"location":"NDC-Layout-Renderer/#configuration-syntax","text":"${ndc:bottomFrames=Integer:topFrames=Integer:separator=String}","title":"Configuration Syntax"},{"location":"NDC-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"NDC-Layout-Renderer/#rendering-options","text":"bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer . Default -1 . topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer . Default -1 separator - Separator to be used for concatenating nested diagnostics context output. string . Default (space)","title":"Rendering Options"},{"location":"NDC-Layout-Renderer/#examples","text":"","title":"Examples"},{"location":"NDC-Layout-Renderer/#one-level","text":"NestedDiagnosticsContext.Push(\"entering method X\"); ... // log here NestedDiagnosticsContext.Pop(); //leaving methods Then in the log config: ${ndc} logs entering method X if logged between push() and pop()","title":"One level"},{"location":"NDC-Layout-Renderer/#multiple-levels","text":"c# NestedDiagnosticsContext.Push(\"entering method X1\"); NestedDiagnosticsContext.Push(\"entering method X2\"); ... // log here NestedDiagnosticsContext.Pop(); //leaving method X2 NestedDiagnosticsContext.Pop(); //leaving method X1 logs entering method X1 entering method X2","title":"Multiple levels"},{"location":"NDLC-Layout-Renderer/","text":"\u26a0\ufe0f NLog 5.0 introduces ScopeContext that replaces NDLC + NDC Nested Diagnostics Logical Context (NDLC) acts like a stack of string, that are stored in an Async-Local structure (Similar to \"Thread Context Stack\" or \"Nested Diagnostic Context\" or in Log4j). It is the async version of NDC-Layout-Renderer Platforms Supported: All Introduced in NLog 4.4.1 It enables one to assign a scope-name to the active scope (Ex. a request method-name). Then all logger-events created within the scoped logical context, can automatically capture the scope-name without needing to specify it with each LogEvent. The specified scope states will automatically flow together with async Tasks. See also NLog Context . Configuration Syntax ${ndlc:bottomFrames=Integer:topFrames=Integer:separator=String} Parameters Rendering Options bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer . Default -1 . topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer . Default -1 separator - Separator to be used for concatenating nested diagnostics context output. string . Default (space) Examples using (NLog.NestedDiagnosticsLogicalContext.Push(\"Outer Scope\")) { Logger.Info(\"Hello Outer\"); await InnerOperationAsync(); } static async Task InnerOperationAsync() { using (NLog.NestedDiagnosticsLogicalContext.Push(\"Inner Scope\")) { Logger.Info(\"Hello Inner\"); await Task.Yield(); } }","title":"NDLC Layout Renderer"},{"location":"NDLC-Layout-Renderer/#configuration-syntax","text":"${ndlc:bottomFrames=Integer:topFrames=Integer:separator=String}","title":"Configuration Syntax"},{"location":"NDLC-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"NDLC-Layout-Renderer/#rendering-options","text":"bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer . Default -1 . topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer . Default -1 separator - Separator to be used for concatenating nested diagnostics context output. string . Default (space)","title":"Rendering Options"},{"location":"NDLC-Layout-Renderer/#examples","text":"using (NLog.NestedDiagnosticsLogicalContext.Push(\"Outer Scope\")) { Logger.Info(\"Hello Outer\"); await InnerOperationAsync(); } static async Task InnerOperationAsync() { using (NLog.NestedDiagnosticsLogicalContext.Push(\"Inner Scope\")) { Logger.Info(\"Hello Inner\"); await Task.Yield(); } }","title":"Examples"},{"location":"NLog-Install/","text":"Installing NLog \u2139\ufe0f For .NET Core Console. Use: Getting started with .NET Core \u2139\ufe0f For ASP.NET Core. Use: Getting started with ASP.NET Core Standard install Install the latest NLog from NuGet. Setup initial NLog.config xml-file Example NLog.config can be downloaded and just added to your main application project. Set \"Copy To Output Directory\" to \"Copy if newer\" for the NLog.config . That's it, you can now compile and run your application and it will be able to use NLog. Tutorial Next step, see Tutorial Troubleshooting If something is not working as expected then check here: * Troubleshooting Configuration * Troubleshooting Logging * Check Internal Logging * FAQ * External articles and tutorials","title":"NLog Install"},{"location":"NLog-Install/#installing-nlog","text":"\u2139\ufe0f For .NET Core Console. Use: Getting started with .NET Core \u2139\ufe0f For ASP.NET Core. Use: Getting started with ASP.NET Core Standard install Install the latest NLog from NuGet. Setup initial NLog.config xml-file Example NLog.config can be downloaded and just added to your main application project. Set \"Copy To Output Directory\" to \"Copy if newer\" for the NLog.config . That's it, you can now compile and run your application and it will be able to use NLog.","title":"Installing NLog"},{"location":"NLog-Install/#tutorial","text":"Next step, see Tutorial","title":"Tutorial"},{"location":"NLog-Install/#troubleshooting","text":"If something is not working as expected then check here: * Troubleshooting Configuration * Troubleshooting Logging * Check Internal Logging * FAQ * External articles and tutorials","title":"Troubleshooting"},{"location":"NLog-Trace-Listener-for-System-Diagnostics-Trace/","text":"NLogTraceListener Captures output from System Diagnostics Trace and redirects to NLog Targets. Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6 Attributes DisableFlush - Ignore flush operations from System.Diagnostics.Trace (Default = True) DefaultLogLevel - Use this default LogLevel for all LogEvents without any LogLevel. ForceLogLevel - Always use this LogLevel for all LogEvents (independent on the one provided). AutoLoggerName - Always capture StackTrace for each LogEvent and resolve Logger-name from callsite (Default = False) Example config Update app.config to redirect from the WCF ServiceModel-source to NLog Target output: and Example from code: System.Diagnostics.Trace.Listeners.Clear(); System.Diagnostics.Trace.Listeners.Add(new NLog.NLogTraceListener { Name = \"NLog\" }); System.Diagnostics.Trace.WriteLine(\"Hello World\"); Performance Optimizations NLogTraceListener is threadsafe and supports multithreading. To improve concurrency then ensure useGlobalLock is false (Default = true). See also LowLevelDesign.org - Case of deadlock NLogTraceListener does not need help with flushing, since this is handled automatically by the NLog engine. To improve performance then ensure autoflush is false (Default = false). StackOverflow Pitfall If having setup NLogTraceListener and at the same time using custom NLog Target that depends on System.Diagnostics.Trace for diagnostics tracing, then one can experience StackOverflowException . Since it is just like calling NLog Logger from NLog Target, which is also forbidden. Possible solution is to setup filtering of the particular Trace-source, so it doesn't become a recursive loop.","title":"NLogTraceListener"},{"location":"NLog-Trace-Listener-for-System-Diagnostics-Trace/#nlogtracelistener","text":"Captures output from System Diagnostics Trace and redirects to NLog Targets. Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6","title":"NLogTraceListener"},{"location":"NLog-Trace-Listener-for-System-Diagnostics-Trace/#attributes","text":"DisableFlush - Ignore flush operations from System.Diagnostics.Trace (Default = True) DefaultLogLevel - Use this default LogLevel for all LogEvents without any LogLevel. ForceLogLevel - Always use this LogLevel for all LogEvents (independent on the one provided). AutoLoggerName - Always capture StackTrace for each LogEvent and resolve Logger-name from callsite (Default = False)","title":"Attributes"},{"location":"NLog-Trace-Listener-for-System-Diagnostics-Trace/#example-config","text":"Update app.config to redirect from the WCF ServiceModel-source to NLog Target output: and ","title":"Example config"},{"location":"NLog-Trace-Listener-for-System-Diagnostics-Trace/#example-from-code","text":"System.Diagnostics.Trace.Listeners.Clear(); System.Diagnostics.Trace.Listeners.Add(new NLog.NLogTraceListener { Name = \"NLog\" }); System.Diagnostics.Trace.WriteLine(\"Hello World\");","title":"Example from code:"},{"location":"NLog-Trace-Listener-for-System-Diagnostics-Trace/#performance-optimizations","text":"NLogTraceListener is threadsafe and supports multithreading. To improve concurrency then ensure useGlobalLock is false (Default = true). See also LowLevelDesign.org - Case of deadlock NLogTraceListener does not need help with flushing, since this is handled automatically by the NLog engine. To improve performance then ensure autoflush is false (Default = false). ","title":"Performance Optimizations"},{"location":"NLog-Trace-Listener-for-System-Diagnostics-Trace/#stackoverflow-pitfall","text":"If having setup NLogTraceListener and at the same time using custom NLog Target that depends on System.Diagnostics.Trace for diagnostics tracing, then one can experience StackOverflowException . Since it is just like calling NLog Logger from NLog Target, which is also forbidden. Possible solution is to setup filtering of the particular Trace-source, so it doesn't become a recursive loop.","title":"StackOverflow Pitfall"},{"location":"NLog-config-Example/","text":"Save this file as \"nlog.config\" in the root of your application (Add to project with Copy if newer ) Simple config example: autoReload=\"true\" internalLogLevel=\"Warn\" internalLogFile=\"${basedir}/nlog-internal.txt\"> Advanced config example: ```xml autoReload=\"true\" internalLogLevel=\"Warn\" internalLogFile=\"${basedir}/logs/nlog-internal.txt\"> INSERT INTO [LogEntries](TimeStamp, Message, Level, Logger) VALUES(getutcdate(), @msg, @level, @logger) System.Data.SqlClient server=.\\SQLEXPRESS;database=MyLogs;integrated security=sspi CREATE DATABASE MyLogs server=.\\SQLEXPRESS;database=master;integrated security=sspi true CREATE TABLE LogEntries( id int primary key not null identity(1,1), TimeStamp datetime2, Message nvarchar(max), level nvarchar(10), logger nvarchar(128)) DROP DATABASE MyLogs server=.\\SQLEXPRESS;database=master;integrated security=sspi true level >= LogLevel.Info = LogLevel.Error\" filter=\"level >= LogLevel.Trace\" /> ````","title":"NLog config Example"},{"location":"NLog-config-Example/#simple-config-example","text":" autoReload=\"true\" internalLogLevel=\"Warn\" internalLogFile=\"${basedir}/nlog-internal.txt\"> ","title":"Simple config example:"},{"location":"NLog-config-Example/#advanced-config-example","text":"```xml autoReload=\"true\" internalLogLevel=\"Warn\" internalLogFile=\"${basedir}/logs/nlog-internal.txt\"> INSERT INTO [LogEntries](TimeStamp, Message, Level, Logger) VALUES(getutcdate(), @msg, @level, @logger) System.Data.SqlClient server=.\\SQLEXPRESS;database=MyLogs;integrated security=sspi CREATE DATABASE MyLogs server=.\\SQLEXPRESS;database=master;integrated security=sspi true CREATE TABLE LogEntries( id int primary key not null identity(1,1), TimeStamp datetime2, Message nvarchar(max), level nvarchar(10), logger nvarchar(128)) DROP DATABASE MyLogs server=.\\SQLEXPRESS;database=master;integrated security=sspi true level >= LogLevel.Info = LogLevel.Error\" filter=\"level >= LogLevel.Trace\" /> ````","title":"Advanced config example:"},{"location":"NLogDir-Layout-Renderer/","text":"The directory where NLog.dll is located. Platforms Supported: All Configuration Syntax ${nlogdir:dir=String:file=String} Parameters Advanced Options dir - Name of the directory to be Path.Combine()'d with the directory name. file - Name of the file to be Path.Combine()'d with the directory name.","title":"NLogDir Layout Renderer"},{"location":"NLogDir-Layout-Renderer/#configuration-syntax","text":"${nlogdir:dir=String:file=String}","title":"Configuration Syntax"},{"location":"NLogDir-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"NLogDir-Layout-Renderer/#advanced-options","text":"dir - Name of the directory to be Path.Combine()'d with the directory name. file - Name of the file to be Path.Combine()'d with the directory name.","title":"Advanced Options"},{"location":"NLogViewer-target/","text":"Sends log messages to the remote instance of Log4J XML Viewer. Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6 \u26a0\ufe0f This target uses an non-standard Log4J-format that includes special NLog-schema-values ( IncludeNLogData=true ). For correct Log4J-xml-format, then use Chainsaw-Target \u26a0\ufe0f This target is not related to the different WPF-Controls like dojo90 NLogViewer or erizet NlogViewer . This target inherits from the Network Target , and so it has also all the properties of the Network Target available. Using the Log4JXmlEventLayout to produce Log4J XML output. \u2139\ufe0f NLog v6 has merged NLogViewer-Target and ChainSaw-Target into Log4JXml-Target Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Introduced in 4.3.8. Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default) Connection Options connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb For SOAP-based webservice support over HTTP use WebService target. keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . Introduced with NLog v4.2.1. Default became 16 with NLog v4.5 (Before 0 ) onConnectionOverflow - Action that should be taken if the will be more connections than maxConnections . Introduced with NLog v4.2.1. Default became Block with NLog v4.5 (Before AllowNewConnnection ) Possible values: * AllowNewConnnection - Just allow it. * Block - Block until there's more room in the queue. (default) * DiscardMessage - Discard the connection item. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 (Before NLog 5.0 the default was 0) NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. NLog 5.0.0 enabled queue-support for UDP. onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Introduced with NLog 5.0 Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. Payload Options includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Default: false . includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Default: false . includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: true . IncludeEventProperties - Include all events properties of a logevent? Default: false . Before NLog 5.0 option was named IncludeAllProperties IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 4.5 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 parameter - Additional context properties that should be included. name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required. Example Available Log4J-XML viewers (See also LogViewer Tools ) - Sentinel - Avoid using TCP since not complete. - Log2Console - Logazmic - Loginator - Logbert - LogViewer - Lilith - OtrosLogViewer Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this: ","title":"NLogViewer target"},{"location":"NLogViewer-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"NLogViewer-target/#parameters","text":"","title":"Parameters"},{"location":"NLogViewer-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"NLogViewer-target/#layout-options","text":"layout - Instance of Log4JXmlEventLayout that is used to format log messages. Layout Default: Log4JXmlEventLayout encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Introduced in 4.3.8. Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default)","title":"Layout Options"},{"location":"NLogViewer-target/#connection-options","text":"connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb For SOAP-based webservice support over HTTP use WebService target. keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . Introduced with NLog v4.2.1. Default became 16 with NLog v4.5 (Before 0 ) onConnectionOverflow - Action that should be taken if the will be more connections than maxConnections . Introduced with NLog v4.2.1. Default became Block with NLog v4.5 (Before AllowNewConnnection ) Possible values: * AllowNewConnnection - Just allow it. * Block - Block until there's more room in the queue. (default) * DiscardMessage - Discard the connection item. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 (Before NLog 5.0 the default was 0) NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. NLog 5.0.0 enabled queue-support for UDP. onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Introduced with NLog 5.0 Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit.","title":"Connection Options"},{"location":"NLogViewer-target/#payload-options","text":"includeSourceInfo - Indicates whether to include source info (file name and line number) in the information sent over the network. Default: false . includeCallSite - Indicates whether to include call site (class and method name) in the information sent over the network. Default: false . includeNLogData - Indicates whether to include NLog-specific extensions to log4j schema. Default: true . IncludeEventProperties - Include all events properties of a logevent? Default: false . Before NLog 5.0 option was named IncludeAllProperties IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc IncludeScopeNested - Indicates whether to include ScopeNested-Layout-Renderer as NDC. Default: false . Before NLog 5.0 option was named IncludeNdlc ScopeNestedSeparator - NDC item separator. Default: Before NLog 5.0 option was named NdlcItemSeparator includeNdc - Indicates whether to include ScopeNested-Layout-Renderer . Default: false . ndcItemSeparator - NDC item separator. Default: appInfo - AppInfo field. By default it's the friendly name of the current AppDomain. loggerName - Logger field. By default it's the output of ${logger} Introduced in NLog 4.5 formattedMessage - Message field. By default it's the output of ${message} Introduced in NLog 5.3 parameter - Additional context properties that should be included. name - Name of Parameter. Required. layout - The layout for the Parameter-Value. Required.","title":"Payload Options"},{"location":"NLogViewer-target/#example","text":" Available Log4J-XML viewers (See also LogViewer Tools ) - Sentinel - Avoid using TCP since not complete. - Log2Console - Logazmic - Loginator - Logbert - LogViewer - Lilith - OtrosLogViewer Notice that most Log4J-XML viewers will drop messages and stall when NLog sends messages at full speed. One can consider to throttle NLog like this: ","title":"Example"},{"location":"NdlcTiming-Layout-Renderer/","text":"NDLC allows one to give a scope name for an operation that can be async. When the scope begins then it automatically captures a timestamp. This can be used to show duration of the active scope. Platforms Supported: All Introduced in NLog 4.5 NLog 5.0 introduces ScopeContext that unifies MDLC + MDC into a single context. See also NLog Context . Configuration Syntax ${ndlctiming:currentScope=Boolean:scopeBeginTime=Boolean:format=String} Parameters Rendering Options currentScope - Whether to only include the duration of the last scope created. Boolean . Default False . scopeBeginTime - Whether to just display the scope creation time, and not the duration. Boolean . Default False format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format) . string . Default null","title":"NdlcTiming Layout Renderer"},{"location":"NdlcTiming-Layout-Renderer/#configuration-syntax","text":"${ndlctiming:currentScope=Boolean:scopeBeginTime=Boolean:format=String}","title":"Configuration Syntax"},{"location":"NdlcTiming-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"NdlcTiming-Layout-Renderer/#rendering-options","text":"currentScope - Whether to only include the duration of the last scope created. Boolean . Default False . scopeBeginTime - Whether to just display the scope creation time, and not the duration. Boolean . Default False format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format) . string . Default null","title":"Rendering Options"},{"location":"Network-target/","text":"Sends log messages over the network using Tcp / Udp / Tls / Http / Https Platforms Supported: All - Requires nuget-package NLog.Targets.Network since NLog v6 For SOAP-based webservice support over HTTP and HTTPS use WebService target , and if needing batch-support to HTTP/HTTPS-EndPoint use NLog.Targets.HttpClient . Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Payload Options layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Introduced in 4.3.8. Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. compress - Use compression to reduce message size. Default: None Introduced with NLog 5.0 None - No compression (Default) GZip - GZip with optimal compression GZipFast - GZip with fastest compression compressMinBytes - Use compression only when message size is higher than limit to reduce overhead in cpu-usage and additional headers. Default: 0 Introduced with NLog 5.0 maxMessageSize - Maximum message size in bytes. Integer Default: 65000 Notice when using UDP and the message-size exceeds MTU-size (default 1500 bytes), then IP fragmentation will happen. If network-switch/router has DontFragment enabled, then it will drop large network packets. Usually UDP is only used on local network since no authentication or security, and the network-switch seldom has DontFragment enabled (or under your control to be configured). onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default) Connection Options address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Not used for stateless protocols (= http, https) Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections when keepConnection = false. 0 = no limit. Integer Default: 100 (Before NLog 5.0 the default was 0) Introduced in NLog 4.2.1 onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Introduced in NLog 4.2.1. Possible enum values: * Discard - Discard new messages when reaching limit (Default) (Before NLog 5.0 it was enum value DiscardMessage ) * Grow - Send message and ignore limit (Before NLog 5.0 it was enum value AllowNewConnnection ) * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 (Before NLog 5.0 the default was 0) NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. NLog 5.0.0 enabled queue-support for UDP. onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Introduced with NLog 5.0 Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) Introduced in NLog 4.6 SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) Introduced in NLog 5.3.4 NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. Introduced in NLog 5.5. Before NLog 6.0 it was default = false. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Introduced in NLog 4.6 Possible values (combination allowed, comma separated): * None - No SSL/TLS is used * Default - Accepts Tls or Ssl3 * Ssl2 - really not recommended * Ssl3 - not recommended * Tls - TLS 1.0 * Tls11 - TLS 1.1 * Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) Introduced in NLog.Targets.Network v6.0 SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile Introduced in NLog.Targets.Network v6.0 SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6","title":"Network target"},{"location":"Network-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Network-target/#parameters","text":"","title":"Parameters"},{"location":"Network-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Network-target/#payload-options","text":"layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Introduced in 4.3.8. Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. compress - Use compression to reduce message size. Default: None Introduced with NLog 5.0 None - No compression (Default) GZip - GZip with optimal compression GZipFast - GZip with fastest compression compressMinBytes - Use compression only when message size is higher than limit to reduce overhead in cpu-usage and additional headers. Default: 0 Introduced with NLog 5.0 maxMessageSize - Maximum message size in bytes. Integer Default: 65000 Notice when using UDP and the message-size exceeds MTU-size (default 1500 bytes), then IP fragmentation will happen. If network-switch/router has DontFragment enabled, then it will drop large network packets. Usually UDP is only used on local network since no authentication or security, and the network-switch seldom has DontFragment enabled (or under your control to be configured). onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default)","title":"Payload Options"},{"location":"Network-target/#connection-options","text":"address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Not used for stateless protocols (= http, https) Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections when keepConnection = false. 0 = no limit. Integer Default: 100 (Before NLog 5.0 the default was 0) Introduced in NLog 4.2.1 onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Introduced in NLog 4.2.1. Possible enum values: * Discard - Discard new messages when reaching limit (Default) (Before NLog 5.0 it was enum value DiscardMessage ) * Grow - Send message and ignore limit (Before NLog 5.0 it was enum value AllowNewConnnection ) * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 (Before NLog 5.0 the default was 0) NLog 4.6.7 enabled queue-support for http/https and NLog 4.7.1 activated this setting for http/https. NLog 5.0.0 enabled queue-support for UDP. onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Introduced with NLog 5.0 Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) Introduced in NLog 4.6 SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) Introduced in NLog 5.3.4 NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. Introduced in NLog 5.5. Before NLog 6.0 it was default = false. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Introduced in NLog 4.6 Possible values (combination allowed, comma separated): * None - No SSL/TLS is used * Default - Accepts Tls or Ssl3 * Ssl2 - really not recommended * Ssl3 - not recommended * Tls - TLS 1.0 * Tls11 - TLS 1.1 * Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) Introduced in NLog.Targets.Network v6.0 SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile Introduced in NLog.Targets.Network v6.0 SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6","title":"Connection Options"},{"location":"Newline-Layout-Renderer/","text":"A newline literal. Platforms Supported: All Configuration Syntax ${newline}","title":"Newline Layout Renderer"},{"location":"Newline-Layout-Renderer/#configuration-syntax","text":"${newline}","title":"Configuration Syntax"},{"location":"NoRawValue-layout-renderer/","text":"Prevents the output of another layout renderer to be treated as raw value. Platforms Supported: All Introduced in NLog 4.6 Some NLog targets are able to extract the raw value directly from the layout renderer without first rendering as string. Specifying norawvalue=true will force rendering as string. Configuration Syntax ${date:format=yyyy-MM-dd:norawvalue=true}","title":"NoRawValue layout renderer"},{"location":"NoRawValue-layout-renderer/#configuration-syntax","text":"${date:format=yyyy-MM-dd:norawvalue=true}","title":"Configuration Syntax"},{"location":"Null-target/","text":"Discards log messages. Used mainly for debugging and benchmarking. Platforms Supported: All Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options formatMessage - Indicates whether to perform layout calculation. Boolean Default: False layout - Layout used to format log messages. Boolean Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} Example This example is useful for testing the performance of the NLog engine. Logging rule without any writeTo= option is much faster way to do filtering (Zero allocation). ","title":"Null target"},{"location":"Null-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Null-target/#parameters","text":"","title":"Parameters"},{"location":"Null-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Null-target/#layout-options","text":"formatMessage - Indicates whether to perform layout calculation. Boolean Default: False layout - Layout used to format log messages. Boolean Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}","title":"Layout Options"},{"location":"Null-target/#example","text":"This example is useful for testing the performance of the NLog engine. Logging rule without any writeTo= option is much faster way to do filtering (Zero allocation). ","title":"Example"},{"location":"ObjectPath-Layout-Renderer/","text":"Render a property of an object. Introducted in NLog 4.6.7 Platforms Supported: All Configuration Syntax ${object-path:${exception}:path=String:Format=String:Culture=String} ${exception:objectpath=String} // Ambient way Parameters Rendering Options objectpath - Path to the property. Nested properties are supported. Arrays aren't supported. format - Format when rendering. culture - Culture code used for formatting. Example Assume we catch new ExternalException(\"Exception with errorCode\", 5000) ${exception:objectpath=HResult} // results in 5000 ${object-path:${exception}:path=HResult:Culture=NL-nl:format=N2}\"; // results in 5.000,00","title":"ObjectPath Layout Renderer"},{"location":"ObjectPath-Layout-Renderer/#configuration-syntax","text":"${object-path:${exception}:path=String:Format=String:Culture=String} ${exception:objectpath=String} // Ambient way","title":"Configuration Syntax"},{"location":"ObjectPath-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"ObjectPath-Layout-Renderer/#rendering-options","text":"objectpath - Path to the property. Nested properties are supported. Arrays aren't supported. format - Format when rendering. culture - Culture code used for formatting.","title":"Rendering Options"},{"location":"ObjectPath-Layout-Renderer/#example","text":"Assume we catch new ExternalException(\"Exception with errorCode\", 5000) ${exception:objectpath=HResult} // results in 5000 ${object-path:${exception}:path=HResult:Culture=NL-nl:format=N2}\"; // results in 5.000,00","title":"Example"},{"location":"OnException-Layout-Renderer/","text":"Only outputs the inner layout when exception has been defined for log message. Platforms Supported: All Configuration Syntax ${onexception:inner=Layout} Parameters Transformation Options inner - Wrapped layout. Layout else - Layout if the condition is not true (introduced in NLog 5.0.5)","title":"OnException Layout Renderer"},{"location":"OnException-Layout-Renderer/#configuration-syntax","text":"${onexception:inner=Layout}","title":"Configuration Syntax"},{"location":"OnException-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"OnException-Layout-Renderer/#transformation-options","text":"inner - Wrapped layout. Layout else - Layout if the condition is not true (introduced in NLog 5.0.5)","title":"Transformation Options"},{"location":"OnHasProperties-Layout-Renderer/","text":"Only outputs the inner layout when event properties from structured logging are included with the logevent. Platforms Supported: All Introduced with NLog 4.7 Configuration Syntax ${onHasProperties:inner=Layout} Parameters Transformation Options inner - Wrapped layout. Layout else - Layout if the condition is not true (introduced in NLog 5.0.5) Example: ${onHasProperties:, Properties\\: ${all-event-properties}}","title":"OnHasProperties Layout Renderer"},{"location":"OnHasProperties-Layout-Renderer/#configuration-syntax","text":"${onHasProperties:inner=Layout}","title":"Configuration Syntax"},{"location":"OnHasProperties-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"OnHasProperties-Layout-Renderer/#transformation-options","text":"inner - Wrapped layout. Layout else - Layout if the condition is not true (introduced in NLog 5.0.5)","title":"Transformation Options"},{"location":"OnHasProperties-Layout-Renderer/#example","text":"${onHasProperties:, Properties\\: ${all-event-properties}}","title":"Example:"},{"location":"OutputDebugString-target/","text":"Outputs log messages through the OutputDebugString Win32 API. That can be monitored using DebugView or Harvester Platforms Supported: Limited - Requires Windows and requires nuget-package NLog.OutputDebugString since NLog 5.0 Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Layout Options layout - Layout used to format log messages. Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} header - Layout used to format header-output when initializing. Layout Introduced with NLog 5.0 footer - Layout used to format footer-output when closing. Layout Introduced with NLog 5.0 Notes Alternative targets for diagnostic output: - Trace-target for output to System.Diagnostics.Trace - DebugSystem-target for output to System.Diagnostics.Debug - Debugger-target for output to System.Diagnostics.Debugger.Log","title":"OutputDebugString target"},{"location":"OutputDebugString-target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"OutputDebugString-target/#parameters","text":"","title":"Parameters"},{"location":"OutputDebugString-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"OutputDebugString-target/#layout-options","text":"layout - Layout used to format log messages. Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} header - Layout used to format header-output when initializing. Layout Introduced with NLog 5.0 footer - Layout used to format footer-output when closing. Layout Introduced with NLog 5.0","title":"Layout Options"},{"location":"OutputDebugString-target/#notes","text":"Alternative targets for diagnostic output: - Trace-target for output to System.Diagnostics.Trace - DebugSystem-target for output to System.Diagnostics.Debug - Debugger-target for output to System.Diagnostics.Debugger.Log","title":"Notes"},{"location":"Pad-Layout-Renderer/","text":"Applies padding to another layout output. Platforms Supported: All Configuration Syntax ${pad:padCharacter=Char:padding=Integer:fixedLength=Boolean :inner=Layout:alignmentOnTruncation=PaddingHorizontalAlignment} or by using ambient property to modify output of other layout renderer: ${other:padding=5} Parameters Transformation Options padCharacter - Padding character. Char Default: (space character) padding - Number of characters to pad the output to. Positive padding values cause left padding, negative values cause right padding to the desired width. Integer fixedLength - Indicates whether to trim the rendered text to the absolute value of the padding length. Boolean Default: False inner - Wrapped layout. Layout alignmentOnTruncation - Indicates whether a value that has been truncated due to fixedLength=true is aligned to the left (characters removed from the right) or right (characters removed from the left). This is independent of the alignment applied when padding shorter strings out to padding characters. This property was introduced in NLog 4.0. Earlier versions always apply an alignment equivalent to alignmentOnTruncation=left . PaddingHorizontalAlignment Default: Left","title":"Pad Layout Renderer"},{"location":"Pad-Layout-Renderer/#configuration-syntax","text":"${pad:padCharacter=Char:padding=Integer:fixedLength=Boolean :inner=Layout:alignmentOnTruncation=PaddingHorizontalAlignment} or by using ambient property to modify output of other layout renderer: ${other:padding=5}","title":"Configuration Syntax"},{"location":"Pad-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Pad-Layout-Renderer/#transformation-options","text":"padCharacter - Padding character. Char Default: (space character) padding - Number of characters to pad the output to. Positive padding values cause left padding, negative values cause right padding to the desired width. Integer fixedLength - Indicates whether to trim the rendered text to the absolute value of the padding length. Boolean Default: False inner - Wrapped layout. Layout alignmentOnTruncation - Indicates whether a value that has been truncated due to fixedLength=true is aligned to the left (characters removed from the right) or right (characters removed from the left). This is independent of the alignment applied when padding shorter strings out to padding characters. This property was introduced in NLog 4.0. Earlier versions always apply an alignment equivalent to alignmentOnTruncation=left . PaddingHorizontalAlignment Default: Left","title":"Transformation Options"},{"location":"PerfCounter-target/","text":"PerformanceCounterTarget updates specified Windows Performance Counter on each write. Platforms Supported: Limited - Windows only and requires nuget-package NLog.PerformanceCounter since NLog 5.0 Configuration Syntax The actual Performance Counter can be created by Installing targets , or by using autoCreate=\"true\" . Read more about using the Configuration File . Parameters counterName - Name of the performance counter. Required. categoryName - Name of the performance counter category. Required. instanceName - Performance counter instance name. counterHelp - Counter help text. counterType - Performance counter type. Default: NumberOfItems32 Possible values: AverageBase AverageCount64 AverageTimer32 CounterDelta32 CounterDelta64 CounterMultiBase CounterMultiTimer CounterMultiTimer100Ns CounterMultiTimer100NsInverse CounterMultiTimerInverse CounterTimer CounterTimerInverse CountPerTimeInterval32 CountPerTimeInterval64 ElapsedTime NumberOfItems32 NumberOfItems64 NumberOfItemsHEX32 NumberOfItemsHEX64 RateOfCountsPerSecond32 RateOfCountsPerSecond64 RawBase RawFraction SampleBase SampleCounter SampleFraction Timer100Ns Timer100NsInverse autoCreate - Indicates whether performance counter should be automatically created. Default: false. incrementValue - The value by which to increment the counter. Layout. Default: 1. Introduced in NLog v4.2 Notes Alternative one can use NLog.ETW for writing to ETW EventCounter using EtwEventCounter -Target.","title":"PerfCounter target"},{"location":"PerfCounter-target/#configuration-syntax","text":" The actual Performance Counter can be created by Installing targets , or by using autoCreate=\"true\" . Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"PerfCounter-target/#parameters","text":"counterName - Name of the performance counter. Required. categoryName - Name of the performance counter category. Required. instanceName - Performance counter instance name. counterHelp - Counter help text. counterType - Performance counter type. Default: NumberOfItems32 Possible values: AverageBase AverageCount64 AverageTimer32 CounterDelta32 CounterDelta64 CounterMultiBase CounterMultiTimer CounterMultiTimer100Ns CounterMultiTimer100NsInverse CounterMultiTimerInverse CounterTimer CounterTimerInverse CountPerTimeInterval32 CountPerTimeInterval64 ElapsedTime NumberOfItems32 NumberOfItems64 NumberOfItemsHEX32 NumberOfItemsHEX64 RateOfCountsPerSecond32 RateOfCountsPerSecond64 RawBase RawFraction SampleBase SampleCounter SampleFraction Timer100Ns Timer100NsInverse autoCreate - Indicates whether performance counter should be automatically created. Default: false. incrementValue - The value by which to increment the counter. Layout. Default: 1. Introduced in NLog v4.2","title":"Parameters"},{"location":"PerfCounter-target/#notes","text":"Alternative one can use NLog.ETW for writing to ETW EventCounter using EtwEventCounter -Target.","title":"Notes"},{"location":"Performance/","text":"NLog has been created with performance in mind, and is optimized to have minimal impact on the actual application-code. It can easily handle 500.000 messages/sec, but if using NLog in ways not intended, then you might not get the expected performance. Logger optimizations When using the NLog Logger, then there are some things that affects optimal performance: Avoid constantly calling LogManager.GetLogger() and LogManager.GetCurrentClassLogger() , instead use static readonly variables. Defer message-formatting by not using string.format and string interpolation (Ex $\"Hello {world}\" ) but pass the arguments to the log method. Avoid logging synchronous to slow NLog targets (Ex. console or file), instead it is recommend to apply the AsyncWrapper . Conditional logging is recommended when creation of the log-message has an overhead, and logging is not always turned on. Defer message-formatting NLog has a strong focus on being able to defer the message-formatting. When using or AsyncWrapper target then the formatting and writing can be done by a background-thread. The async message-formatting requires that all parameters are immutable. To ensure that they don't change after having called the Logger (Ex logging an object and disposing the object afterwards should not log a disposed object). The NLog Logger (During the creation of LogEventInfo) checks whether all parameters are immutable / primitive. If one is complex-object, then message-formatting is not deferred. When having more than 5 parameters then it will skip the performance optimization, because checking the immutable state of the parameters has a cost. Notice when using Microsoft Extension Logging with NLog, then NLog is not able to perform this optimization, because Microsoft Extension Logging handles the message-parsing and -formatting upfront. Layout configuration Many NLog LayoutRenderers have little overhead, and allows deferring the layout logic to background-thread when enabled with (Activates AsyncWrapper target ). But if using NLog LayoutRenders that requires context capture of the current application-thread like ${threadid} , then the application-thread will get extra overhead to perform this context capture. This also happens with most ${aspnet-request} -layout-renderers as they have to extract values from the active HttpContext. If performance is very important then one should focus on using ${longdate} , ${logger} , ${level} , ${message} and ${event-properties} . One should be careful with using ${callsite} and ${stacktrace} that outputs the call-site of the application-thread, because NLog makes the application-thread capture its current StackTrace, which is very expensive. NLog 5.0 introduces a new fluent Logger-API , that support caller-member-attributes, and reduces the overhead from using ${callsite} . Conditional logging NLog Logger has very little overhead when LogLevel is not enabled for any targets. But it might be noticeable if running in a tight loop and doing almost nothing, besides calling NLog Logger. If having a complex logging statement, then one can consider checking if LogLevel is enabled before executing it: if (Logger.IsDebugEnabled) Logger.Debug(GenerateMassiveLogEvent()); Starting of NLog 4.0 it\u2019s possible to only include the Trace and Debug calls for DEBUG-builds. Instead of: Logger.Debug(\"entering method {0}\", methodname); Then use: Logger.ConditionalDebug(\"entering method {0}\", methodname); This call will be removed by the .Net compiler if the DEBUG conditional compilation symbol is not set \u2013 default for release build. InternalLogger overhead NLog Internal Logging is very useful for troubleshooting. To be alerted about potential logging issues, then one can enable internalLogLevel=\"Warn\" to get warnings and errors. During troubleshooting sessions then one might use internalLogLevel=\"Trace\" , but make sure to turn it off again when issue has been resolved. The InternalLogger is not written for performance, and will give a significant performance hit. Automatic Extension Loading NLog 4.0 automatically scans for assemblies that contains extensions for NLog at initial startup. This will automatically trigger loading of debugging symbols. This will be give the experience that NLog slows down the application startup. NLog 5.0 no longer scans for assemblies at startup because of the startup overhead, and also because it doesn't work with the new csproj . To skip the assembly scan for NLog v4, then execute this statement before loading NLog Config or creating NLog Logger: NLog.Config.ConfigurationItemFactory.Default = new NLog.Config.ConfigurationItemFactory(typeof(NLog.ILogger).GetTypeInfo().Assembly); Visual Studio Debugger pauses during NLog initialization Visual Studio is slow the first time when debugging application and having configured to load relevant debug symbol information. To avoid these pauses then one can configure Visual Studio to 'Enable Just My Code` It is a checkbox in Visual Studio Options. See Just my Code File Logging Performance Single process applications (in single AppDomain) can optimize performance by configuring the FileTarget attributes: - keepFileOpen = True - concurrentwrites = False See also FileTarget - Performance To avoid the blocking file write operation, then one can consider to wrap the FileTarget within a AsyncWrapper (Very important if using keepFileOpen = False). This will also optimize the writing to disk, as it will be done in batches. Be careful as the default behavior is to discard log operations if they come fast. So it is recommended to change the overflow-policy for non-network targets: ... Your File Targets Here ... Remember to Flush is very important, to ensure background threads have completed writing before application exit.","title":"Performance"},{"location":"Performance/#logger-optimizations","text":"When using the NLog Logger, then there are some things that affects optimal performance: Avoid constantly calling LogManager.GetLogger() and LogManager.GetCurrentClassLogger() , instead use static readonly variables. Defer message-formatting by not using string.format and string interpolation (Ex $\"Hello {world}\" ) but pass the arguments to the log method. Avoid logging synchronous to slow NLog targets (Ex. console or file), instead it is recommend to apply the AsyncWrapper . Conditional logging is recommended when creation of the log-message has an overhead, and logging is not always turned on.","title":"Logger optimizations"},{"location":"Performance/#defer-message-formatting","text":"NLog has a strong focus on being able to defer the message-formatting. When using or AsyncWrapper target then the formatting and writing can be done by a background-thread. The async message-formatting requires that all parameters are immutable. To ensure that they don't change after having called the Logger (Ex logging an object and disposing the object afterwards should not log a disposed object). The NLog Logger (During the creation of LogEventInfo) checks whether all parameters are immutable / primitive. If one is complex-object, then message-formatting is not deferred. When having more than 5 parameters then it will skip the performance optimization, because checking the immutable state of the parameters has a cost. Notice when using Microsoft Extension Logging with NLog, then NLog is not able to perform this optimization, because Microsoft Extension Logging handles the message-parsing and -formatting upfront.","title":"Defer message-formatting"},{"location":"Performance/#layout-configuration","text":"Many NLog LayoutRenderers have little overhead, and allows deferring the layout logic to background-thread when enabled with (Activates AsyncWrapper target ). But if using NLog LayoutRenders that requires context capture of the current application-thread like ${threadid} , then the application-thread will get extra overhead to perform this context capture. This also happens with most ${aspnet-request} -layout-renderers as they have to extract values from the active HttpContext. If performance is very important then one should focus on using ${longdate} , ${logger} , ${level} , ${message} and ${event-properties} . One should be careful with using ${callsite} and ${stacktrace} that outputs the call-site of the application-thread, because NLog makes the application-thread capture its current StackTrace, which is very expensive. NLog 5.0 introduces a new fluent Logger-API , that support caller-member-attributes, and reduces the overhead from using ${callsite} .","title":"Layout configuration"},{"location":"Performance/#conditional-logging","text":"NLog Logger has very little overhead when LogLevel is not enabled for any targets. But it might be noticeable if running in a tight loop and doing almost nothing, besides calling NLog Logger. If having a complex logging statement, then one can consider checking if LogLevel is enabled before executing it: if (Logger.IsDebugEnabled) Logger.Debug(GenerateMassiveLogEvent()); Starting of NLog 4.0 it\u2019s possible to only include the Trace and Debug calls for DEBUG-builds. Instead of: Logger.Debug(\"entering method {0}\", methodname); Then use: Logger.ConditionalDebug(\"entering method {0}\", methodname); This call will be removed by the .Net compiler if the DEBUG conditional compilation symbol is not set \u2013 default for release build.","title":"Conditional logging"},{"location":"Performance/#internallogger-overhead","text":"NLog Internal Logging is very useful for troubleshooting. To be alerted about potential logging issues, then one can enable internalLogLevel=\"Warn\" to get warnings and errors. During troubleshooting sessions then one might use internalLogLevel=\"Trace\" , but make sure to turn it off again when issue has been resolved. The InternalLogger is not written for performance, and will give a significant performance hit.","title":"InternalLogger overhead"},{"location":"Performance/#automatic-extension-loading","text":"NLog 4.0 automatically scans for assemblies that contains extensions for NLog at initial startup. This will automatically trigger loading of debugging symbols. This will be give the experience that NLog slows down the application startup. NLog 5.0 no longer scans for assemblies at startup because of the startup overhead, and also because it doesn't work with the new csproj . To skip the assembly scan for NLog v4, then execute this statement before loading NLog Config or creating NLog Logger: NLog.Config.ConfigurationItemFactory.Default = new NLog.Config.ConfigurationItemFactory(typeof(NLog.ILogger).GetTypeInfo().Assembly);","title":"Automatic Extension Loading"},{"location":"Performance/#visual-studio-debugger-pauses-during-nlog-initialization","text":"Visual Studio is slow the first time when debugging application and having configured to load relevant debug symbol information. To avoid these pauses then one can configure Visual Studio to 'Enable Just My Code` It is a checkbox in Visual Studio Options. See Just my Code","title":"Visual Studio Debugger pauses during NLog initialization"},{"location":"Performance/#file-logging-performance","text":"Single process applications (in single AppDomain) can optimize performance by configuring the FileTarget attributes: - keepFileOpen = True - concurrentwrites = False See also FileTarget - Performance To avoid the blocking file write operation, then one can consider to wrap the FileTarget within a AsyncWrapper (Very important if using keepFileOpen = False). This will also optimize the writing to disk, as it will be done in batches. Be careful as the default behavior is to discard log operations if they come fast. So it is recommended to change the overflow-policy for non-network targets: ... Your File Targets Here ... Remember to Flush is very important, to ensure background threads have completed writing before application exit.","title":"File Logging Performance"},{"location":"PerformanceCounter-Layout-Renderer/","text":"Render value retrieved from Windows Performance Counter. Platforms Supported: Limited - Windows only and requires nuget-package NLog.PerformanceCounter since NLog 5.0 Configuration Syntax ${performancecounter:Category=String:Counter=PerformanceCounterType:Instance=String :IncrementValue=Integer:MachineName:string format=String:culture=Culture} Parameters Performance Counter Options Counter - Name of the performance counter. Required. Category - Name of the counter category. Required. Instance - Name of the performance counter instance. Optional. NLog 4.6 will automatically use current process as Instance-Id when Category = \"Process\" (Supports multi-instance) MachineName The name of the machine to read the performance counter from. Optional. Rendering Options Format - Format string for conversion from float to string. Introduced with NLog v4.6 Culture - Culture used for rendering. Culture Introduced with NLog v4.6","title":"PerformanceCounter Layout Renderer"},{"location":"PerformanceCounter-Layout-Renderer/#configuration-syntax","text":"${performancecounter:Category=String:Counter=PerformanceCounterType:Instance=String :IncrementValue=Integer:MachineName:string format=String:culture=Culture}","title":"Configuration Syntax"},{"location":"PerformanceCounter-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"PerformanceCounter-Layout-Renderer/#performance-counter-options","text":"Counter - Name of the performance counter. Required. Category - Name of the counter category. Required. Instance - Name of the performance counter instance. Optional. NLog 4.6 will automatically use current process as Instance-Id when Category = \"Process\" (Supports multi-instance) MachineName The name of the machine to read the performance counter from. Optional.","title":"Performance Counter Options"},{"location":"PerformanceCounter-Layout-Renderer/#rendering-options","text":"Format - Format string for conversion from float to string. Introduced with NLog v4.6 Culture - Culture used for rendering. Culture Introduced with NLog v4.6","title":"Rendering Options"},{"location":"Platform-Support/","text":"The platform support is now integrated with the config options list. See https://nlog-project.org/config/ screenshot:","title":"Platform Support"},{"location":"PostFilteringWrapper-target/","text":"Filters buffered log entries based on a set of conditions that are evaluated on a group of events. Platforms Supported: All Configuration Syntax Parameters General Options name - Name of the target. Filtering Options defaultFilter - Default filter to be applied when no specific rule matches. Conditions Filtering Rules rules - The collection of filtering rules. The rules are processed top-down and the first rule that matches determines the filtering condition to be applied to log events. Collection Each collection item is represented by \\ element with the following attributes: exists - Condition to be tested. Conditions Required. filter - Resulting filter to be applied when the condition matches. Conditions Required. Remarks Before NLog 4.6.4 then the filtering only worked when using PostFilteringWrapper with some type of buffering target or wrapper, such as AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper. It is still a good idea add the wrapper when using the rules filtering-logic (will inspect the entire batch when a single logevent matches exists ). ","title":"PostFilteringWrapper target"},{"location":"PostFilteringWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"PostFilteringWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"PostFilteringWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"PostFilteringWrapper-target/#filtering-options","text":"defaultFilter - Default filter to be applied when no specific rule matches. Conditions","title":"Filtering Options"},{"location":"PostFilteringWrapper-target/#filtering-rules","text":"rules - The collection of filtering rules. The rules are processed top-down and the first rule that matches determines the filtering condition to be applied to log events. Collection Each collection item is represented by \\ element with the following attributes: exists - Condition to be tested. Conditions Required. filter - Resulting filter to be applied when the condition matches. Conditions Required.","title":"Filtering Rules"},{"location":"PostFilteringWrapper-target/#remarks","text":"Before NLog 4.6.4 then the filtering only worked when using PostFilteringWrapper with some type of buffering target or wrapper, such as AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper. It is still a good idea add the wrapper when using the rules filtering-logic (will inspect the entire batch when a single logevent matches exists ). ","title":"Remarks"},{"location":"ProcessDir-Layout-Renderer/","text":"The current process executable directory of the application. Platforms Supported: All Introduced in NLog v4.7.1. See also ${basedir} , ${specialfolder} , ${currentdir} , ${tempdir} Configuration Syntax ${processdir:dir=String:file=String} Parameters Advanced Options dir: Name of the directory to be Path.Combine()'d with the process directory. file: Name of the file to be Path.Combine()'d with the process directory. Remarks This is the same as using ${basedir:processDir=true} . See also: FileTarget FileName Directory","title":"ProcessDir Layout Renderer"},{"location":"ProcessDir-Layout-Renderer/#configuration-syntax","text":"${processdir:dir=String:file=String}","title":"Configuration Syntax"},{"location":"ProcessDir-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"ProcessDir-Layout-Renderer/#advanced-options","text":"dir: Name of the directory to be Path.Combine()'d with the process directory. file: Name of the file to be Path.Combine()'d with the process directory.","title":"Advanced Options"},{"location":"ProcessDir-Layout-Renderer/#remarks","text":"This is the same as using ${basedir:processDir=true} . See also: FileTarget FileName Directory","title":"Remarks"},{"location":"ProcessId-Layout-Renderer/","text":"The identifier of the current process. Platforms Supported: All Configuration Syntax ${processid}","title":"ProcessId Layout Renderer"},{"location":"ProcessId-Layout-Renderer/#configuration-syntax","text":"${processid}","title":"Configuration Syntax"},{"location":"ProcessInfo-Layout-Renderer/","text":"The information about the running process returned by Process.GetCurrentProcess() Platforms Supported: All \u26a0\ufe0f NLog v6.2 has marked this as obsolete, because the Process -object has lots of dependencies when AOT. Instead use alternatives ${processid} or ${processname} or ${processstart} or ${processtime} or ${gc:WorkingSet} Configuration Syntax ${processinfo:property=Enum:format=string} Parameters Rendering Options property - Property to retrieve. Default: Id Possible values: ExitCode - Exit Code (Not available for current process). ExitTime - Exit Time (Not available for current process). Handle - Process Handle. HandleCount - Handle Count. HasExited - Whether process has exited (Not available for current process). Id - Process ID. MachineName - Machine name. MainWindowHandle - Handle of the main window. MainWindowTitle - Title of the main window. MaxWorkingSet - Maximum Working Set. MinWorkingSet - Minimum Working Set. NonPagedSystemMemorySize - Non-paged System Memory Size. NonPagedSystemMemorySize64 - Non-paged System Memory Size (64-bit). PagedMemorySize - Paged Memory Size. PagedMemorySize64 - Paged Memory Size (64-bit).. PagedSystemMemorySize - Paged System Memory Size. PagedSystemMemorySize64 - Paged System Memory Size (64-bit). PeakPagedMemorySize - Peak Paged Memory Size. PeakPagedMemorySize64 - Peak Paged Memory Size (64-bit). PeakVirtualMemorySize - Peak Virtual Memory Size. PeakVirtualMemorySize64 - Peak Virtual Memory Size (64-bit).. PeakWorkingSet - Peak Working Set Size. PeakWorkingSet64 - Peak Working Set Size (64-bit). PriorityBoostEnabled - Whether priority boost is enabled. PriorityClass - Priority Class. PrivateMemorySize - Private Memory Size. PrivateMemorySize64 - Private Memory Size (64-bit). PrivilegedProcessorTime - Privileged Processor Time. ProcessName - Process Name. Responding - Whether process is responding. SessionId - Session ID. StartTime - Process Start Time. TotalProcessorTime - Total Processor Time. UserProcessorTime - User Processor Time. VirtualMemorySize - Virtual Memory Size. VirtualMemorySize64 - Virtual Memory Size (64-bit). WorkingSet - Working Set Size. WorkingSet64 - Working Set Size (64-bit) format formatstring in the value is formatable. Ex. formatting process StartTime. Introduced in NLog 4.4","title":"ProcessInfo Layout Renderer"},{"location":"ProcessInfo-Layout-Renderer/#configuration-syntax","text":"${processinfo:property=Enum:format=string}","title":"Configuration Syntax"},{"location":"ProcessInfo-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"ProcessInfo-Layout-Renderer/#rendering-options","text":"property - Property to retrieve. Default: Id Possible values: ExitCode - Exit Code (Not available for current process). ExitTime - Exit Time (Not available for current process). Handle - Process Handle. HandleCount - Handle Count. HasExited - Whether process has exited (Not available for current process). Id - Process ID. MachineName - Machine name. MainWindowHandle - Handle of the main window. MainWindowTitle - Title of the main window. MaxWorkingSet - Maximum Working Set. MinWorkingSet - Minimum Working Set. NonPagedSystemMemorySize - Non-paged System Memory Size. NonPagedSystemMemorySize64 - Non-paged System Memory Size (64-bit). PagedMemorySize - Paged Memory Size. PagedMemorySize64 - Paged Memory Size (64-bit).. PagedSystemMemorySize - Paged System Memory Size. PagedSystemMemorySize64 - Paged System Memory Size (64-bit). PeakPagedMemorySize - Peak Paged Memory Size. PeakPagedMemorySize64 - Peak Paged Memory Size (64-bit). PeakVirtualMemorySize - Peak Virtual Memory Size. PeakVirtualMemorySize64 - Peak Virtual Memory Size (64-bit).. PeakWorkingSet - Peak Working Set Size. PeakWorkingSet64 - Peak Working Set Size (64-bit). PriorityBoostEnabled - Whether priority boost is enabled. PriorityClass - Priority Class. PrivateMemorySize - Private Memory Size. PrivateMemorySize64 - Private Memory Size (64-bit). PrivilegedProcessorTime - Privileged Processor Time. ProcessName - Process Name. Responding - Whether process is responding. SessionId - Session ID. StartTime - Process Start Time. TotalProcessorTime - Total Processor Time. UserProcessorTime - User Processor Time. VirtualMemorySize - Virtual Memory Size. VirtualMemorySize64 - Virtual Memory Size (64-bit). WorkingSet - Working Set Size. WorkingSet64 - Working Set Size (64-bit) format formatstring in the value is formatable. Ex. formatting process StartTime. Introduced in NLog 4.4","title":"Rendering Options"},{"location":"ProcessStart-Layout-Renderer/","text":"The start time of the current process. Platforms Supported: All Introduced with NLog v6.2 Configuration Syntax ${processstart:Format=String:UniversalTime=Boolean} Parameters Rendering Options Format - DateTime ToString(...) Format specifier. Default = yyyy-MM-dd HH:mm:ss UniversalTime - DateTime UTC time. Default = False . Culture - DateTime formatting culture. Default = Invariant .","title":"ProcessStart Layout Renderer"},{"location":"ProcessStart-Layout-Renderer/#configuration-syntax","text":"${processstart:Format=String:UniversalTime=Boolean}","title":"Configuration Syntax"},{"location":"ProcessStart-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"ProcessStart-Layout-Renderer/#rendering-options","text":"Format - DateTime ToString(...) Format specifier. Default = yyyy-MM-dd HH:mm:ss UniversalTime - DateTime UTC time. Default = False . Culture - DateTime formatting culture. Default = Invariant .","title":"Rendering Options"},{"location":"Processname-Layout-Renderer/","text":"The name of the current process. Platforms Supported: All Configuration Syntax ${processname:fullName=Boolean} Parameters Rendering Options fullName - Indicates whether to write the full path to the process executable. Boolean Default: False","title":"Processname Layout Renderer"},{"location":"Processname-Layout-Renderer/#configuration-syntax","text":"${processname:fullName=Boolean}","title":"Configuration Syntax"},{"location":"Processname-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Processname-Layout-Renderer/#rendering-options","text":"fullName - Indicates whether to write the full path to the process executable. Boolean Default: False","title":"Rendering Options"},{"location":"Processtime-Layout-Renderer/","text":"The process lifetime in short sortable format HH:mm:ss.fff . Platforms Supported: All See also ${time} , ${date} , ${longdate} , ${shortdate} Configuration Syntax ${processtime:invariant=Boolean} Parameters Rendering Options invariant - Indicates whether to output in invariant time format, and not lookup of current cultureinfo. Boolean Default: true (Before NLog 5.0 the default was false) Introduced with NLog 4.5.2 culture - Culture used for time format. Default: InvariantCulture Introduced with NLog 5.0 Time Source Precision NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Processtime Layout Renderer"},{"location":"Processtime-Layout-Renderer/#configuration-syntax","text":"${processtime:invariant=Boolean}","title":"Configuration Syntax"},{"location":"Processtime-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Processtime-Layout-Renderer/#rendering-options","text":"invariant - Indicates whether to output in invariant time format, and not lookup of current cultureinfo. Boolean Default: true (Before NLog 5.0 the default was false) Introduced with NLog 4.5.2 culture - Culture used for time format. Default: InvariantCulture Introduced with NLog 5.0","title":"Rendering Options"},{"location":"Processtime-Layout-Renderer/#time-source-precision","text":"NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Time Source Precision"},{"location":"Properties-constraints-for-custom-extensions/","text":"Custom Targets, layout etc. could have properties. When configuring from the XML config, there are some limitations on the types. Supported types Supported types for Targets, Layouts and Layout renderers: .NET primitive types: e.g. bool, char, decimal, double, float, int, uint, etc. Enums (use short name in the XML) Encoding CultureInfo Type LineEndingMode Uri NLog types: Layout , SimpleLayout & ConditionExpression Types which has an implicit conversion from string Types which are using TypeDescriptor from string Collections, introduced in NLog 4.4. See section Collection types Collection types Introduced in NLog 4.4, collection types could be used. Usage in XML: comma separated string. If the value contains a comma, single quote the whole value. Examples: - value=\"one arg\" - value=\"1,2\" - value=\"value1,'value2, with comma'\" Supported types: - IList / IList - IEnumerable / IEnumerable - ISet / HashSet with the following types: - .NET built in types (string, int, double, object) - enums - culture, encoding, Type - not supported: Layout Not supported: - Arrays - Non-generic List - Non-gereric IList - Custom class implementing/inheriting types listed above (because of performance) PS: .NET 3.5 hasn't ISet , so use HashSet XML Elements For targets and layout renderers there is also support for XML elements. E.g. the JSON layout : Usage in C# [ArrayParameter(typeof(JsonAttribute), \"attribute\")] public IList Attributes { get; private set; } [NLogConfigurationItem] public class JsonAttribute {} //needs default ctor Another example is the Database target","title":"Properties constraints for custom extensions"},{"location":"Properties-constraints-for-custom-extensions/#supported-types","text":"Supported types for Targets, Layouts and Layout renderers: .NET primitive types: e.g. bool, char, decimal, double, float, int, uint, etc. Enums (use short name in the XML) Encoding CultureInfo Type LineEndingMode Uri NLog types: Layout , SimpleLayout & ConditionExpression Types which has an implicit conversion from string Types which are using TypeDescriptor from string Collections, introduced in NLog 4.4. See section Collection types","title":"Supported types"},{"location":"Properties-constraints-for-custom-extensions/#collection-types","text":"Introduced in NLog 4.4, collection types could be used. Usage in XML: comma separated string. If the value contains a comma, single quote the whole value. Examples: - value=\"one arg\" - value=\"1,2\" - value=\"value1,'value2, with comma'\" Supported types: - IList / IList - IEnumerable / IEnumerable - ISet / HashSet with the following types: - .NET built in types (string, int, double, object) - enums - culture, encoding, Type - not supported: Layout Not supported: - Arrays - Non-generic List - Non-gereric IList - Custom class implementing/inheriting types listed above (because of performance) PS: .NET 3.5 hasn't ISet , so use HashSet","title":"Collection types"},{"location":"Properties-constraints-for-custom-extensions/#xml-elements","text":"For targets and layout renderers there is also support for XML elements. E.g. the JSON layout : Usage in C# [ArrayParameter(typeof(JsonAttribute), \"attribute\")] public IList Attributes { get; private set; } [NLogConfigurationItem] public class JsonAttribute {} //needs default ctor Another example is the Database target","title":"XML Elements"},{"location":"QPC-Layout-Renderer/","text":"High precision timer, based on the value returned from QueryPerformanceCounter() optionally converted to seconds. Platforms Supported: Limited (Only for .NetFramework and deprecated with NLog 5.0) Configuration Syntax ${qpc:normalize=Boolean:difference=Boolean:alignDecimalPoint=Boolean :precision=Integer:seconds=Boolean} Parameters Rendering Options normalize - Indicates whether to normalize the result by subtracting it from the result of the first call (so that it's effectively zero-based). Boolean Default: True difference - Indicates whether to output the difference between the result of QueryPerformanceCounter and the previous one. Boolean Default: False alignDecimalPoint - Indicates whether to align decimal point (emit non-significant zeros). Boolean Default: True precision - Number of decimal digits to be included in output. Integer Default: 4 seconds - Indicates whether to convert the result to seconds by dividing by the result of QueryPerformanceFrequency(). Boolean Default: True","title":"QPC Layout Renderer"},{"location":"QPC-Layout-Renderer/#configuration-syntax","text":"${qpc:normalize=Boolean:difference=Boolean:alignDecimalPoint=Boolean :precision=Integer:seconds=Boolean}","title":"Configuration Syntax"},{"location":"QPC-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"QPC-Layout-Renderer/#rendering-options","text":"normalize - Indicates whether to normalize the result by subtracting it from the result of the first call (so that it's effectively zero-based). Boolean Default: True difference - Indicates whether to output the difference between the result of QueryPerformanceCounter and the previous one. Boolean Default: False alignDecimalPoint - Indicates whether to align decimal point (emit non-significant zeros). Boolean Default: True precision - Number of decimal digits to be included in output. Integer Default: 4 seconds - Indicates whether to convert the result to seconds by dividing by the result of QueryPerformanceFrequency(). Boolean Default: True","title":"Rendering Options"},{"location":"RandomizeGroup-target/","text":"Sends log messages to a randomly selected target. Platforms Supported: All Configuration Syntax ... Parameters General Options name - Name of the target.","title":"RandomizeGroup target"},{"location":"RandomizeGroup-target/#configuration-syntax","text":" ... ","title":"Configuration Syntax"},{"location":"RandomizeGroup-target/#parameters","text":"","title":"Parameters"},{"location":"RandomizeGroup-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"RegEx-Replace-Layout-Renderer/","text":"RegEx for replacing a string in the output of another layout with another string. Platforms Supported: All - Requires nuget-package NLog.RegEx There is also ${replace} if not needing RegEx-support. Configuration Syntax ${regex-replace:searchFor=String:wholeWords=Boolean:replaceWith=String :ignoreCase=Boolean:inner=Layout} Parameters Search/Replace Options searchFor - Text to search for. String replaceWith - Replacement string. ignoreCase - Indicates whether to ignore case when searching. Boolean Default: False wholeWords - Indicates whether to search for whole words. Boolean Default: False replaceGroupName - Specifies group name for Matched Subexpressions , where it will perform replace of all matches with that group name. Ex. (?subexpression) compileRegex - Compiles the Regex. Setting this to true can improve regex performance, but costs memory. Boolean Default: False Examples Replace sensitive data, that starts with password= or password: Truncate after token, search for , and replace everything after with empty string: With Regular Expressions keep in mind the content escaping rules to escape special characters in Regex. Specifically } and \\ . So for example the regular expression (\\d{3})+ would need to be escaped like so in your configuration There is a dedicated layout ${replace-newlines} for replacing / removing newlines (handles both Unix and Windows newlines)","title":"RegEx Replace Layout Renderer"},{"location":"RegEx-Replace-Layout-Renderer/#configuration-syntax","text":"${regex-replace:searchFor=String:wholeWords=Boolean:replaceWith=String :ignoreCase=Boolean:inner=Layout}","title":"Configuration Syntax"},{"location":"RegEx-Replace-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"RegEx-Replace-Layout-Renderer/#searchreplace-options","text":"searchFor - Text to search for. String replaceWith - Replacement string. ignoreCase - Indicates whether to ignore case when searching. Boolean Default: False wholeWords - Indicates whether to search for whole words. Boolean Default: False replaceGroupName - Specifies group name for Matched Subexpressions , where it will perform replace of all matches with that group name. Ex. (?subexpression) compileRegex - Compiles the Regex. Setting this to true can improve regex performance, but costs memory. Boolean Default: False","title":"Search/Replace Options"},{"location":"RegEx-Replace-Layout-Renderer/#examples","text":"Replace sensitive data, that starts with password= or password: Truncate after token, search for , and replace everything after with empty string: With Regular Expressions keep in mind the content escaping rules to escape special characters in Regex. Specifically } and \\ . So for example the regular expression (\\d{3})+ would need to be escaped like so in your configuration There is a dedicated layout ${replace-newlines} for replacing / removing newlines (handles both Unix and Windows newlines)","title":"Examples"},{"location":"Register-your-custom-component/","text":"NLog extensions must be registered before they can be used in NLog configuration. This can be done in different ways: Register the NLog extensions from code NLog 5.2 encourage registration from code of the NLog-extension-types, when you know up-front what will be needed. NLog.LogManager.Setup().SetupExtensions(ext => { ext.RegisterTarget(); ext.RegisterLayout(); ext.RegisterLayoutRenderer(); }); This will improve application startup-time, as one can skip assembly-loading and assembly-scanning for NLog-extension-types. It also ensures that build-trimming for the application will work (linker-tree-shake). Note registrations must be performed before LogManager.Configuration is loaded, which happens automatically on calling LogManager.GetLogger(\"..\") or LogManager.GetCurrentClassLogger() Include assembly-name in type for NLog extensions NLog 5.0 introduces the ability to use fully qualified name when specifying the type for a config-item. Register NLog extensions from assembly in NLog config Include your assembly with the syntax. Use the assembly name (not the filename) Register NLog extensions from assembly at runtime Provide the name of the assembly, which contains the NLog extension types: NLog.LogManager.Setup().SetupExtensions(s => s.RegisterAssembly(\"MyAssemblyName\")); Since NLog v5.2 this is no longer recommended. Instead one should explicit register the NLog-extension-types from code. Register NLog extension from code (Old style) Introduced with NLog v4.4. Now marked as obsolete with NLog v5.2 //target Target.Register(\"MyFirst\"); //generic Target.Register(\"MyFirst\", typeof(MyNamespace.MyFirstTarget)); //OR, dynamic //layout renderer LayoutRenderer.Register(\"MyFirst\"); //generic LayoutRenderer.Register(\"MyFirst\", typeof(MyNamespace.MyFirstLayoutRenderer)); //dynamic //layout Layout.Register(\"csv\"); //generic Layout.Register(\"csv\", typeof(MyNamespace.CsvLayout)); //dynamic Register NLog extension from code (Older style) Now marked as obsolete with NLog v5.2 //target ConfigurationItemFactory.Default.Targets .RegisterDefinition(\"MyFirst\", typeof(MyNamespace.MyFirstTarget)); //layout renderer ConfigurationItemFactory.Default.LayoutRenderers .RegisterDefinition(\"hello-world\", typeof(MyNamespace.HelloWorldLayoutRenderer)); //layout ConfigurationItemFactory.Default.Layouts .RegisterDefinition(\"csv\", typeof(MyNamespace.CsvLayout)); Automatic loading NLog extensions from assemblies with NLog prefix \u26a0\ufe0f NLog 5.0 no longer automatically scans all assemblies to register NLog extensions. This avoids an overhead during startup, and because it doesn't work with . To explicit enable the automatic scanning, then one can specify autoLoadAssemblies=\"true\" in . Introduced in NLog 4.0, where it automatically scans all assemblies starting with \"NLog\", and attempt to register any available NLog extensions types. Name your assembly \"NLog*.dll\", like \u201cNLog.CustomTarget.dll\u201d. When the assembly is in the same folder as nlog.dll, it will be autoloaded when the configuration changes.","title":"Register your custom component"},{"location":"Register-your-custom-component/#register-the-nlog-extensions-from-code","text":"NLog 5.2 encourage registration from code of the NLog-extension-types, when you know up-front what will be needed. NLog.LogManager.Setup().SetupExtensions(ext => { ext.RegisterTarget(); ext.RegisterLayout(); ext.RegisterLayoutRenderer(); }); This will improve application startup-time, as one can skip assembly-loading and assembly-scanning for NLog-extension-types. It also ensures that build-trimming for the application will work (linker-tree-shake). Note registrations must be performed before LogManager.Configuration is loaded, which happens automatically on calling LogManager.GetLogger(\"..\") or LogManager.GetCurrentClassLogger()","title":"Register the NLog extensions from code"},{"location":"Register-your-custom-component/#include-assembly-name-in-type-for-nlog-extensions","text":"NLog 5.0 introduces the ability to use fully qualified name when specifying the type for a config-item. ","title":"Include assembly-name in type for NLog extensions"},{"location":"Register-your-custom-component/#register-nlog-extensions-from-assembly-in-nlog-config","text":"Include your assembly with the syntax. Use the assembly name (not the filename) ","title":"Register NLog extensions from assembly in NLog config"},{"location":"Register-your-custom-component/#register-nlog-extensions-from-assembly-at-runtime","text":"Provide the name of the assembly, which contains the NLog extension types: NLog.LogManager.Setup().SetupExtensions(s => s.RegisterAssembly(\"MyAssemblyName\")); Since NLog v5.2 this is no longer recommended. Instead one should explicit register the NLog-extension-types from code.","title":"Register NLog extensions from assembly at runtime"},{"location":"Register-your-custom-component/#register-nlog-extension-from-code-old-style","text":"Introduced with NLog v4.4. Now marked as obsolete with NLog v5.2 //target Target.Register(\"MyFirst\"); //generic Target.Register(\"MyFirst\", typeof(MyNamespace.MyFirstTarget)); //OR, dynamic //layout renderer LayoutRenderer.Register(\"MyFirst\"); //generic LayoutRenderer.Register(\"MyFirst\", typeof(MyNamespace.MyFirstLayoutRenderer)); //dynamic //layout Layout.Register(\"csv\"); //generic Layout.Register(\"csv\", typeof(MyNamespace.CsvLayout)); //dynamic","title":"Register NLog extension from code (Old style)"},{"location":"Register-your-custom-component/#register-nlog-extension-from-code-older-style","text":"Now marked as obsolete with NLog v5.2 //target ConfigurationItemFactory.Default.Targets .RegisterDefinition(\"MyFirst\", typeof(MyNamespace.MyFirstTarget)); //layout renderer ConfigurationItemFactory.Default.LayoutRenderers .RegisterDefinition(\"hello-world\", typeof(MyNamespace.HelloWorldLayoutRenderer)); //layout ConfigurationItemFactory.Default.Layouts .RegisterDefinition(\"csv\", typeof(MyNamespace.CsvLayout));","title":"Register NLog extension from code (Older style)"},{"location":"Register-your-custom-component/#automatic-loading-nlog-extensions-from-assemblies-with-nlog-prefix","text":"\u26a0\ufe0f NLog 5.0 no longer automatically scans all assemblies to register NLog extensions. This avoids an overhead during startup, and because it doesn't work with . To explicit enable the automatic scanning, then one can specify autoLoadAssemblies=\"true\" in . Introduced in NLog 4.0, where it automatically scans all assemblies starting with \"NLog\", and attempt to register any available NLog extensions types. Name your assembly \"NLog*.dll\", like \u201cNLog.CustomTarget.dll\u201d. When the assembly is in the same folder as nlog.dll, it will be autoloaded when the configuration changes.","title":"Automatic loading NLog extensions from assemblies with NLog prefix"},{"location":"Registry-Layout-Renderer/","text":"A value from the Registry. Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsRegistry since NLog 5.0 Configuration Syntax ${registry:value=Layout:key=Layout:defaultValue=Layout:view=enum:requireEscapingSlashesInDefaultValue=boolean} Parameters Registry Options value - Registry value name. Since NLog 4.3 a Layout . Before String . key - Registry key. Required. Since NLog 4.3 a Layout . Before String . Must have the form: hive /key/subkey/name Possible hives: HKLM/HKEY_LOCAL_MACHINE/HKCU/HKEY_CURRENT_USER Also possible since NLog 4.3: HKEY_CLASSES_ROOT/HKEY_USERS/HKEY_CURRENT_CONFIG/HKEY_DYN_DATA/HKEY_PERFORMANCE_DATA defaultValue - Value to be output when the specified registry key or value is not found. Since NLog 4.3 a Layout . Before String . RequireEscapingSlashesInDefaultValue - Introduced in NLog 4.3 boolean . Require escaping backward slashes in DefaultValue . Need to be backwardscompatible. Default true . Will be removed in the future. View - Introduced in NLog 4.3 . Registry32, Registry64, Default","title":"Registry Layout Renderer"},{"location":"Registry-Layout-Renderer/#configuration-syntax","text":"${registry:value=Layout:key=Layout:defaultValue=Layout:view=enum:requireEscapingSlashesInDefaultValue=boolean}","title":"Configuration Syntax"},{"location":"Registry-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Registry-Layout-Renderer/#registry-options","text":"value - Registry value name. Since NLog 4.3 a Layout . Before String . key - Registry key. Required. Since NLog 4.3 a Layout . Before String . Must have the form: hive /key/subkey/name Possible hives: HKLM/HKEY_LOCAL_MACHINE/HKCU/HKEY_CURRENT_USER Also possible since NLog 4.3: HKEY_CLASSES_ROOT/HKEY_USERS/HKEY_CURRENT_CONFIG/HKEY_DYN_DATA/HKEY_PERFORMANCE_DATA defaultValue - Value to be output when the specified registry key or value is not found. Since NLog 4.3 a Layout . Before String . RequireEscapingSlashesInDefaultValue - Introduced in NLog 4.3 boolean . Require escaping backward slashes in DefaultValue . Need to be backwardscompatible. Default true . Will be removed in the future. View - Introduced in NLog 4.3 . Registry32, Registry64, Default","title":"Registry Options"},{"location":"Reinitialize-NLog-configuration/","text":"The combination of dynamic logging configuration and NLog-targets that only applies configuration during initialization can give a catch22. You want to have logging up and running early, but this will fail if NLog-targets initialization depends on configuration settings being available. This can lead to NLog-targets failing to initialize so NLog suddenly is disabled, or NLog-targets never using the configured destination. GDC and whenEmpty The recommended solution to this problem is to make use of GDC and whenEmpty : Then one can apply the dynamic configuration change like this: NLog.GlobalDiagnosticsContext.Set(\"targetUri\", \"http://127.0.0.1:9200\"); NLog.LogManager.Configuration = NLog.LogManager.Configuration?.Reload(); Please note that Configuration.Reload() will cause all NLog-variables to be reset. This is why GDC is being used to store the dynamic configuration. Re-initialize single target The standard NLog targets supports reinitialization, but it is not always supported by 3rdParty NLog targets. This can happen if closing NLog-target performs dispose of members, that are only initialized in the constructor of the NLog-target. var target = NLog.LogManager.Configuration?.FindTargetByName(\"blob\"); target?.Dispose(); // Closes the target so it is uninitialized NLog.LogManager.ReconfigExistingLoggers(); // Ensures all targets are initialized Knowing the name of the NLog-target can sometimes be a challenge, especially if the NLog-target is wrapped using AsyncWrapper or BufferingWrapper . One can also do this: NLog.LogManager.Configuration?.AllTargets.OfType().ToList().ForEach(t => t.Dispose()); NLog.LogManager.ReconfigExistingLoggers(); // Ensures all targets are initialized Re-initialize all targets This is the big hammer, and might not be supported by all NLog-targets. This can happen if closing NLog-target performs dispose of members, that are only initialized in the constructor of the NLog-target. NLog v5 has introduced this command: NLog.LogManager.Setup().ReloadConfiguration(); If using NLog v4 then this will also work: NLog.LogManager.Configuration = NLog.LogManager.Configuration; Notice that LogEvents produced by the application can become lost, in the period where closing and initializing all NLog targets.","title":"Reinitialize NLog configuration"},{"location":"Reinitialize-NLog-configuration/#gdc-and-whenempty","text":"The recommended solution to this problem is to make use of GDC and whenEmpty : Then one can apply the dynamic configuration change like this: NLog.GlobalDiagnosticsContext.Set(\"targetUri\", \"http://127.0.0.1:9200\"); NLog.LogManager.Configuration = NLog.LogManager.Configuration?.Reload(); Please note that Configuration.Reload() will cause all NLog-variables to be reset. This is why GDC is being used to store the dynamic configuration.","title":"GDC and whenEmpty"},{"location":"Reinitialize-NLog-configuration/#re-initialize-single-target","text":"The standard NLog targets supports reinitialization, but it is not always supported by 3rdParty NLog targets. This can happen if closing NLog-target performs dispose of members, that are only initialized in the constructor of the NLog-target. var target = NLog.LogManager.Configuration?.FindTargetByName(\"blob\"); target?.Dispose(); // Closes the target so it is uninitialized NLog.LogManager.ReconfigExistingLoggers(); // Ensures all targets are initialized Knowing the name of the NLog-target can sometimes be a challenge, especially if the NLog-target is wrapped using AsyncWrapper or BufferingWrapper . One can also do this: NLog.LogManager.Configuration?.AllTargets.OfType().ToList().ForEach(t => t.Dispose()); NLog.LogManager.ReconfigExistingLoggers(); // Ensures all targets are initialized","title":"Re-initialize single target"},{"location":"Reinitialize-NLog-configuration/#re-initialize-all-targets","text":"This is the big hammer, and might not be supported by all NLog-targets. This can happen if closing NLog-target performs dispose of members, that are only initialized in the constructor of the NLog-target. NLog v5 has introduced this command: NLog.LogManager.Setup().ReloadConfiguration(); If using NLog v4 then this will also work: NLog.LogManager.Configuration = NLog.LogManager.Configuration; Notice that LogEvents produced by the application can become lost, in the period where closing and initializing all NLog targets.","title":"Re-initialize all targets"},{"location":"RepeatingWrapper-target/","text":"Repeats each log event the specified number of times. Platforms Supported: All Configuration Syntax Parameters General Options name - Name of the target. Repeating Options repeatCount - Number of times to repeat each log message. Integer Default: 3","title":"RepeatingWrapper target"},{"location":"RepeatingWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"RepeatingWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"RepeatingWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"RepeatingWrapper-target/#repeating-options","text":"repeatCount - Number of times to repeat each log message. Integer Default: 3","title":"Repeating Options"},{"location":"Replace-Layout-Renderer/","text":"Replaces a string in the output of another layout with another string. Platforms Supported: All Configuration Syntax ${replace:searchFor=String:wholeWords=Boolean:replaceWith=String :ignoreCase=Boolean:inner=Layout} Parameters Search/Replace Options searchFor - Text to search for. String replaceWith - Replacement string. ignoreCase - Indicates whether to ignore case when searching. Boolean Default: False wholeWords - Indicates whether to search for whole words. Boolean Default: False Transformation Options inner - Wrapped layout. Layout RegEx not supported NLog v6 does not support Regular Expressions (RegEx), and have removed these options: regex - Indicates whether regular expressions should be used when searching. Boolean Default: False replaceGroupName - Specifies group name for Matched Subexpressions , where it will perform replace of all matches with that group name. Ex. (?subexpression) Introduced with NLog 3.1 compileRegex - Compiles the Regex. Setting this to true can improve regex performance, but costs memory. Boolean Default: False Introduced with NLog 4.7 If needing Regular Expressions, then one can use ${regex-replace} from NLog.RegEx -nuget-package. RegEx Examples Replace sensitive data, that starts with password= or password: Truncate after token, search for , and replace everything after with empty string: With Regular Expressions keep in mind the content escaping rules to escape special characters in Regex. Specifically } and \\ . So for example the regular expression (\\d{3})+ would need to be escaped like so in your configuration There is a dedicated layout ${replace-newlines} for replacing / removing newlines (handles both Unix and Windows newlines)","title":"Replace Layout Renderer"},{"location":"Replace-Layout-Renderer/#configuration-syntax","text":"${replace:searchFor=String:wholeWords=Boolean:replaceWith=String :ignoreCase=Boolean:inner=Layout}","title":"Configuration Syntax"},{"location":"Replace-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Replace-Layout-Renderer/#searchreplace-options","text":"searchFor - Text to search for. String replaceWith - Replacement string. ignoreCase - Indicates whether to ignore case when searching. Boolean Default: False wholeWords - Indicates whether to search for whole words. Boolean Default: False","title":"Search/Replace Options"},{"location":"Replace-Layout-Renderer/#transformation-options","text":"inner - Wrapped layout. Layout","title":"Transformation Options"},{"location":"Replace-Layout-Renderer/#regex-not-supported","text":"NLog v6 does not support Regular Expressions (RegEx), and have removed these options: regex - Indicates whether regular expressions should be used when searching. Boolean Default: False replaceGroupName - Specifies group name for Matched Subexpressions , where it will perform replace of all matches with that group name. Ex. (?subexpression) Introduced with NLog 3.1 compileRegex - Compiles the Regex. Setting this to true can improve regex performance, but costs memory. Boolean Default: False Introduced with NLog 4.7 If needing Regular Expressions, then one can use ${regex-replace} from NLog.RegEx -nuget-package.","title":"RegEx not supported"},{"location":"Replace-Layout-Renderer/#regex-examples","text":"Replace sensitive data, that starts with password= or password: Truncate after token, search for , and replace everything after with empty string: With Regular Expressions keep in mind the content escaping rules to escape special characters in Regex. Specifically } and \\ . So for example the regular expression (\\d{3})+ would need to be escaped like so in your configuration There is a dedicated layout ${replace-newlines} for replacing / removing newlines (handles both Unix and Windows newlines)","title":"RegEx Examples"},{"location":"Replace-NewLines-Layout-Renderer/","text":"Replaces a new lines in the output of another layout with a string. Platforms Supported: All Introduced in NLog 4.1 For general purpose search and replace there is also ${replace} Configuration Syntax ${replace-newlines:inner=Layout:replacement=String} Parameters replacement - Text to replace newlines with. Default is \" \" (space) Examples logger.Info(\"foo {0}\", \"bar\" + System.Environment.NewLine + \"123\"); To space ${replace-newlines:${message}} Will result in \"foo bar 123\" To other char ${replace-newlines:replacement=|:${message}} Will result in \"foo bar|123\"","title":"Replace NewLines Layout Renderer"},{"location":"Replace-NewLines-Layout-Renderer/#configuration-syntax","text":"${replace-newlines:inner=Layout:replacement=String}","title":"Configuration Syntax"},{"location":"Replace-NewLines-Layout-Renderer/#parameters","text":"replacement - Text to replace newlines with. Default is \" \" (space)","title":"Parameters"},{"location":"Replace-NewLines-Layout-Renderer/#examples","text":"logger.Info(\"foo {0}\", \"bar\" + System.Environment.NewLine + \"123\");","title":"Examples"},{"location":"Replace-NewLines-Layout-Renderer/#to-space","text":"${replace-newlines:${message}} Will result in \"foo bar 123\"","title":"To space"},{"location":"Replace-NewLines-Layout-Renderer/#to-other-char","text":"${replace-newlines:replacement=|:${message}} Will result in \"foo bar|123\"","title":"To other char"},{"location":"RetryingWrapper-target/","text":"Retries in case of write error. Platforms Supported: All Configuration Syntax Parameters General Options name - Name of the target. Retrying Options retryDelayMilliseconds - Time to wait between retries in milliseconds. Integer Default: 100 retryCount - Number of retries that should be attempted on the wrapped target in case of a failure. Integer Default: 3 enableBatchWrite - Allow batch writes, and only introduced retry delay once before retrying the batch items one at a time. Introduced with NLog 5.0 Notes When failure occurs, then the retry will perform a synchronous delay. To avoid blocking the application-thread in the retry-sleep, then consider using AsyncWrapper like this: AsyncWrapper -> RetryWrapper -> Actual Target","title":"RetryingWrapper target"},{"location":"RetryingWrapper-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"RetryingWrapper-target/#parameters","text":"","title":"Parameters"},{"location":"RetryingWrapper-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"RetryingWrapper-target/#retrying-options","text":"retryDelayMilliseconds - Time to wait between retries in milliseconds. Integer Default: 100 retryCount - Number of retries that should be attempted on the wrapped target in case of a failure. Integer Default: 3 enableBatchWrite - Allow batch writes, and only introduced retry delay once before retrying the batch items one at a time. Introduced with NLog 5.0","title":"Retrying Options"},{"location":"RetryingWrapper-target/#notes","text":"When failure occurs, then the retry will perform a synchronous delay. To avoid blocking the application-thread in the retry-sleep, then consider using AsyncWrapper like this: AsyncWrapper -> RetryWrapper -> Actual Target","title":"Notes"},{"location":"RichTextBox-target/","text":"Page moved to RichTextBoxTarget - NLog.Windows.Forms","title":"RichTextBox target"},{"location":"Right-layout-renderer/","text":"Right part of a text Platforms Supported: All Introduced in NLog 4.6 Related: ${substring} ${left} Configuration Syntax ${right:inner=Layout:length=Integer} Read more about using the Configuration File . Parameters Transformation Options inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout length - Length in characters. Integer Required.","title":"Right layout renderer"},{"location":"Right-layout-renderer/#configuration-syntax","text":"${right:inner=Layout:length=Integer} Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Right-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Right-layout-renderer/#transformation-options","text":"inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout length - Length in characters. Integer Required.","title":"Transformation Options"},{"location":"Rot13-Layout-Renderer/","text":"Decodes text \"encrypted\" with ROT-13. Platforms Supported: All Configuration Syntax ${rot13:inner=Layout:text=Layout} Parameters Transformation Options inner - Wrapped layout. Layout text - Layout to be wrapped. Layout This variable is for backwards compatibility Remarks See https://en.wikipedia.org/wiki/ROT13.","title":"Rot13 Layout Renderer"},{"location":"Rot13-Layout-Renderer/#configuration-syntax","text":"${rot13:inner=Layout:text=Layout}","title":"Configuration Syntax"},{"location":"Rot13-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Rot13-Layout-Renderer/#transformation-options","text":"inner - Wrapped layout. Layout text - Layout to be wrapped. Layout This variable is for backwards compatibility","title":"Transformation Options"},{"location":"Rot13-Layout-Renderer/#remarks","text":"See https://en.wikipedia.org/wiki/ROT13.","title":"Remarks"},{"location":"RoundRobinGroup-target/","text":"Distributes log events to targets in a round-robin fashion. Platforms Supported: All Configuration Syntax ... Parameters General Options name - Name of the target.","title":"RoundRobinGroup target"},{"location":"RoundRobinGroup-target/#configuration-syntax","text":" ... ","title":"Configuration Syntax"},{"location":"RoundRobinGroup-target/#parameters","text":"","title":"Parameters"},{"location":"RoundRobinGroup-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"SL-AppInfo-Layout-Renderer/","text":"Information about Silverlight application. Supported in Silverlight (Deprecated with NLog 5.0) Configuration Syntax ${sl-appinfo:option=Enum} Parameters Rendering Options option - Specific information to display. Default: 0 Possible values: HasElevatedPermissions - Whether application is running with elevated permissions. This parameter is not supported in: * NLog v2.0 for Silverlight 2.0 * NLog v2.0 for Silverlight 3.0 InstallState - Installed state of an application. This parameter is not supported in: * NLog v2.0 for Silverlight 2.0 IsOutOfBrowser - Whether application is running out-of-browser. This parameter is not supported in: * NLog v2.0 for Silverlight 2.0 XapUri - URI of the current application XAP file.","title":"SL AppInfo Layout Renderer"},{"location":"SL-AppInfo-Layout-Renderer/#configuration-syntax","text":"${sl-appinfo:option=Enum}","title":"Configuration Syntax"},{"location":"SL-AppInfo-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"SL-AppInfo-Layout-Renderer/#rendering-options","text":"option - Specific information to display. Default: 0 Possible values: HasElevatedPermissions - Whether application is running with elevated permissions. This parameter is not supported in: * NLog v2.0 for Silverlight 2.0 * NLog v2.0 for Silverlight 3.0 InstallState - Installed state of an application. This parameter is not supported in: * NLog v2.0 for Silverlight 2.0 IsOutOfBrowser - Whether application is running out-of-browser. This parameter is not supported in: * NLog v2.0 for Silverlight 2.0 XapUri - URI of the current application XAP file.","title":"Rendering Options"},{"location":"ScopeIndent-Layout-Renderer/","text":"ScopeContext Nested States are stored in the thread execution context. Similar to \"Nested Diagnostic Context\" (NDC) in Log4j. Platforms Supported: All (AsyncLocal is used for NetStandard and Net46, but older platforms uses Remoting.Messaging.CallContext ) Introduced with NLog 5.0.5 Inserts indent-delimiter for every nested state in the ScopeContext. Configuration Syntax ${scopeindent:indent=Layout} Parameters indent - Delimiter to insert for every nested state level in ScopeContext. Layout . Default (double space) Examples Logger.Info(\"Hello No Scope\"); // Will not be indented using (NLog.ScopeContext.PushNestedState(\"First Scope\")) { Logger.Info(\"Hello First Scope\"); // Will be indented once await InnerOperationAsync(); } static async Task InnerOperationAsync() { using (NLog.ScopeContext.PushNestedState(\"Second Scope\")) { Logger.Info(\"Hello Second Scope\"); // Will be indented twice await Task.Yield(); } }","title":"ScopeIndent Layout Renderer"},{"location":"ScopeIndent-Layout-Renderer/#configuration-syntax","text":"${scopeindent:indent=Layout}","title":"Configuration Syntax"},{"location":"ScopeIndent-Layout-Renderer/#parameters","text":"indent - Delimiter to insert for every nested state level in ScopeContext. Layout . Default (double space)","title":"Parameters"},{"location":"ScopeIndent-Layout-Renderer/#examples","text":"Logger.Info(\"Hello No Scope\"); // Will not be indented using (NLog.ScopeContext.PushNestedState(\"First Scope\")) { Logger.Info(\"Hello First Scope\"); // Will be indented once await InnerOperationAsync(); } static async Task InnerOperationAsync() { using (NLog.ScopeContext.PushNestedState(\"Second Scope\")) { Logger.Info(\"Hello Second Scope\"); // Will be indented twice await Task.Yield(); } }","title":"Examples"},{"location":"ScopeNested-Layout-Renderer/","text":"ScopeContext Nested States are stored in the thread execution context. Similar to \"Nested Diagnostic Context\" (NDC) in Log4j. Platforms Supported: All (AsyncLocal is used for NetStandard and Net46, but older platforms uses Remoting.Messaging.CallContext ) Introduced with NLog 5.0 that merges ${MDC} + ${MDLC} + ${NDC} + ${NDLC} into an unified ScopeContext. It enables one to assign a scope-name to the active scope (Ex. a request method-name). Then all logger-events created within the scoped logical context, can automatically capture the scope-name without needing to specify it with each LogEvent. The specified scope states will automatically flow together with async Tasks. See also NLog Context and ${scopeproperty} and ${scopetiming} and ${scopeindent} Configuration Syntax ${scopenested:bottomFrames=Integer:topFrames=Integer:separator=String} Parameters bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer . Default -1 . topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer . Default -1 separator - Separator to be used for concatenating nested diagnostics context output. string . Default (space) format - Format string for conversion into string. Possible to use @ for Json-Array. culture - Format provider for conversion into string. Examples using (NLog.ScopeContext.PushNestedState(\"Outer Scope\")) { Logger.Info(\"Hello Outer\"); await InnerOperationAsync(); } static async Task InnerOperationAsync() { using (NLog.ScopeContext.PushNestedState(\"Inner Scope\")) { Logger.Info(\"Hello Inner\"); await Task.Yield(); } } The NLog Logger can also be used to update ScopeContext: var logger = NLog.LogManager.GetCurrentClassLogger(); using (logger.PushScopeNested(\"Outer Scope\")) { } .NET Core logging When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : using (_logger.BeginScope(\"Outer Scope\")) { _logger.LogDebug(\"Start process {ProccessName}, \"Main\"); } Indenting Log Messages Indent log-messages based on how many nested levels in ScopeContext using ${scopeindent} ${scopeindent}${message}","title":"ScopeNested Layout Renderer"},{"location":"ScopeNested-Layout-Renderer/#configuration-syntax","text":"${scopenested:bottomFrames=Integer:topFrames=Integer:separator=String}","title":"Configuration Syntax"},{"location":"ScopeNested-Layout-Renderer/#parameters","text":"bottomFrames - Number of bottom stack frames to be rendered. -1 is no limit. Integer . Default -1 . topFrames - Number of top stack frames to be rendered. -1 is no limit. Integer . Default -1 separator - Separator to be used for concatenating nested diagnostics context output. string . Default (space) format - Format string for conversion into string. Possible to use @ for Json-Array. culture - Format provider for conversion into string.","title":"Parameters"},{"location":"ScopeNested-Layout-Renderer/#examples","text":"using (NLog.ScopeContext.PushNestedState(\"Outer Scope\")) { Logger.Info(\"Hello Outer\"); await InnerOperationAsync(); } static async Task InnerOperationAsync() { using (NLog.ScopeContext.PushNestedState(\"Inner Scope\")) { Logger.Info(\"Hello Inner\"); await Task.Yield(); } } The NLog Logger can also be used to update ScopeContext: var logger = NLog.LogManager.GetCurrentClassLogger(); using (logger.PushScopeNested(\"Outer Scope\")) { }","title":"Examples"},{"location":"ScopeNested-Layout-Renderer/#net-core-logging","text":"When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : using (_logger.BeginScope(\"Outer Scope\")) { _logger.LogDebug(\"Start process {ProccessName}, \"Main\"); }","title":".NET Core logging"},{"location":"ScopeNested-Layout-Renderer/#indenting-log-messages","text":"Indent log-messages based on how many nested levels in ScopeContext using ${scopeindent} ${scopeindent}${message}","title":"Indenting Log Messages"},{"location":"ScopeProperty-Layout-Renderer/","text":"ScopeContext Properties are stored in the thread execution context. Similar to \"Mapped Diagnostic Context\" (MDC) in Log4j. Platforms Supported: All (AsyncLocal is used for NetStandard and Net46, but older platforms uses Remoting.Messaging.CallContext ) Introduced with NLog 5.0 that merges ${MDC} + ${MDLC} + ${NDC} + ${NDLC} into an unified ScopeContext. It enables one to assign one or more named properties to the active scope (Ex. a request CorrelationId). Then all logger-events created within the scoped logical context, can automatically include the scope-properties in the ouput without specifying with each LogEvent. The specified scope properties will automatically flow together with async Tasks. See also NLog Context and ${scopenested} and ${scopetiming} and ${all-event-properties:includeScopeProperties=true} Configuration Syntax ${scopeproperty:item=String} Parameters item - Name of the item. Lookup is case-insensitive. Required. format - Format string for conversion into string. Possible to use @ for Json. culture - Format provider for conversion into string. Example using (NLog.ScopeContext.PushProperty(\"PropertyName\", \"PropertyValue\")) { Logger.Info(\"Hello World\"); // LogEvent can use ${scopeproperty:PropertyName} in target output } // \"PropertyName\" items has been removed from current context The NLog Logger can also be used for updating the ScopeContext: var logger = NLog.LogManager.GetCurrentClassLogger(); using (logger.PushScopeProperty(\"PropertyName\", \"PropertyValue\")) { logger.Info(\"Hello World\"); // LogEvent can use ${scopeproperty:PropertyName} in target output } .NET Core logging When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : using (_logger.BeginScope(new[] { new KeyValuePair(\"userid\", request.UserId) })) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output } NLog.Extensions.Logging v5.3.7 adds support for using ValueTuple for single scope-property (better performance): using (_logger.BeginScope((\"userid\", request.UserId))) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output } Fallback to default value When ScopeContext Property cannot be found (or has blank value), then one use whenEmpty to specify fallback value: ${scope-property:UserId:whenEmpty=42}","title":"ScopeProperty Layout Renderer"},{"location":"ScopeProperty-Layout-Renderer/#configuration-syntax","text":"${scopeproperty:item=String}","title":"Configuration Syntax"},{"location":"ScopeProperty-Layout-Renderer/#parameters","text":"item - Name of the item. Lookup is case-insensitive. Required. format - Format string for conversion into string. Possible to use @ for Json. culture - Format provider for conversion into string.","title":"Parameters"},{"location":"ScopeProperty-Layout-Renderer/#example","text":"using (NLog.ScopeContext.PushProperty(\"PropertyName\", \"PropertyValue\")) { Logger.Info(\"Hello World\"); // LogEvent can use ${scopeproperty:PropertyName} in target output } // \"PropertyName\" items has been removed from current context The NLog Logger can also be used for updating the ScopeContext: var logger = NLog.LogManager.GetCurrentClassLogger(); using (logger.PushScopeProperty(\"PropertyName\", \"PropertyValue\")) { logger.Info(\"Hello World\"); // LogEvent can use ${scopeproperty:PropertyName} in target output }","title":"Example"},{"location":"ScopeProperty-Layout-Renderer/#net-core-logging","text":"When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options : using (_logger.BeginScope(new[] { new KeyValuePair(\"userid\", request.UserId) })) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output } NLog.Extensions.Logging v5.3.7 adds support for using ValueTuple for single scope-property (better performance): using (_logger.BeginScope((\"userid\", request.UserId))) { _logger.LogDebug(\"Hello {World}\", \"Earth\"); // Render userId via ${scopeproperty:userid} in target output }","title":".NET Core logging"},{"location":"ScopeProperty-Layout-Renderer/#fallback-to-default-value","text":"When ScopeContext Property cannot be found (or has blank value), then one use whenEmpty to specify fallback value: ${scope-property:UserId:whenEmpty=42}","title":"Fallback to default value"},{"location":"ScopeTiming-Layout-Renderer/","text":"ScopeContext allows one to give a scope name for an operation that can be async. When the scope begins then it automatically captures a timestamp. This can be used to show duration of the active scope. Platforms Supported: All Introduced in NLog 5.0 and replaces ${ndlctiming} See also NLog Context and ${scopeproperty} and ${scopenested} Configuration Syntax ${scopetiming:currentScope=Boolean:StartTime=Boolean:format=String} Parameters Rendering Options currentScope - Whether to only include the duration of the last scope created. Boolean . Default False . StartTime - Whether to just display the scope creation time, and not the duration. Boolean . Default False format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format) . string . Default null","title":"ScopeTiming Layout Renderer"},{"location":"ScopeTiming-Layout-Renderer/#configuration-syntax","text":"${scopetiming:currentScope=Boolean:StartTime=Boolean:format=String}","title":"Configuration Syntax"},{"location":"ScopeTiming-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"ScopeTiming-Layout-Renderer/#rendering-options","text":"currentScope - Whether to only include the duration of the last scope created. Boolean . Default False . StartTime - Whether to just display the scope creation time, and not the duration. Boolean . Default False format - TimeSpan format. Can be any argument accepted by TimeSpan.ToString(format) . string . Default null","title":"Rendering Options"},{"location":"SequenceId-layout-renderer/","text":"The log sequence id (Reset to zero on application restart) Platforms Supported: All Introduced in NLog v4.5 Alternative use ${counter:sequence=global} or ${guid:GeneratedFromLogEvent=true} Configuration syntax ${sequenceid}","title":"SequenceId layout renderer"},{"location":"SequenceId-layout-renderer/#configuration-syntax","text":"${sequenceid}","title":"Configuration syntax"},{"location":"ShortDate-Layout-Renderer/","text":"The short date in a sortable format yyyy-MM-dd. Platforms Supported: All Alternative ${date:format=yyyy_MM_dd} can be used to customize the DateTime-format. Configuration Syntax ${shortdate:universalTime=Boolean} Parameters Rendering Options universalTime - Indicates whether to output UTC time instead of local time. Boolean Default: False","title":"ShortDate Layout Renderer"},{"location":"ShortDate-Layout-Renderer/#configuration-syntax","text":"${shortdate:universalTime=Boolean}","title":"Configuration Syntax"},{"location":"ShortDate-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"ShortDate-Layout-Renderer/#rendering-options","text":"universalTime - Indicates whether to output UTC time instead of local time. Boolean Default: False","title":"Rendering Options"},{"location":"SimpleLayout/","text":"Represents a string with embedded placeholders that can render contextual information from the LogEvent. Platforms Supported: All Configuration Syntax SimpleLayout is used by default when nothing specified, so one can just write: But one can explictly specify the SimpleLayout -type like this: Parameters Layout Options text - Layout text Remarks The layout is not meant to be built explicitly from code, instead assign a string, e.g. Layout l = \"${longdate}|${level}|${logger}|${message}\" The layout can be literal text like \"Hello\" , but can also contain Layout-Renderers like ${message} . See also: List of Layout-Renderers Many NLog Targets has their Layout -option configured to this default-value: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} 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} There also exists Layout-types for more structured output-formats like JSON , XML , CSV , etc. See also: List of Layouts","title":"SimpleLayout"},{"location":"SimpleLayout/#configuration-syntax","text":"SimpleLayout is used by default when nothing specified, so one can just write: But one can explictly specify the SimpleLayout -type like this: ","title":"Configuration Syntax"},{"location":"SimpleLayout/#parameters","text":"","title":"Parameters"},{"location":"SimpleLayout/#layout-options","text":"text - Layout text","title":"Layout Options"},{"location":"SimpleLayout/#remarks","text":"The layout is not meant to be built explicitly from code, instead assign a string, e.g. Layout l = \"${longdate}|${level}|${logger}|${message}\" The layout can be literal text like \"Hello\" , but can also contain Layout-Renderers like ${message} . See also: List of Layout-Renderers Many NLog Targets has their Layout -option configured to this default-value: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} 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} There also exists Layout-types for more structured output-formats like JSON , XML , CSV , etc. See also: List of Layouts","title":"Remarks"},{"location":"Special-Folder-Layout-Renderer/","text":"System special folder path (includes My Documents, My Music, Program Files, Desktop, and more). Platforms Supported: All See also ${processdir} , ${basedir} , ${currentdir} , ${tempdir} Configuration Syntax ${specialfolder:dir=String:file=String:folder=Enum} Example using CommonApplicationData which is good when running as Windows Service: fileName=\"${specialfolder:folder=CommonApplicationData:cached=true}/AppName/logfile.txt\" Windows-Path - C:/ProgramData/AppName/logfile.txt Parameters Advanced Options dir - Name of the directory to be Path.Combine()'d with the directory name. file - Name of the file to be Path.Combine()'d with the directory name. Rendering Options folder - System special folder to use. Full list of options is available at MSDN . The most common ones are: ApplicationData - Roaming application data for current user Windows Path = C:\\Users\\%USERNAME%\\AppData\\Roaming Xamarin Mono = $HOME/.config (or $XDG_CONFIG_HOME if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/.config Xamarin Android = /data/data/@PACKAGE_NAME@/files/.config LocalApplicationData - Non roaming application data for current user Windows Path = C:\\Users\\%USERNAME%\\AppData\\Local Xamarin Mono = $HOME/.local/share (or $XDG_DATA_HOME if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents Xamarin Android = /data/data/@PACKAGE_NAME@/files/.local/share CommonApplicationData - Application data for all users (Good when running as Windows Service) Windows Path = C:\\ProgramData Xamarin Mono = /usr/share Xamarin iOS = /usr/share Xamarin Android = /usr/share MyDocuments - My Documents Windows Path = C:\\Users\\%USERNAME%\\Documents Xamarin Mono = $HOME Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents Xamarin Android = /data/data/@PACKAGE_NAME@/files Desktop - My Desktop Windows Path = C:\\Users\\%USERNAME%\\Desktop Xamarin Mono = $HOME/Desktop (or $XDG_DESKTOP_DIR if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/Desktop Xamarin Android = /data/data/@PACKAGE_NAME@/files/Desktop UserProfile Windows Path = C:\\Users\\%USERNAME% Xamarin Mono = $HOME Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@ Xamarin Android = /data/data/@PACKAGE_NAME@/files Templates Windows Path = C:\\Users\\%USERNAME%\\AppData\\Roaming\\Microsoft\\Windows\\Templates Xamarin Mono = $HOME/Templates (or $XDG_TEMPLATES_DIR if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/Templates Xamarin Android = /data/data/@PACKAGE_NAME@/files/Templates CommonTemplates Windows Path = C:\\ProgramData\\Microsoft\\Windows\\Templates Xamarin Mono = /usr/share/templates Xamarin iOS = /usr/share/templates Xamarin Android = /usr/share/templates Resources Windows Path = C:\\WINDOWS\\resources Xamarin iOS = /Library AdminTools CommonAdminTools CommonDesktopDirectory CommonDocuments CommonMusic CommonPictures CommonProgramFiles CommonProgramFilesX86 CommonPrograms CommonStartMenu CommonStartup CommonVideos Cookies DesktopDirectory (Same as Desktop ) Favorites Fonts History LocalizedResources MyComputer MyMusic MyPictures MyVideos NetworkShortcuts Personal (Same as MyDocuments ) PrinterShortcuts ProgramFiles ProgramFilesX86 Programs Recent SendTo StartMenu Startup System SystemX86 Windows","title":"Special Folder Layout Renderer"},{"location":"Special-Folder-Layout-Renderer/#configuration-syntax","text":"${specialfolder:dir=String:file=String:folder=Enum} Example using CommonApplicationData which is good when running as Windows Service: fileName=\"${specialfolder:folder=CommonApplicationData:cached=true}/AppName/logfile.txt\" Windows-Path - C:/ProgramData/AppName/logfile.txt","title":"Configuration Syntax"},{"location":"Special-Folder-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Special-Folder-Layout-Renderer/#advanced-options","text":"dir - Name of the directory to be Path.Combine()'d with the directory name. file - Name of the file to be Path.Combine()'d with the directory name.","title":"Advanced Options"},{"location":"Special-Folder-Layout-Renderer/#rendering-options","text":"folder - System special folder to use. Full list of options is available at MSDN . The most common ones are: ApplicationData - Roaming application data for current user Windows Path = C:\\Users\\%USERNAME%\\AppData\\Roaming Xamarin Mono = $HOME/.config (or $XDG_CONFIG_HOME if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/.config Xamarin Android = /data/data/@PACKAGE_NAME@/files/.config LocalApplicationData - Non roaming application data for current user Windows Path = C:\\Users\\%USERNAME%\\AppData\\Local Xamarin Mono = $HOME/.local/share (or $XDG_DATA_HOME if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents Xamarin Android = /data/data/@PACKAGE_NAME@/files/.local/share CommonApplicationData - Application data for all users (Good when running as Windows Service) Windows Path = C:\\ProgramData Xamarin Mono = /usr/share Xamarin iOS = /usr/share Xamarin Android = /usr/share MyDocuments - My Documents Windows Path = C:\\Users\\%USERNAME%\\Documents Xamarin Mono = $HOME Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents Xamarin Android = /data/data/@PACKAGE_NAME@/files Desktop - My Desktop Windows Path = C:\\Users\\%USERNAME%\\Desktop Xamarin Mono = $HOME/Desktop (or $XDG_DESKTOP_DIR if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/Desktop Xamarin Android = /data/data/@PACKAGE_NAME@/files/Desktop UserProfile Windows Path = C:\\Users\\%USERNAME% Xamarin Mono = $HOME Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@ Xamarin Android = /data/data/@PACKAGE_NAME@/files Templates Windows Path = C:\\Users\\%USERNAME%\\AppData\\Roaming\\Microsoft\\Windows\\Templates Xamarin Mono = $HOME/Templates (or $XDG_TEMPLATES_DIR if set) Xamarin iOS = /data/Containers/Data/Application/@GENERATED_NAME@/Documents/Templates Xamarin Android = /data/data/@PACKAGE_NAME@/files/Templates CommonTemplates Windows Path = C:\\ProgramData\\Microsoft\\Windows\\Templates Xamarin Mono = /usr/share/templates Xamarin iOS = /usr/share/templates Xamarin Android = /usr/share/templates Resources Windows Path = C:\\WINDOWS\\resources Xamarin iOS = /Library AdminTools CommonAdminTools CommonDesktopDirectory CommonDocuments CommonMusic CommonPictures CommonProgramFiles CommonProgramFilesX86 CommonPrograms CommonStartMenu CommonStartup CommonVideos Cookies DesktopDirectory (Same as Desktop ) Favorites Fonts History LocalizedResources MyComputer MyMusic MyPictures MyVideos NetworkShortcuts Personal (Same as MyDocuments ) PrinterShortcuts ProgramFiles ProgramFilesX86 Programs Recent SendTo StartMenu Startup System SystemX86 Windows","title":"Rendering Options"},{"location":"SplitGroup-target/","text":"Writes log events to all wrapped targets. Platforms Supported: All \u2139\ufe0f For better performance, specify targets directly on the logging rule, optionally using NLog variables. Configuration Syntax ... Parameters General Options name - Name of the target.","title":"SplitGroup target"},{"location":"SplitGroup-target/#configuration-syntax","text":" ... ","title":"Configuration Syntax"},{"location":"SplitGroup-target/#parameters","text":"","title":"Parameters"},{"location":"SplitGroup-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Splunk-Target/","text":"Sends log messages to the remote instance of Splunk Server using Splunk JSON-format using TCP / UDP. Platforms Supported: All - Requires nuget-package NLog.Targets.Network This target inherits from the Network Target , and so it has also all the properties of the Network Target available. Using the SplunkLayout to produce Splunk JSON-format. Configuration Syntax Read more about using the Configuration File . Parameters General Options name - Name of the target. Payload Options layout - Instance of GelfLayout that is used to format log messages. Layout Default: GelfLayout SplunkHostName - Splunk Message Host-field. Default = ${hostname} SplunkSourceName - Splunk Message Source-field. Default = ${processname} SplunkSourceType - Splunk Message SourceType-field. Default = null SplunkIndex - Splunk Message Index-field. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. SplunkField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout) encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default) Connection Options address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: * Discard - Discard new messages when reaching limit (Default) * Grow - Send message and ignore limit * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6 Example ","title":"Splunk Target"},{"location":"Splunk-Target/#configuration-syntax","text":" Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Splunk-Target/#parameters","text":"","title":"Parameters"},{"location":"Splunk-Target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Splunk-Target/#payload-options","text":"layout - Instance of GelfLayout that is used to format log messages. Layout Default: GelfLayout SplunkHostName - Splunk Message Host-field. Default = ${hostname} SplunkSourceName - Splunk Message Source-field. Default = ${processname} SplunkSourceType - Splunk Message SourceType-field. Default = null SplunkIndex - Splunk Message Index-field. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. SplunkField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout) encoding - Encoding to be used. Encoding Default: utf-8 newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default)","title":"Payload Options"},{"location":"Splunk-Target/#connection-options","text":"address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: * Discard - Discard new messages when reaching limit (Default) * Grow - Send message and ignore limit * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6","title":"Connection Options"},{"location":"Splunk-Target/#example","text":" ","title":"Example"},{"location":"SplunkLayout/","text":"A specialized layout that renders each log event as the Splunk JSON format expected by the Splunk HTTP Event Collector (HEC). SplunkLayout renders the complete HEC event, including the outer time , host , source , sourcetype , index , and nested event fields. Platforms Supported: All - Requires nuget-package NLog.Targets.Network Layout Options SplunkHostName - Splunk Message Host-field. Default = ${hostname} SplunkSourceName - Splunk Message Source-field. Default = ${processname} SplunkSourceType - Splunk Message SourceType-field. Use _json to enable automatic extraction of fields from the JSON event object. Default = _json SplunkIndex - Splunk Message Index-field. The HEC token must have write-access to this index. No value means using HEC token's default index. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. SplunkField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout) Splunk HTTP Event Collector (HEC) SplunkLayout can be used with an HTTP target to send events to the Splunk HEC /services/collector/event endpoint using newline-delimited JSON (NDJSON). The HTTP target must provide the following HTTP header: Authorization: Splunk ","title":"SplunkLayout"},{"location":"SplunkLayout/#layout-options","text":"SplunkHostName - Splunk Message Host-field. Default = ${hostname} SplunkSourceName - Splunk Message Source-field. Default = ${processname} SplunkSourceType - Splunk Message SourceType-field. Use _json to enable automatic extraction of fields from the JSON event object. Default = _json SplunkIndex - Splunk Message Index-field. The HEC token must have write-access to this index. No value means using HEC token's default index. Default = null IncludeEventProperties - Include all properties from the log events. Default = true . IncludeScopeProperties - Include all scope-properties from the ScopeContext. Default = false . ExcludeEmptyProperties - Exclude null/empty properties. Default = false . ExcludeProperties - Comma separated string with names which properties to exclude. SplunkField name - Required. The name of the JSON-key layout - The layout for the JSON-value (Can be a nested JsonLayout)","title":"Layout Options"},{"location":"SplunkLayout/#splunk-http-event-collector-hec","text":"SplunkLayout can be used with an HTTP target to send events to the Splunk HEC /services/collector/event endpoint using newline-delimited JSON (NDJSON). The HTTP target must provide the following HTTP header: Authorization: Splunk ","title":"Splunk HTTP Event Collector (HEC)"},{"location":"Stack-Trace-Layout-Renderer/","text":"Render Stack trace of a log event. Platforms Supported: All Configuration Syntax ${stacktrace:format=Enum:topFrames=Integer:skipFrames=Integer:separator=String} Parameters Rendering Options format - Output format of the stack trace. Default: Flat Possible values: DetailedFlat - Detailed flat format (method signatures displayed in a single line). Flat - Flat format (class and method names displayed in a single line). Raw - Raw format (multiline - as returned by StackFrame.ToString() method). topFrames - Number of top stack frames to be rendered. Integer Default: 3 skipFrames - Numberof frames to skip. Integer Default: 0 separator - Stack frame separator string. Default: =>. To set new line use captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1 reverse - Whether to output the stacktrace in reverse order. Default: false Introduced with NLog 5.0 Examples Raw Note: To get the filenames and line numbers, include the PDB files. Note: Prior NLog 4.4.7, the result was always :0:0 Main at offset 638 in file:line:column file1.cs:100:10 TestLogging at offset 590 in file:line:column testlogger.cs:30:10 WriteToLog at offset 112 in file:line:column testlogger.cs:10:20 Flat Program.Main Program.TestLogging NLogLoggerHelper.LogEvent DetailedFlat [Int32 Main()] [Void TestLogging()] [Void WriteToLog(NLog.Logger, NLog.LogLevel, System.String)]","title":"Stack Trace Layout Renderer"},{"location":"Stack-Trace-Layout-Renderer/#configuration-syntax","text":"${stacktrace:format=Enum:topFrames=Integer:skipFrames=Integer:separator=String}","title":"Configuration Syntax"},{"location":"Stack-Trace-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Stack-Trace-Layout-Renderer/#rendering-options","text":"format - Output format of the stack trace. Default: Flat Possible values: DetailedFlat - Detailed flat format (method signatures displayed in a single line). Flat - Flat format (class and method names displayed in a single line). Raw - Raw format (multiline - as returned by StackFrame.ToString() method). topFrames - Number of top stack frames to be rendered. Integer Default: 3 skipFrames - Numberof frames to skip. Integer Default: 0 separator - Stack frame separator string. Default: =>. To set new line use captureStackTrace - Logger should capture StackTrace, if it was not provided manually. Default: true Introduced with NLog 4.7.1 reverse - Whether to output the stacktrace in reverse order. Default: false Introduced with NLog 5.0","title":"Rendering Options"},{"location":"Stack-Trace-Layout-Renderer/#examples","text":"","title":"Examples"},{"location":"Stack-Trace-Layout-Renderer/#raw","text":"Note: To get the filenames and line numbers, include the PDB files. Note: Prior NLog 4.4.7, the result was always :0:0 Main at offset 638 in file:line:column file1.cs:100:10 TestLogging at offset 590 in file:line:column testlogger.cs:30:10 WriteToLog at offset 112 in file:line:column testlogger.cs:10:20","title":"Raw"},{"location":"Stack-Trace-Layout-Renderer/#flat","text":"Program.Main Program.TestLogging NLogLoggerHelper.LogEvent","title":"Flat"},{"location":"Stack-Trace-Layout-Renderer/#detailedflat","text":"[Int32 Main()] [Void TestLogging()] [Void WriteToLog(NLog.Logger, NLog.LogLevel, System.String)]","title":"DetailedFlat"},{"location":"Substring-layout-renderer/","text":"Substring the result Platforms Supported: All Introduced in NLog 4.6 Related: ${left} ${right} Configuration Syntax ${substring:inner=Layout:length=Integer:start=Integer} Read more about using the Configuration File . Parameters Transformation Options inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout length - Length in characters. If null , then the whole string Integer . Default: null start - Start index. Integer Default: 0","title":"Substring layout renderer"},{"location":"Substring-layout-renderer/#configuration-syntax","text":"${substring:inner=Layout:length=Integer:start=Integer} Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Substring-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"Substring-layout-renderer/#transformation-options","text":"inner - Wrapped layout. [DefaultParameter] so Inner: is not required if it's the first Layout length - Length in characters. If null , then the whole string Integer . Default: null start - Start index. Integer Default: 0","title":"Transformation Options"},{"location":"Syslog-Target/","text":"Sends log messages to the remote instance of Syslog Server. Platforms Supported: All - Requires nuget-package NLog.Targets.Network This target inherits from the Network Target , and so it has also all the properties of the Network Target available. Using the SyslogLayout to produce Syslog output. Configuration Syntax true false Read more about using the Configuration File . Parameters General Options name - Name of the target. Payload Options layout - Instance of SyslogLayout that is used to format log messages. Layout Default: SyslogLayout Rfc5424 - Rfc5424 as Syslog Format. Default = true. Rfc3164 - Rfc3164 as Syslog Format. Default = false. SyslogHostName - Hostname of the sender machine. Default = ${hostname} SyslogAppName - Name of the device / application / process sending the Syslog-message. Default = ${processname} SyslogProcessId - Process Id or Process Name or Logger Name. Default = ${processid} SyslogMessage - Syslog Message Payload. Default = ${message}${onexception:|}${exception:format=shortType,message} . SyslogMessageId - EventId to recognize the Syslog Message Type. SyslogLevel - Syslog Level Mapping . Default automatically converts from NLog LogLevel. SyslogFacility - Syslog Device Facility . Default = User SyslogTimestamp - Syslog DateTime Format when Rfc5424. Default = ${date:format=o} IncludeEventProperties - Include all properties from the log events when Rfc5424. Default = true . ExcludeEmptyProperties - Exclude event properties with value null or empty when Rfc5424. Default = false . Introduced with NLog.Targets.Network v6.1.6 ExcludeProperties - Comma separated string with names which properties to exclude when Rfc5424. Case insensitive. Default empty. Introduced with NLog.Targets.Network v6.1.6 StructuredDataId - Prefix for StructuredData when Rfc5424. Default = meta StructuredDataParam name - Structured property-name when Rfc5424 layout - Structured property-value layout newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default) Connection Options address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: * Discard - Discard new messages when reaching limit (Default) * Grow - Send message and ignore limit * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6 Example true false ","title":"Syslog Target"},{"location":"Syslog-Target/#configuration-syntax","text":" true false Read more about using the Configuration File .","title":"Configuration Syntax"},{"location":"Syslog-Target/#parameters","text":"","title":"Parameters"},{"location":"Syslog-Target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Syslog-Target/#payload-options","text":"layout - Instance of SyslogLayout that is used to format log messages. Layout Default: SyslogLayout Rfc5424 - Rfc5424 as Syslog Format. Default = true. Rfc3164 - Rfc3164 as Syslog Format. Default = false. SyslogHostName - Hostname of the sender machine. Default = ${hostname} SyslogAppName - Name of the device / application / process sending the Syslog-message. Default = ${processname} SyslogProcessId - Process Id or Process Name or Logger Name. Default = ${processid} SyslogMessage - Syslog Message Payload. Default = ${message}${onexception:|}${exception:format=shortType,message} . SyslogMessageId - EventId to recognize the Syslog Message Type. SyslogLevel - Syslog Level Mapping . Default automatically converts from NLog LogLevel. SyslogFacility - Syslog Device Facility . Default = User SyslogTimestamp - Syslog DateTime Format when Rfc5424. Default = ${date:format=o} IncludeEventProperties - Include all properties from the log events when Rfc5424. Default = true . ExcludeEmptyProperties - Exclude event properties with value null or empty when Rfc5424. Default = false . Introduced with NLog.Targets.Network v6.1.6 ExcludeProperties - Comma separated string with names which properties to exclude when Rfc5424. Case insensitive. Default empty. Introduced with NLog.Targets.Network v6.1.6 StructuredDataId - Prefix for StructuredData when Rfc5424. Default = meta StructuredDataParam name - Structured property-name when Rfc5424 layout - Structured property-value layout newLine - Indicates whether to append newline at the end of log message. Boolean Default: False lineEnding - Line Ending to be used if newLine is set to true. LineEndingMode Default: CRLF . Not used if newLine is false . Possible values: CRLF - Carriage Return and Line Feed (ASCII 13, ASCII 10). (default) CR - Carriage Return (ASCII 13). LF - Line Feed (ASCII 10). NULL - Null terminator (ASCII 0) None - No end of line characters. maxMessageSize - Maximum message size in bytes. Integer Default: 65000 onOverflow - Action that should be taken if the message-size is larger than maxMessageSize . Possible values: Discard - Discard the entire message. Error - Report an error. Split - Split the message into smaller pieces (Default)","title":"Payload Options"},{"location":"Syslog-Target/#connection-options","text":"address - Network address. Layout The network address can be: tcp://host:port - TCP (auto select IPv4/IPv6) tcp4://host:port - force TCP/IPv4 tcp6://host:port - force TCP/IPv6 udp://host:port - UDP (auto select IPv4/IPv6) udp4://host:port - force UDP/IPv4 udp6://host:port - force UDP/IPv6 http://host:port/pageName - HTTP using POST verb https://host:port/pageName - HTTPS using POST verb keepConnection - Indicates whether to keep connection open whenever possible. Boolean Default: True connectionCacheSize - Size of the connection cache (number of connections which are kept alive). Integer Default: 5 maxConnections - Maximum current connections. 0 = no maximum. Integer Default: 16 . Not used if keepConnection is true . onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections . Possible enum values: * Discard - Discard new messages when reaching limit (Default) * Grow - Send message and ignore limit * Block - Block until pending connections has been freed. maxQueueSize - Maximum queue size for a single connection. 0 means no limit. Integer . Default: 10000 onQueueOverflow - Action that should be taken if pending queue of messages is larger than maxQueueSize . Discard - Discard the entire message (Default) Grow - Ignore limit and grow the queue. Block - Block until queue is below limit. KeepAliveTimeSeconds - Idle time before first TCP keep-alive probe is sent. Faster detection of stale TCP connections. Currently only implemented for TCP. Integer . Default: 0 (Disabled) SendTimeoutSeconds - Waiting time before TCP socket send-operation fails with timeout error. Default wait forever when network cable unplugged and tcp-buffer becomes full. Integer . Default: 0 (Disabled) NoDelay - Disable the delayed ACK timer, and avoid delay of 200 ms. Default = true. sslProtocols - Enables SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. Invalid certificates are not supported. Possible values (combination allowed, comma separated): None - No SSL/TLS is used Default - Accepts Tls or Ssl3 Ssl2 - really not recommended Ssl3 - not recommended Tls - TLS 1.0 Tls11 - TLS 1.1 Tls12 - TLS 1.2 SslCertificateFile - Enables loading SSL certificate from local file, instead of injecting into operating system cache (Blank value means disable SSL certificate validation) SslCertificatePassword - When password is needed for loading SSL certificate from local file using SslCertificateFile SslCertificateThumbprint - Enables loading SSL certificate using thumbprint from operating system store (First CurrentUser, then LocalMachine) Introduced in NLog.Targets.Network v6.1.6","title":"Connection Options"},{"location":"Syslog-Target/#example","text":" true false ","title":"Example"},{"location":"SyslogLayout/","text":"A specialized layout that renders to Syslog Server Format. Platforms Supported: All - Requires nuget-package NLog.Targets.Network false true Layout Options Rfc5424 - Rfc5424 as Syslog Format. Default = true. Rfc3164 - Rfc3164 as Syslog Format. Default = false. SyslogHostName - Hostname of the sender machine. Default = ${hostname} SyslogAppName - Name of the device / application / process sending the Syslog-message. Default = ${processname} SyslogProcessId - Process Id or Process Name or Logger Name. Default = ${processid} SyslogMessage - Syslog Message Payload. Default = ${message}${onexception:|}${exception:format=shortType,message} . SyslogMessageId - EventId to recognize the Syslog Message Type. SyslogLevel - Syslog Level Mapping. SyslogFacility - Syslog Device Facility. Default = User SyslogTimestamp - Syslog DateTime Format when Rfc5424. Default = ${date:format=o} IncludeEventProperties - Include all properties from the log events when Rfc5424. Default = true . ExcludeEmptyProperties - Exclude event properties with value null or empty when Rfc5424. Default = false . Introduced with NLog.Targets.Network v6.1.6 ExcludeProperties - Comma separated string with names which properties to exclude when Rfc5424. Case insensitive. Default empty. Introduced with NLog.Targets.Network v6.1.6 StructuredDataId - Prefix for StructuredData when Rfc5424. Default = meta StructuredDataParam name - Structured property-name when Rfc5424 layout - Structured property-value layout","title":"SyslogLayout"},{"location":"SyslogLayout/#layout-options","text":"Rfc5424 - Rfc5424 as Syslog Format. Default = true. Rfc3164 - Rfc3164 as Syslog Format. Default = false. SyslogHostName - Hostname of the sender machine. Default = ${hostname} SyslogAppName - Name of the device / application / process sending the Syslog-message. Default = ${processname} SyslogProcessId - Process Id or Process Name or Logger Name. Default = ${processid} SyslogMessage - Syslog Message Payload. Default = ${message}${onexception:|}${exception:format=shortType,message} . SyslogMessageId - EventId to recognize the Syslog Message Type. SyslogLevel - Syslog Level Mapping. SyslogFacility - Syslog Device Facility. Default = User SyslogTimestamp - Syslog DateTime Format when Rfc5424. Default = ${date:format=o} IncludeEventProperties - Include all properties from the log events when Rfc5424. Default = true . ExcludeEmptyProperties - Exclude event properties with value null or empty when Rfc5424. Default = false . Introduced with NLog.Targets.Network v6.1.6 ExcludeProperties - Comma separated string with names which properties to exclude when Rfc5424. Case insensitive. Default empty. Introduced with NLog.Targets.Network v6.1.6 StructuredDataId - Prefix for StructuredData when Rfc5424. Default = meta StructuredDataParam name - Structured property-name when Rfc5424 layout - Structured property-value layout","title":"Layout Options"},{"location":"Targets-and-Wrappers/","text":"Moved to Targets","title":"Targets and Wrappers"},{"location":"Targets/","text":"Use Targets are used to display, store, or pass log messages to another destination. There are two kinds of target: 1. Targets that writes the LogEvents 2. 'Wrapper' Targets that apply additional logic when writing to wrapped Target. Logic can be filtering / batching / retry-on-error / etc. Available Targets List of NLog targets can found here: https://nlog-project.org/config/?tab=targets Nuget Packages from NLog Writing your own target NLog can be extended with custom new targets. For more information, see: Extending-NLog","title":"Targets"},{"location":"Targets/#use","text":"Targets are used to display, store, or pass log messages to another destination. There are two kinds of target: 1. Targets that writes the LogEvents 2. 'Wrapper' Targets that apply additional logic when writing to wrapped Target. Logic can be filtering / batching / retry-on-error / etc.","title":"Use"},{"location":"Targets/#available-targets","text":"List of NLog targets can found here: https://nlog-project.org/config/?tab=targets Nuget Packages from NLog","title":"Available Targets"},{"location":"Targets/#writing-your-own-target","text":"NLog can be extended with custom new targets. For more information, see: Extending-NLog","title":"Writing your own target"},{"location":"TempDir-Layout-Renderer/","text":"The temporary directory on the local machine. Platforms Supported: All See also ${basedir} , ${processdir} , ${specialfolder} , ${currentdir} Configuration Syntax ${tempdir:dir=String:file=String} Parameters Advanced Options dir - Name of the directory to be Path.Combine()'d with the directory name. file - Name of the file to be Path.Combine()'d with the directory name.","title":"TempDir Layout Renderer"},{"location":"TempDir-Layout-Renderer/#configuration-syntax","text":"${tempdir:dir=String:file=String}","title":"Configuration Syntax"},{"location":"TempDir-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"TempDir-Layout-Renderer/#advanced-options","text":"dir - Name of the directory to be Path.Combine()'d with the directory name. file - Name of the file to be Path.Combine()'d with the directory name.","title":"Advanced Options"},{"location":"TextLayout/","text":"Page moved here: https://github.com/NLog/NLog/wiki/SimpleLayout","title":"TextLayout"},{"location":"ThreadId-Layout-Renderer/","text":"The identifier of the current thread. Platforms Supported: All Configuration Syntax ${threadid}","title":"ThreadId Layout Renderer"},{"location":"ThreadId-Layout-Renderer/#configuration-syntax","text":"${threadid}","title":"Configuration Syntax"},{"location":"ThreadName-Layout-Renderer/","text":"The name of the current thread. Platforms Supported: All Configuration Syntax ${threadname}","title":"ThreadName Layout Renderer"},{"location":"ThreadName-Layout-Renderer/#configuration-syntax","text":"${threadname}","title":"Configuration Syntax"},{"location":"Ticks-Layout-Renderer/","text":"The Ticks value of current date and time. Platforms Supported: All Configuration Syntax ${ticks}","title":"Ticks Layout Renderer"},{"location":"Ticks-Layout-Renderer/#configuration-syntax","text":"${ticks}","title":"Configuration Syntax"},{"location":"Time-Layout-Renderer/","text":"The time in a 24-hour, sortable format HH:mm:ss.ffff . Platforms Supported: All See also ${processtime} , ${date} , ${longdate} , ${shortdate} Configuration Syntax ${time:universalTime=Boolean:invariant=Boolean} Parameters Rendering Options universalTime - Indicates whether to output UTC time instead of local time. Boolean Default: False invariant - Indicates whether to output in invariant time format, and not lookup of current cultureinfo. Boolean Default: true (Before NLog 5.0 the default was false) Introduced with NLog 4.5.2 culture - Culture used for time format. Default: InvariantCulture Introduced with NLog 5.0 Time Source Precision NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Time Layout Renderer"},{"location":"Time-Layout-Renderer/#configuration-syntax","text":"${time:universalTime=Boolean:invariant=Boolean}","title":"Configuration Syntax"},{"location":"Time-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Time-Layout-Renderer/#rendering-options","text":"universalTime - Indicates whether to output UTC time instead of local time. Boolean Default: False invariant - Indicates whether to output in invariant time format, and not lookup of current cultureinfo. Boolean Default: true (Before NLog 5.0 the default was false) Introduced with NLog 4.5.2 culture - Culture used for time format. Default: InvariantCulture Introduced with NLog 5.0","title":"Rendering Options"},{"location":"Time-Layout-Renderer/#time-source-precision","text":"NLog uses local-time by default, but because conversion from machine-time to local-time has an overhead, then NLog uses cached time-source FastLocal with 15ms time-precision that follows Environment.TickCount . For high time-precision and still fast performance, then consider using Time-source AccurateUtc (Time-precision of 1ms)","title":"Time Source Precision"},{"location":"Time-Source/","text":"NLog outputs its timestamps in local time by default, as this is expected by most first time users. The conversion from machine time to regional local time has an overhead, so NLog uses a cached time-source ( FastLocal ) by default, which only refreshes every 15 msec (Follows Environment.TickCount ) NLog has the ability to change the time source, that provides timestamping of LogEvents. This can be done from code, and also via XML-file. The following sections were based and/or provided by Robert Va\u017ean\u2019s blog : NLog timestamps with millisecond accuracy How to configure NLog time source How to write custom NLog time source Configure Via XML The time source can be configured via XML by setting the time element with the XML name. The provided time sources don\u2019t include \u201cTimeSource\u201d in their XML names. Configure Via Runtime Configuration The time source can be configured by inserting the following before any log messages are printed: NLog.Time.TimeSource.Current = new NLog.Time.AccurateUtcTimeSource(); Provided Time Sources The time source implementations that are included with NLog, either provides local-time or UTC-time. Where NLog uses FastLocal by default with low accuracy, but high performance. For almost monotonic timestamp then consider using AccurateUTC : XML Configuration Is Default? Runtime Configuration Time Accuracy Speed FastLocal Yes FastLocalTimeSource local 16ms very fast FastUTC No FastUtcTimeSource UTC 16ms very fast AccurateLocal No AccurateLocalTimeSource local 1ms slow AccurateUTC No AccurateUtcTimeSource UTC 1ms fast Performance benchmarks for time source implementations (used BenchmarkDotNet ): Method 32-bit Mean 64-bit Mean FastLocal 5.205 ns 3.546 ns FastUtc 5.202 ns 3.541 ns AccurateLocal 190.481 ns 85.927 ns AccurateUtc 137.258 ns 66.451 ns The accuracy relates directly to Windows and how it balances accuracy, speed, and efficiency (i.e. battery life). By default, Windows is set to 16ms of accuracy, but can be changed via the API calls of timeBeginPeriod and timeEndPeriod . Custom Time Source Before implementing your own time source, see the provided time sources first. If none of those fit your needs, this section will guide you through the process. Create a class that inherits from TimeSource and implement the inherited property getter Time and method FromSystemTime . The property getter Time provides the current time instance. The method FromSystemTime converts the system time to the same form as if the time source provided it. [TimeSource(\"CustomTimeZone\")] public class CustomTimeZoneTimeSource : TimeSource { string ZoneName; TimeZoneInfo ZoneInfo; [Required] public string Zone { get { return ZoneName; } set { ZoneName = value; ZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(value); } } public override DateTime Time { get { return TimeZoneInfo.ConvertTimeFromUtc( DateTime.UtcNow, ZoneInfo); } } public override DateTime FromSystemTime(DateTime systemTime) { return TimeZoneInfo.ConvertTimeFromUtc(systemTime, ZoneInfo); } } In addition, add an attribute to the top that provides the name when specifying the type via XML. Your custom time source can be loaded by NLog just like any other NLog extension. See how to use the custom target / layout renderer . The Runtime Configuration would look like this: TimeSource.Current = new CustomTimeZoneTimeSource() { Zone = \"Central Standard Time\" } The XML Configuration would look like this: ","title":"Time Source"},{"location":"Time-Source/#configure-via-xml","text":"The time source can be configured via XML by setting the time element with the XML name. The provided time sources don\u2019t include \u201cTimeSource\u201d in their XML names. ","title":"Configure Via XML"},{"location":"Time-Source/#configure-via-runtime-configuration","text":"The time source can be configured by inserting the following before any log messages are printed: NLog.Time.TimeSource.Current = new NLog.Time.AccurateUtcTimeSource();","title":"Configure Via Runtime Configuration"},{"location":"Time-Source/#provided-time-sources","text":"The time source implementations that are included with NLog, either provides local-time or UTC-time. Where NLog uses FastLocal by default with low accuracy, but high performance. For almost monotonic timestamp then consider using AccurateUTC : XML Configuration Is Default? Runtime Configuration Time Accuracy Speed FastLocal Yes FastLocalTimeSource local 16ms very fast FastUTC No FastUtcTimeSource UTC 16ms very fast AccurateLocal No AccurateLocalTimeSource local 1ms slow AccurateUTC No AccurateUtcTimeSource UTC 1ms fast Performance benchmarks for time source implementations (used BenchmarkDotNet ): Method 32-bit Mean 64-bit Mean FastLocal 5.205 ns 3.546 ns FastUtc 5.202 ns 3.541 ns AccurateLocal 190.481 ns 85.927 ns AccurateUtc 137.258 ns 66.451 ns The accuracy relates directly to Windows and how it balances accuracy, speed, and efficiency (i.e. battery life). By default, Windows is set to 16ms of accuracy, but can be changed via the API calls of timeBeginPeriod and timeEndPeriod .","title":"Provided Time Sources"},{"location":"Time-Source/#custom-time-source","text":"Before implementing your own time source, see the provided time sources first. If none of those fit your needs, this section will guide you through the process. Create a class that inherits from TimeSource and implement the inherited property getter Time and method FromSystemTime . The property getter Time provides the current time instance. The method FromSystemTime converts the system time to the same form as if the time source provided it. [TimeSource(\"CustomTimeZone\")] public class CustomTimeZoneTimeSource : TimeSource { string ZoneName; TimeZoneInfo ZoneInfo; [Required] public string Zone { get { return ZoneName; } set { ZoneName = value; ZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(value); } } public override DateTime Time { get { return TimeZoneInfo.ConvertTimeFromUtc( DateTime.UtcNow, ZoneInfo); } } public override DateTime FromSystemTime(DateTime systemTime) { return TimeZoneInfo.ConvertTimeFromUtc(systemTime, ZoneInfo); } } In addition, add an attribute to the top that provides the name when specifying the type via XML. Your custom time source can be loaded by NLog just like any other NLog extension. See how to use the custom target / layout renderer . The Runtime Configuration would look like this: TimeSource.Current = new CustomTimeZoneTimeSource() { Zone = \"Central Standard Time\" } The XML Configuration would look like this: ","title":"Custom Time Source"},{"location":"ToolStripItem-Target/","text":"Page moved to ToolStripItemTarget - NLog.Windows.Forms","title":"ToolStripItem Target"},{"location":"Tools/","text":"Log Viewers/Analyzers Logs produced by NLog can be analyzed using a number of GUI tools: NLog-specific viewers Gibraltar (using Gibraltar Adapter for NLog) - https://nlog-project.org/2009/11/01/gibraltar-adapter-for-nlog-released.html Sentinel - https://github.com/yarseyah/sentinel NLogViewer - http://github.com/jkowalski/NLogViewer (functional, but no longer in development, not recommended) LogEntries - http://www.logentries.com (service for cloud logging, has .net NLog target) Legit Log Viewer - http://www.legitlog.com/ (Although their website is down, it is Free and powerful log viewer.) ReflectInsight Viewer (using the ReflectInsight Extension for NLog) - http://insightextensions.codeplex.com/ Log4x-compatible viewers In general, any viewer supporting Log4J or Log4Net should work fine with NLog - see Chainsaw Target for information on configuring NLog for use with those viewers. * LogWizard - https://github.com/jtorjo/logwizard * Apache Chainsaw v2 - https://logging.apache.org/chainsaw/ * ~~DevIntelligence Log4Net Viewer - http://devintelligence.com/log4netviewer/~~ (questionable status) * C# WPF Log4Net Viewer - https://www.codeproject.com/KB/cs/logviewer.aspx * ~~Log4Net Dashboard - http://www.l4ndash.com/~~ (questionable status) * Log4View - http://www.log4view.com/ * Log2Console - https://github.com/Statyk7/log2console * ~~Legit Log Viewer - http://www.legitlog.com/~~ (questionable status) * ReflectInsight Viewer (using the ReflectInsight Extension for Log4net) - http://insightextensions.codeplex.com/ * Free Log File Viewer: Log4Net Log4J NLog - https://sourceforge.net/projects/gamutlogviewer/ * Lilith * OtrosLogViewer * LogViewer","title":"Tools"},{"location":"Tools/#log-viewersanalyzers","text":"Logs produced by NLog can be analyzed using a number of GUI tools:","title":"Log Viewers/Analyzers"},{"location":"Tools/#nlog-specific-viewers","text":"Gibraltar (using Gibraltar Adapter for NLog) - https://nlog-project.org/2009/11/01/gibraltar-adapter-for-nlog-released.html Sentinel - https://github.com/yarseyah/sentinel NLogViewer - http://github.com/jkowalski/NLogViewer (functional, but no longer in development, not recommended) LogEntries - http://www.logentries.com (service for cloud logging, has .net NLog target) Legit Log Viewer - http://www.legitlog.com/ (Although their website is down, it is Free and powerful log viewer.) ReflectInsight Viewer (using the ReflectInsight Extension for NLog) - http://insightextensions.codeplex.com/","title":"NLog-specific viewers"},{"location":"Tools/#log4x-compatible-viewers","text":"In general, any viewer supporting Log4J or Log4Net should work fine with NLog - see Chainsaw Target for information on configuring NLog for use with those viewers. * LogWizard - https://github.com/jtorjo/logwizard * Apache Chainsaw v2 - https://logging.apache.org/chainsaw/ * ~~DevIntelligence Log4Net Viewer - http://devintelligence.com/log4netviewer/~~ (questionable status) * C# WPF Log4Net Viewer - https://www.codeproject.com/KB/cs/logviewer.aspx * ~~Log4Net Dashboard - http://www.l4ndash.com/~~ (questionable status) * Log4View - http://www.log4view.com/ * Log2Console - https://github.com/Statyk7/log2console * ~~Legit Log Viewer - http://www.legitlog.com/~~ (questionable status) * ReflectInsight Viewer (using the ReflectInsight Extension for Log4net) - http://insightextensions.codeplex.com/ * Free Log File Viewer: Log4Net Log4J NLog - https://sourceforge.net/projects/gamutlogviewer/ * Lilith * OtrosLogViewer * LogViewer","title":"Log4x-compatible viewers"},{"location":"Trace-Activity-Id-Layout-Renderer/","text":"Outputs the Trace.CorrelationManager.ActivityId as trace correlation id. Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6 Introduced in NLog v4.1. Configuration Syntax ${activityid} Remarks \u26a0\ufe0f Trace.CorrelationManager.ActivityId is now considered legacy and instead replaced by System.Diagnostics.Activity . See also: ${activity} If the Trace.CorrelationManager.ActivityId is equal to Guid.Empty , then appends String.Empty , otherwise appends Trace.CorrelationManager.ActivityId as separated by hyphens according to the CultureInfo.InvariantCulture . Example For an ASP.NET IIS application, initialize the Trace.CorrelationManager.ActivityId in the Global.asax.cs , Application_BeginRequest event: protected void Application_BeginRequest(object sender, EventArgs e) { ... if (Trace.CorrelationManager.ActivityId == Guid.Empty) { Trace.CorrelationManager.ActivityId = Guid.NewGuid(); } } Notice IIS Express might automatically setup ActivityId without needing the above code.","title":"Trace Activity Id Layout Renderer"},{"location":"Trace-Activity-Id-Layout-Renderer/#configuration-syntax","text":"${activityid}","title":"Configuration Syntax"},{"location":"Trace-Activity-Id-Layout-Renderer/#remarks","text":"\u26a0\ufe0f Trace.CorrelationManager.ActivityId is now considered legacy and instead replaced by System.Diagnostics.Activity . See also: ${activity} If the Trace.CorrelationManager.ActivityId is equal to Guid.Empty , then appends String.Empty , otherwise appends Trace.CorrelationManager.ActivityId as separated by hyphens according to the CultureInfo.InvariantCulture .","title":"Remarks"},{"location":"Trace-Activity-Id-Layout-Renderer/#example","text":"For an ASP.NET IIS application, initialize the Trace.CorrelationManager.ActivityId in the Global.asax.cs , Application_BeginRequest event: protected void Application_BeginRequest(object sender, EventArgs e) { ... if (Trace.CorrelationManager.ActivityId == Guid.Empty) { Trace.CorrelationManager.ActivityId = Guid.NewGuid(); } } Notice IIS Express might automatically setup ActivityId without needing the above code.","title":"Example"},{"location":"Trace-target/","text":"Sends log messages through System.Diagnostics.Trace. Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6 Configuration Syntax Parameters General Options name - Name of the target. Output Options layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} rawWrite - Always use Trace.WriteLine independent of LogLevel. Default: False Introduced with NLog 4.5, fixes the issue with output being prefixed with exe-filename. EnableTraceFail - Use Trace.Fail for LogLevel.Fatal, instead of Trace.Error . Default: False Introduced with NLog 4.7, avoids Enviroment.FailFast that can happen for default trace listener. header - Layout used to format header-output when initializing. Layout Introduced with NLog 5.0 footer - Layout used to format footer-output when closing. Layout Introduced with NLog 5.0 Notes Alternative targets for diagnostic output: - DebugSystem-target for output to System.Diagnostics.Debug - Debugger-target for output to System.Diagnostics.Debugger.Log - OutputDebugString-target for output to OutputDebugString Win32 API","title":"Trace target"},{"location":"Trace-target/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"Trace-target/#parameters","text":"","title":"Parameters"},{"location":"Trace-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"Trace-target/#output-options","text":"layout - Layout used to format log messages. Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true} rawWrite - Always use Trace.WriteLine independent of LogLevel. Default: False Introduced with NLog 4.5, fixes the issue with output being prefixed with exe-filename. EnableTraceFail - Use Trace.Fail for LogLevel.Fatal, instead of Trace.Error . Default: False Introduced with NLog 4.7, avoids Enviroment.FailFast that can happen for default trace listener. header - Layout used to format header-output when initializing. Layout Introduced with NLog 5.0 footer - Layout used to format footer-output when closing. Layout Introduced with NLog 5.0","title":"Output Options"},{"location":"Trace-target/#notes","text":"Alternative targets for diagnostic output: - DebugSystem-target for output to System.Diagnostics.Debug - Debugger-target for output to System.Diagnostics.Debugger.Log - OutputDebugString-target for output to OutputDebugString Win32 API","title":"Notes"},{"location":"Trim-Whitespace-Layout-Renderer/","text":"Trims the whitespace from the result of another layout renderer. Platforms Supported: All Configuration Syntax ${trim-whitespace:trimWhiteSpace=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:trimWhiteSpace=Boolean} Parameters Transformation Options trimWhiteSpace - Indicates whether trim should be applied. Boolean Default: True inner - Wrapped layout. Layout","title":"Trim Whitespace Layout Renderer"},{"location":"Trim-Whitespace-Layout-Renderer/#configuration-syntax","text":"${trim-whitespace:trimWhiteSpace=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:trimWhiteSpace=Boolean}","title":"Configuration Syntax"},{"location":"Trim-Whitespace-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Trim-Whitespace-Layout-Renderer/#transformation-options","text":"trimWhiteSpace - Indicates whether trim should be applied. Boolean Default: True inner - Wrapped layout. Layout","title":"Transformation Options"},{"location":"Tutorial/","text":"NLog can be setup with the following steps: Install NLog nuget package Configure NLog Targets for output Writing log messages After having setup NLog, then make sure to explore: Layouts and LayoutRenderers Target Wrappers Best practices for using NLog Frequently Asked Questions If something is not working as expected then check the Troubleshooting section. If wanting to use Microsoft Extension Logging (MEL) then check .NET Core and ASP.NET Core tutorials. Configure NLog Targets for output NLog will only produce output if having configured one (or more) NLog targets. NLog can be configured using XML by adding a NLog.config file to your application project (File Properties: Copy If newer). NLog will automatically load the NLog.config by searching multiple file locations . This is a simple example of the content for NLog.config : Alternative one can configure programmatically by doing this in code: var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget(\"logfile\") { FileName = \"logfile.txt\" }; var logconsole = new NLog.Targets.ConsoleTarget(\"logconsole\"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; NLog 5.0 introduces a Fluent-Configuration-API so you can do this instead: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: \"logfile.txt\"); }); The rules redirects logger output to the wanted output targets. The rules also provides filtering options to output only relevant logevents. Usually based on logger-name and loglevel (Ex. name=\"*\" minlevel=\"Trace\" means everything). See also Configuration File or Configure from code See also Available NLog Targets for output. Writing log messages public static class Program { private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); public static void Main() { try { Logger.Info(\"Hello world\"); System.Console.ReadKey(); } catch (Exception ex) { Logger.Error(ex, \"Goodbye cruel world\"); } } } The Logger can write messages with different LogLevels, which is used by the logging-rules (See minLevel in configuration example above) so only relevant messages are redirected to the wanted targets. The LogLevel identifies how important/detailed the message is. NLog can route log messages based primarily on their logger name and log level. The log levels ordered by severity: LogLevel Severity Typical Use Trace Most verbose level. Used for development and seldom enabled in production. Ex. Request-payload, Response-payload, Begin-method-X or End-method-X Debug Debugging the application behavior from internal events of interest. Ex. Executed query, User authenticated, Session expired Info Information about application lifetime events like starting/stopping and configuration changes. Warn Warnings about validation issues or temporary failures that can be recovered. Error Errors where functionality has failed or Exception have been caught. Fatal Most critical level. Application is about to abort. The logger is not tied to a specific target. The messages written to one logger can reach multiple targets based on the Configuration-file#rules . Maintaining this separation lets you keep logging statements in your code and easily change how and where the logs are written, just by updating the configuration in one place. See also Filtering log messages . Instead of using NLog Logger directly, then NLog also supports logging abstractions like Microsoft Extension Logging or LibLog . Layouts and LayoutRenderers NLog allows you to customize how log messages are written to a NLog target. This shows the default SimpleLayout used by most NLog targets: This can be configured to include extra context information (Ex ${threadid} ): See full list here: Layout Renderers One can also use a more complex Layout instead of SimpleLayout : * CsvLayout * JsonLayout * XmlLayout See full list here: Layouts Target Wrappers NLog supports special kinds of targets which do not do any logging by themselves, but extends the behavior of destination target. Those targets are called wrappers. The most commonly used ones are: * AsyncWrapper - Improves Performance by providing asynchronous, buffered execution of target writes. * BufferingWrapper - Simple batching of log messages. Maybe only send batch when certain log event occurs (Ex. Exception). * FallbackGroup - Provides fallback-on-error. * RetryingWrapper - Provides retry-on-error. See full list here: Target Wrappers There is a shortcut for enabling the AsyncWrapper for all targets, by adding async=\"true\" : This will make all writes to the file be asynchronous, which will improve responsiveness of the calling thread. Best practices for using NLog 1. Logger should be a static variable in each class When using LogManager.GetCurrentClassLogger : Creating a new Logger has a small overhead, as it has to acquire locks and allocate objects. Therefore it is recommended to create the logger like this: namespace MyNamespace { public class MyClass { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); } } 2. Logger should handle string formatting Avoid performing string allocation or string concatenation upfront, but instead let the Logger do the formatting. This will allow NLog to defer the formatting and improve performance . Either using Structured logging that captures parameters as named properties: logger.Info(\"Hello {World}\", \"Earth\"); Or using string-format syntax: logger.Info(\"Hello {0}\", \"Earth\"); 3. Logger should be given the Exception Avoid giving the Exception as formatting parameter, but instead provide it explicitly as first parameter. This will help the NLog targets to provide better logging. try { } catch (Exception ex) { logger.Error(ex, \"Something bad happened\"); } 4. Validate XML configuration from NLog.config NLog swallows by default all exceptions, so problems with logging will not cause the application to break. But for many application the logging is very critical, so if the initial NLog configuration fails, then it is fatal. Adding throwConfigExceptions=\"true\" will make NLog complain when something is wrong with the configuration: There is also a setting called throwExceptions=\"true\" , which should never be used in production as it can cause havoc for your application. It is intended for unit testing and local troubleshooting. See also Troubleshooting Configuration It is also a good idea to check output from NLog InternalLogger , as it can give alerts when detecting problems with the NLog configuration. 5. Remember to Flush NLog will by default attempt to flush automatically at application shutdown. Microsoft Windows give .NET applications a limited amount of time to perform shutdown (usually 2 sec) before being terminated. If having a NLog configuration with NLog Targets that requires network-traffic (Http, Mail, Tcp), then it is a really good idea to perform a manual Flush/Shutdown independent on running on Linux/Windows. NLog.LogManager.Shutdown(); // Flush and close down internal threads and timers NET Application running on Mono/Linux are required to stop threads/timers before entering application shutdown phase. Failing to do this will cause unhandled exceptions and segmentation faults, and other unpredictable behavior. NET 10.0 (and newer) no longer signals AppDomain.ProcessExit or AssemblyLoadContext.Unloading independent on running on Windows/Linux. So just like using LogManager.AutoShutdown = false . 6. Unhandled exeptions When non-background threads dies because of unhandled Exception, then the entire application will die. For better diagnostics, then one can listen for unhandled exceptions and forward to NLog at application startup: AppDomain.CurrentAppDomain.UnhandledException += (s, e) => { NLog.LogManager.GetLogger(\"Application\").Error(e.ExceptionObject as Exception, \"Unhandled Application Exception\"); NLog.LogManager.Flush(); // Ensure logs are written before application dies }; When async Tasks dies because of unobserved Exception and finalized, then the application will continue without making any noise. For better diagnostics, then one can listen for unobserved exceptions and forward to NLog at application startup: System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (s, e) => { if (e.Exception is System.OperationCanceledException) NLog.LogManager.GetLogger(\"Application\").Info(e.Exception, \"Unobserved Task Cancellation\"); else NLog.LogManager.GetLogger(\"Application\").Warn(e.Exception, \"Unobserved Task Exception\"); }; Notice that TaskScheduler.UnobservedTaskException cannot be used with partial-trust .NET Framework applications, where registration will throw MethodAccessException . Notice there is also AppDomain.CurrentDomain.FirstChanceException but one should avoid doing logging in this event-handler, since it will result in recursive-loop when NLog Target experience any Exception. 7. Environment specific target options Most NLog-Target options supports NLog Layout , which means the NLog-Target options can be assigned from environment-variables , configuration-files or global diagnotic context (GDC) . Thus one only have to maintain a single NLog-configuration, and all environment-specific options can be extracted to a dedicated location. See also Environment specific NLog Logging Configuration If wanting different output levels/targets depending on environment, then one can also use NLog Layout in the Logger-rules , thus having different minLevel=\"${configsetting:DefaultLevel:whenEmpty=Warn}\" depending on environment (Where LogLevel Off can disable output). If having multiple targets, and the targets are using the same NLog Layout for output, then one can use NLog config variables to define the NLog Layout. Instead of maintaining the NLog Layout for each target, then assign target layout to the config-variable. NLog v5 adds support for using more advanced Layouts like the JsonLayout , XmlLayout , CsvLayout or other .","title":"Tutorial"},{"location":"Tutorial/#configure-nlog-targets-for-output","text":"NLog will only produce output if having configured one (or more) NLog targets. NLog can be configured using XML by adding a NLog.config file to your application project (File Properties: Copy If newer). NLog will automatically load the NLog.config by searching multiple file locations . This is a simple example of the content for NLog.config : Alternative one can configure programmatically by doing this in code: var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget(\"logfile\") { FileName = \"logfile.txt\" }; var logconsole = new NLog.Targets.ConsoleTarget(\"logconsole\"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; NLog 5.0 introduces a Fluent-Configuration-API so you can do this instead: NLog.LogManager.Setup().LoadConfiguration(builder => { builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole(); builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName: \"logfile.txt\"); }); The rules redirects logger output to the wanted output targets. The rules also provides filtering options to output only relevant logevents. Usually based on logger-name and loglevel (Ex. name=\"*\" minlevel=\"Trace\" means everything). See also Configuration File or Configure from code See also Available NLog Targets for output.","title":"Configure NLog Targets for output"},{"location":"Tutorial/#writing-log-messages","text":"public static class Program { private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); public static void Main() { try { Logger.Info(\"Hello world\"); System.Console.ReadKey(); } catch (Exception ex) { Logger.Error(ex, \"Goodbye cruel world\"); } } } The Logger can write messages with different LogLevels, which is used by the logging-rules (See minLevel in configuration example above) so only relevant messages are redirected to the wanted targets. The LogLevel identifies how important/detailed the message is. NLog can route log messages based primarily on their logger name and log level. The log levels ordered by severity: LogLevel Severity Typical Use Trace Most verbose level. Used for development and seldom enabled in production. Ex. Request-payload, Response-payload, Begin-method-X or End-method-X Debug Debugging the application behavior from internal events of interest. Ex. Executed query, User authenticated, Session expired Info Information about application lifetime events like starting/stopping and configuration changes. Warn Warnings about validation issues or temporary failures that can be recovered. Error Errors where functionality has failed or Exception have been caught. Fatal Most critical level. Application is about to abort. The logger is not tied to a specific target. The messages written to one logger can reach multiple targets based on the Configuration-file#rules . Maintaining this separation lets you keep logging statements in your code and easily change how and where the logs are written, just by updating the configuration in one place. See also Filtering log messages . Instead of using NLog Logger directly, then NLog also supports logging abstractions like Microsoft Extension Logging or LibLog .","title":"Writing log messages"},{"location":"Tutorial/#layouts-and-layoutrenderers","text":"NLog allows you to customize how log messages are written to a NLog target. This shows the default SimpleLayout used by most NLog targets: This can be configured to include extra context information (Ex ${threadid} ): See full list here: Layout Renderers One can also use a more complex Layout instead of SimpleLayout : * CsvLayout * JsonLayout * XmlLayout See full list here: Layouts","title":"Layouts and LayoutRenderers"},{"location":"Tutorial/#target-wrappers","text":"NLog supports special kinds of targets which do not do any logging by themselves, but extends the behavior of destination target. Those targets are called wrappers. The most commonly used ones are: * AsyncWrapper - Improves Performance by providing asynchronous, buffered execution of target writes. * BufferingWrapper - Simple batching of log messages. Maybe only send batch when certain log event occurs (Ex. Exception). * FallbackGroup - Provides fallback-on-error. * RetryingWrapper - Provides retry-on-error. See full list here: Target Wrappers There is a shortcut for enabling the AsyncWrapper for all targets, by adding async=\"true\" : This will make all writes to the file be asynchronous, which will improve responsiveness of the calling thread.","title":"Target Wrappers"},{"location":"Tutorial/#best-practices-for-using-nlog","text":"","title":"Best practices for using NLog"},{"location":"Tutorial/#1-logger-should-be-a-static-variable-in-each-class","text":"When using LogManager.GetCurrentClassLogger : Creating a new Logger has a small overhead, as it has to acquire locks and allocate objects. Therefore it is recommended to create the logger like this: namespace MyNamespace { public class MyClass { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); } }","title":"1. Logger should be a static variable in each class"},{"location":"Tutorial/#2-logger-should-handle-string-formatting","text":"Avoid performing string allocation or string concatenation upfront, but instead let the Logger do the formatting. This will allow NLog to defer the formatting and improve performance . Either using Structured logging that captures parameters as named properties: logger.Info(\"Hello {World}\", \"Earth\"); Or using string-format syntax: logger.Info(\"Hello {0}\", \"Earth\");","title":"2. Logger should handle string formatting"},{"location":"Tutorial/#3-logger-should-be-given-the-exception","text":"Avoid giving the Exception as formatting parameter, but instead provide it explicitly as first parameter. This will help the NLog targets to provide better logging. try { } catch (Exception ex) { logger.Error(ex, \"Something bad happened\"); }","title":"3. Logger should be given the Exception"},{"location":"Tutorial/#4-validate-xml-configuration-from-nlogconfig","text":"NLog swallows by default all exceptions, so problems with logging will not cause the application to break. But for many application the logging is very critical, so if the initial NLog configuration fails, then it is fatal. Adding throwConfigExceptions=\"true\" will make NLog complain when something is wrong with the configuration: There is also a setting called throwExceptions=\"true\" , which should never be used in production as it can cause havoc for your application. It is intended for unit testing and local troubleshooting. See also Troubleshooting Configuration It is also a good idea to check output from NLog InternalLogger , as it can give alerts when detecting problems with the NLog configuration.","title":"4. Validate XML configuration from NLog.config"},{"location":"Tutorial/#5-remember-to-flush","text":"NLog will by default attempt to flush automatically at application shutdown. Microsoft Windows give .NET applications a limited amount of time to perform shutdown (usually 2 sec) before being terminated. If having a NLog configuration with NLog Targets that requires network-traffic (Http, Mail, Tcp), then it is a really good idea to perform a manual Flush/Shutdown independent on running on Linux/Windows. NLog.LogManager.Shutdown(); // Flush and close down internal threads and timers NET Application running on Mono/Linux are required to stop threads/timers before entering application shutdown phase. Failing to do this will cause unhandled exceptions and segmentation faults, and other unpredictable behavior. NET 10.0 (and newer) no longer signals AppDomain.ProcessExit or AssemblyLoadContext.Unloading independent on running on Windows/Linux. So just like using LogManager.AutoShutdown = false .","title":"5. Remember to Flush"},{"location":"Tutorial/#6-unhandled-exeptions","text":"When non-background threads dies because of unhandled Exception, then the entire application will die. For better diagnostics, then one can listen for unhandled exceptions and forward to NLog at application startup: AppDomain.CurrentAppDomain.UnhandledException += (s, e) => { NLog.LogManager.GetLogger(\"Application\").Error(e.ExceptionObject as Exception, \"Unhandled Application Exception\"); NLog.LogManager.Flush(); // Ensure logs are written before application dies }; When async Tasks dies because of unobserved Exception and finalized, then the application will continue without making any noise. For better diagnostics, then one can listen for unobserved exceptions and forward to NLog at application startup: System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (s, e) => { if (e.Exception is System.OperationCanceledException) NLog.LogManager.GetLogger(\"Application\").Info(e.Exception, \"Unobserved Task Cancellation\"); else NLog.LogManager.GetLogger(\"Application\").Warn(e.Exception, \"Unobserved Task Exception\"); }; Notice that TaskScheduler.UnobservedTaskException cannot be used with partial-trust .NET Framework applications, where registration will throw MethodAccessException . Notice there is also AppDomain.CurrentDomain.FirstChanceException but one should avoid doing logging in this event-handler, since it will result in recursive-loop when NLog Target experience any Exception.","title":"6. Unhandled exeptions"},{"location":"Tutorial/#7-environment-specific-target-options","text":"Most NLog-Target options supports NLog Layout , which means the NLog-Target options can be assigned from environment-variables , configuration-files or global diagnotic context (GDC) . Thus one only have to maintain a single NLog-configuration, and all environment-specific options can be extracted to a dedicated location. See also Environment specific NLog Logging Configuration If wanting different output levels/targets depending on environment, then one can also use NLog Layout in the Logger-rules , thus having different minLevel=\"${configsetting:DefaultLevel:whenEmpty=Warn}\" depending on environment (Where LogLevel Off can disable output). If having multiple targets, and the targets are using the same NLog Layout for output, then one can use NLog config variables to define the NLog Layout. Instead of maintaining the NLog Layout for each target, then assign target layout to the config-variable. NLog v5 adds support for using more advanced Layouts like the JsonLayout , XmlLayout , CsvLayout or other .","title":"7. Environment specific target options"},{"location":"Uppercase-Layout-Renderer/","text":"Converts the result of another layout output to upper case. Platforms Supported: All Configuration Syntax ${uppercase:uppercase=Boolean:inner=Layout:culture=Culture} or by using ambient property to modify output of other layout renderer: ${other:uppercase=Boolean} Parameters Transformation Options inner - Wrapped layout. Layout. Default attribute. uppercase - Indicates whether upper case conversion should be applied. Default true with Inner, required when using as ambient. culture - Culture used for rendering. Culture Examples ${uppercase:${level}} ${uppercase:Inner=${level}} ${level:uppercase=true}","title":"Uppercase Layout Renderer"},{"location":"Uppercase-Layout-Renderer/#configuration-syntax","text":"${uppercase:uppercase=Boolean:inner=Layout:culture=Culture} or by using ambient property to modify output of other layout renderer: ${other:uppercase=Boolean}","title":"Configuration Syntax"},{"location":"Uppercase-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Uppercase-Layout-Renderer/#transformation-options","text":"inner - Wrapped layout. Layout. Default attribute. uppercase - Indicates whether upper case conversion should be applied. Default true with Inner, required when using as ambient. culture - Culture used for rendering. Culture","title":"Transformation Options"},{"location":"Uppercase-Layout-Renderer/#examples","text":"${uppercase:${level}} ${uppercase:Inner=${level}} ${level:uppercase=true}","title":"Examples"},{"location":"Url-Encode-Layout-Renderer/","text":"Encodes the result of another layout output for use with URLs. Platforms Supported: All Configuration Syntax ${url-encode:spaceAsPlus=Boolean:inner=Layout} Parameters Transformation Options spaceAsPlus - Indicates whether spaces should be translated to '+' or '%20'. Boolean inner - Wrapped layout. Layout escapeDataRfc3986 - NLog will by default encode as UTF8 and escape special characters according to Rfc2396. To escape data according to standard Rc3986, set this option to 'true' (Available from NLog 4.4) escapeDataNLogLegacy - NLog will by default encode as UTF8 and escape special characters according to Rfc2396. To escape data according to the old non-standard NLog style, set this option to 'true' (Available from NLog 4.4)","title":"Url Encode Layout Renderer"},{"location":"Url-Encode-Layout-Renderer/#configuration-syntax","text":"${url-encode:spaceAsPlus=Boolean:inner=Layout}","title":"Configuration Syntax"},{"location":"Url-Encode-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Url-Encode-Layout-Renderer/#transformation-options","text":"spaceAsPlus - Indicates whether spaces should be translated to '+' or '%20'. Boolean inner - Wrapped layout. Layout escapeDataRfc3986 - NLog will by default encode as UTF8 and escape special characters according to Rfc2396. To escape data according to standard Rc3986, set this option to 'true' (Available from NLog 4.4) escapeDataNLogLegacy - NLog will by default encode as UTF8 and escape special characters according to Rfc2396. To escape data according to the old non-standard NLog style, set this option to 'true' (Available from NLog 4.4)","title":"Transformation Options"},{"location":"Var-Layout-Renderer/","text":"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 \u26a0\ufe0f 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 as optimized 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 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 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 )","title":"Var Layout Renderer"},{"location":"Var-Layout-Renderer/#configuration-syntax","text":"${var:name=String:default=String}","title":"Configuration Syntax"},{"location":"Var-Layout-Renderer/#parameters","text":"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","title":"Parameters"},{"location":"Var-Layout-Renderer/#example","text":" ","title":"Example"},{"location":"Var-Layout-Renderer/#api","text":"// create or edit LogManager.Configuration.Variables[\"user\"] = \"admin\"; LogManager.Configuration.Variables[\"password\"] = \"123\"; // or remove LogManager.Configuration.Variables.Remove(\"password\");","title":"API"},{"location":"Var-Layout-Renderer/#notes","text":"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 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 )","title":"Notes"},{"location":"Visual-Studio-Support/","text":"NLog integrates with Visual Studio\u00ae Intellisense NLog supports Intellisense when editing XML configuration files. Install the NLog.Schema -nuget-package and update the NLog.config -file: Alternative enable \"Automatically download DTDs and schemas\" (Visual Studio Options), then Intellisense works with using direct URL: Notice Intellisense will only work in Visual Studio when using xsi:type=\"...\" : And not: Legacy Integration with Add/Reference dialog NLog Setup registers the appropriate AssemblyFolders entry in registry so that Visual Studio is able to locate the *.dll files and present them in Add Reference dialog. This is supported in all Visual Studio versions. New Item Templates NLog comes with 3 sample configuration files that can be quickly added to you project through Add New Item dialog. They are: * configuration file that defines one File Target (typical) * configuration file that defines one Console Target * empty configuration file Please note that you need to change \u201cCopy To Output Directory\u201d option of properties of NLog.config to \u201cCopy Always\u201d Note that \u201cNew Item\u201d templates are supported on Visual Studio 2005 and higher (including Express Editions). Code Snippets NLog installs a Visual Studio 2005 Code Snippet called \u201cnlogger\u201d that can be used to quickly declare a logger instance. It inserts the following piece of text: private static Logger logger = LogManager.GetCurrentClassLogger();","title":"Visual Studio Support"},{"location":"Visual-Studio-Support/#intellisense","text":"NLog supports Intellisense when editing XML configuration files. Install the NLog.Schema -nuget-package and update the NLog.config -file: Alternative enable \"Automatically download DTDs and schemas\" (Visual Studio Options), then Intellisense works with using direct URL: Notice Intellisense will only work in Visual Studio when using xsi:type=\"...\" : And not: ","title":"Intellisense"},{"location":"Visual-Studio-Support/#legacy","text":"","title":"Legacy"},{"location":"Visual-Studio-Support/#integration-with-addreference-dialog","text":"NLog Setup registers the appropriate AssemblyFolders entry in registry so that Visual Studio is able to locate the *.dll files and present them in Add Reference dialog. This is supported in all Visual Studio versions.","title":"Integration with Add/Reference dialog"},{"location":"Visual-Studio-Support/#new-item-templates","text":"NLog comes with 3 sample configuration files that can be quickly added to you project through Add New Item dialog. They are: * configuration file that defines one File Target (typical) * configuration file that defines one Console Target * empty configuration file Please note that you need to change \u201cCopy To Output Directory\u201d option of properties of NLog.config to \u201cCopy Always\u201d Note that \u201cNew Item\u201d templates are supported on Visual Studio 2005 and higher (including Express Editions).","title":"New Item Templates"},{"location":"Visual-Studio-Support/#code-snippets","text":"NLog installs a Visual Studio 2005 Code Snippet called \u201cnlogger\u201d that can be used to quickly declare a logger instance. It inserts the following piece of text: private static Logger logger = LogManager.GetCurrentClassLogger();","title":"Code Snippets"},{"location":"W3CExtendedLogLayout/","text":"A specialized layout that renders to W3C Extended Log Format (ELF) Platforms Supported: All Introduced with NLog.Web 5.0 Note default fields will be printed, when no fields has been specified. Same behavior for directives. Parameters field name - Required. The name of the W3C Extended Field layout - The layout value of the W3C Extended Field directive name - Required. The name of the W3C Extended Directive Header layout - The layout value of the W3C Extended Directive Header Notes Available W3C log-parsers: https://github.com/jibedoubleve/log-reader https://support.microsoft.com/en-us/topic/log-parser-2-2-and-asp-net-37531636-1cf5-dc52-f12a-6a9252155631 https://techcommunity.microsoft.com/t5/exchange-team-blog/introducing-log-parser-studio/ba-p/601131 https://www.finalanalytics.com/products/httplogbrowser","title":"W3CExtendedLogLayout"},{"location":"W3CExtendedLogLayout/#parameters","text":"field name - Required. The name of the W3C Extended Field layout - The layout value of the W3C Extended Field directive name - Required. The name of the W3C Extended Directive Header layout - The layout value of the W3C Extended Directive Header","title":"Parameters"},{"location":"W3CExtendedLogLayout/#notes","text":"Available W3C log-parsers: https://github.com/jibedoubleve/log-reader https://support.microsoft.com/en-us/topic/log-parser-2-2-and-asp-net-37531636-1cf5-dc52-f12a-6a9252155631 https://techcommunity.microsoft.com/t5/exchange-team-blog/introducing-log-parser-studio/ba-p/601131 https://www.finalanalytics.com/products/httplogbrowser","title":"Notes"},{"location":"Web-resources/","text":"Articles and tutorials about NLog Introduction to NLog by Jaroslaw Kowalski (Original author of NLog) NLog Tutorial for .NET Logging by Stackify.com NLog Tutorial - Guide for logging by Elmah.io ASP.NET Core logging with NLog and PostgreSQL by Damian Hickey ASP.NET Core logging to MySQL using NLog by Damian Hickey ASP.NET Core logging with NLog and Microsoft SQL Server by Damian Hickey ASP.NET Core logging with NLog and Elasticsearch by Damian Hickey How to use NLog for .NET Core and ASP.NET Core Logging by Aleksander Kovac Configure NLog for ASP.NET MVC in 3 Steps by Jamil Hallal Logging setup in 5 minutes with NLog by Werner van Deventer ASP.Net Logging Using NLog by Ricky Rosario ( Link Broken ) Using NLog to Track Events by Andrew Hay ( Link Broken ) Ninject (Part 2): Customizing your infrastructure for logging by Ivan Porto Carrero Tracing and logging in .NET by Hieu Pham ( Link Broken ) Logging with PostSharp and NLog by Artemis West Ltd ( Link Broken ) Using NLog in C# by Orn Kristjansson ( Link Broken ) Logging NLog messages to a non-static method by Matt Valerio ( Link Broken ) NLog by Pete on Software Switching to NLog by Robert A. McCarter Sending the output from Linq to SQL to a Log file by Grant Barrington Logging to SQLite with NLog by Thomas Beck Aspect-Oriented Instrumentation with PostSharp, NLog, and SQLite by Thomas Beck Logging messages to a Syslog server using NLog by Graffen ( Link Broken ) How to NLog (2.1 & 3.1) with VisualStudio 2013 By Noctis on CodeProject How to NLog (4.2) with Visual Studio 2015 By Noctis on CodeProject NLog vs log4net performance comparison by @imanushin ( Russian translation is here ) Typical logging mistakes by @imanushin ( Russian translation is here ). Article is about he most common logging errors (which lead to application performance degradation). Growl with NLog on Windows by Ryan Farley Logging Facades Microsoft Extensions Logging System.Diagnostics.Trace Castle Windsor LibLog ( Marked as deprecated ) Common Logging ( Seems abandoned ) Caliburn.Micro ( Seems abandoned ) NLog Extensions Targets - External Packages Layouts - External Packages LogViewer Tools - External Packages See also: Extending-NLog See also: Who Is Using NLog","title":"Web resources"},{"location":"Web-resources/#articles-and-tutorials-about-nlog","text":"Introduction to NLog by Jaroslaw Kowalski (Original author of NLog) NLog Tutorial for .NET Logging by Stackify.com NLog Tutorial - Guide for logging by Elmah.io ASP.NET Core logging with NLog and PostgreSQL by Damian Hickey ASP.NET Core logging to MySQL using NLog by Damian Hickey ASP.NET Core logging with NLog and Microsoft SQL Server by Damian Hickey ASP.NET Core logging with NLog and Elasticsearch by Damian Hickey How to use NLog for .NET Core and ASP.NET Core Logging by Aleksander Kovac Configure NLog for ASP.NET MVC in 3 Steps by Jamil Hallal Logging setup in 5 minutes with NLog by Werner van Deventer ASP.Net Logging Using NLog by Ricky Rosario ( Link Broken ) Using NLog to Track Events by Andrew Hay ( Link Broken ) Ninject (Part 2): Customizing your infrastructure for logging by Ivan Porto Carrero Tracing and logging in .NET by Hieu Pham ( Link Broken ) Logging with PostSharp and NLog by Artemis West Ltd ( Link Broken ) Using NLog in C# by Orn Kristjansson ( Link Broken ) Logging NLog messages to a non-static method by Matt Valerio ( Link Broken ) NLog by Pete on Software Switching to NLog by Robert A. McCarter Sending the output from Linq to SQL to a Log file by Grant Barrington Logging to SQLite with NLog by Thomas Beck Aspect-Oriented Instrumentation with PostSharp, NLog, and SQLite by Thomas Beck Logging messages to a Syslog server using NLog by Graffen ( Link Broken ) How to NLog (2.1 & 3.1) with VisualStudio 2013 By Noctis on CodeProject How to NLog (4.2) with Visual Studio 2015 By Noctis on CodeProject NLog vs log4net performance comparison by @imanushin ( Russian translation is here ) Typical logging mistakes by @imanushin ( Russian translation is here ). Article is about he most common logging errors (which lead to application performance degradation). Growl with NLog on Windows by Ryan Farley","title":"Articles and tutorials about NLog"},{"location":"Web-resources/#logging-facades","text":"Microsoft Extensions Logging System.Diagnostics.Trace Castle Windsor LibLog ( Marked as deprecated ) Common Logging ( Seems abandoned ) Caliburn.Micro ( Seems abandoned )","title":"Logging Facades"},{"location":"Web-resources/#nlog-extensions","text":"Targets - External Packages Layouts - External Packages LogViewer Tools - External Packages See also: Extending-NLog See also: Who Is Using NLog","title":"NLog Extensions"},{"location":"WebService-target---Workaround-for-url-variables/","text":"\u26a0\ufe0f NLog 5.0 now supports Layout for the Url -parameter, so this work-around is no longer needed. Given config *a target configured as in: https://github.com/NLog/NLog/wiki/Webservice-Target-for-Splunk Workaround Tool driven Create a transformation from nlog.config using the slow-cheetah plugin: https://github.com/microsoft/slow-cheetah/blob/master/doc/transforming_files.md Manual Create a Nlog.Release.config (XML-File) to override the hard coded url The name must be same as the name from your original target! Install Package \"Microsoft.VisualStudio.SlowCheetah\" Update your csproj file: Always true true Nlog.config Content of nlog.Release.config If NEWURL is a variable In program.cs modify nlog.config before configuring Nlog var token = Environment.GetEnvironmentVariable(\"YOURURL\"); if (!string.IsNullOrWhiteSpace(token)) { var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); var nlogFolder = $\"{currentFolder}/nlog.config\"; var configText = File.ReadAllText(nlogFolder); var updatedConfig = configText .Replace(\"NEWURL\", token); File.WriteAllText(nlogFolder, updatedConfig); } var logger = NLogBuilder.ConfigureNLog(\"nlog.config\").GetCurrentClassLogger(); //...","title":"WebService target Workaround for url variables"},{"location":"WebService-target---Workaround-for-url-variables/#given-config","text":"*a target configured as in: https://github.com/NLog/NLog/wiki/Webservice-Target-for-Splunk","title":"Given config"},{"location":"WebService-target---Workaround-for-url-variables/#workaround","text":"","title":"Workaround"},{"location":"WebService-target---Workaround-for-url-variables/#tool-driven","text":"Create a transformation from nlog.config using the slow-cheetah plugin: https://github.com/microsoft/slow-cheetah/blob/master/doc/transforming_files.md","title":"Tool driven"},{"location":"WebService-target---Workaround-for-url-variables/#manual","text":"Create a Nlog.Release.config (XML-File) to override the hard coded url The name must be same as the name from your original target! Install Package \"Microsoft.VisualStudio.SlowCheetah\" Update your csproj file: Always true true Nlog.config ","title":"Manual"},{"location":"WebService-target---Workaround-for-url-variables/#content-of-nlogreleaseconfig","text":" ","title":"Content of nlog.Release.config"},{"location":"WebService-target---Workaround-for-url-variables/#if-newurl-is-a-variable","text":"In program.cs modify nlog.config before configuring Nlog var token = Environment.GetEnvironmentVariable(\"YOURURL\"); if (!string.IsNullOrWhiteSpace(token)) { var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); var nlogFolder = $\"{currentFolder}/nlog.config\"; var configText = File.ReadAllText(nlogFolder); var updatedConfig = configText .Replace(\"NEWURL\", token); File.WriteAllText(nlogFolder, updatedConfig); } var logger = NLogBuilder.ConfigureNLog(\"nlog.config\").GetCurrentClassLogger(); //...","title":"If NEWURL is a variable"},{"location":"WebService-target/","text":"Calls the specified REST web service using HTTP/HTTPS-request for each log message. Platforms Supported: All - Requires nuget-package NLog.Targets.WebService since NLog v6 Checkout NLog.Targets.HttpClient if needing batching of multiple LogEvents in a single HTTP payload. Configuration Syntax
Parameters General Options name - Name of the target. HttpRequest Parameters Options defines a single parameter to be passed in the Http Request: * name - Name of the parameter. * layout - Layout that should be use to calculate the value for the parameter. Layout Required. * parametertype - Type of the parameter. System.Type HttpRequest Headers Options
defines a single Http-header to be included in Http Request: name - Name of the header parameter. layout - Layout that should be use to calculate the value for the parameter. Layout Required. NLog 4.6 allows override of Http-header SoapAction for Protocol Soap11 Web Service Options url - Web service URI. Layout Required. NLog 5.0 changed property-type from string to NLog Layout . Protocol - Protocol to be used when calling web service. Default: Soap11 Possible values: JsonPost - JSON POST - introduced in NLog 4.4 - ContentType \"application/json\" XmlPost - XML POST - introduced in NLog 4.4 - ContentType \"application/xml\" HttpGet - Use HTTP GET Protocol. HttpPost - Use HTTP POST Protocol. ContentType \"application/x-www-form-urlencoded\" Soap11 - Use SOAP 1.1 Protocol. Remember to configure Namespace + MethodName Soap12 - Use SOAP 1.2 Protocol. Remember to configure Namespace + MethodName Namespace - Web service namespace for soap:Envelope (Soap11 + Soap12) MethodName - Web service method name for soap:Envelope (Soap11 + Soap12) encoding - Encoding. Encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Default: Utf-8 includeBOM - Skip or add Byte-order-mark (BOM) for UTF-8. Only used if encoding is set to UTF-8, because a BOM is optional in UTF-8. default: false . For more info on BOM, check Wikipedia . Possible options: null : doesn\u2019t change BOM. true : always include UTF-8 BOM UTF-8 encodings. false : default, always skip BOM on UTF-8 encodings. escapeDataRfc3986 - NLog will by default encode parameters as UTF8 and escape special characters according to Rfc2396. To escape data according to standard Rc3986, set this option to 'true' (Available from NLog 4.4) escapeDataNLogLegacy - NLog will by default encode parameters as UTF8 and escape special characters according to Rfc2396. To escape data according to the old non-standard NLog style, set this option to 'true' (Available from NLog 4.4) NLog v6 no longer supports this encoding, and marked option obsolete. Expect100Continue - Indicates whether to use http 100-Continue behavior, where the client sends headers and expects a 100-Continue response from the server before sending the request body. This feature is enabled by default for .NET Framework and can cause delays especially when http-server does not support the protocol. Setting this to false can improve performance in such cases. Introduced with NLog.Targets.WebService ver. 6.1.1 PreAuthenticate - Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in Headers parameters) ProxyType - Configuration of HttpWebRequest.Proxy. Default: DefaultWebProxy (Introduced with NLog 4.5) Possible values: DefaultWebProxy - Default proxy configuration from WebRequest.DefaultWebProxy (defaultProxy in app.config) AutoProxy - WebRequest.GetSystemWebProxy() with default network credentials (Not supported on NetCore) ProxyAddress - User defined proxy address retrieved from the ProxyAddress parameter. NoProxy - Disables use of proxy (fast) ProxyAddress - User defined proxy address, include port separated by a colon (Introduced with NLog 4.5) UserAgent - User defined Http-Header 'User-Agent' for the web-request (Introduced with NLog 4.7.11) Remarks The web service must implement a method that accepts a number of string parameters. Example Example config: Example API controller public class LogMeController : ApiController { /// /// We need a complex type for modelbinding because /// of content-type: \"application/x-www-form-urlencoded\" /// in /// public class ComplexType { public string Param1 { get; set; } public string Param2 { get; set; } } /// /// Post /// public void Post([FromBody] ComplexType complexType) { //do something } } Example with JSON document NLog v4.5 supports sending custom JSON document using a single nameless parameter, instead individual named parameters: ","title":"WebService target"},{"location":"WebService-target/#configuration-syntax","text":"
","title":"Configuration Syntax"},{"location":"WebService-target/#parameters","text":"","title":"Parameters"},{"location":"WebService-target/#general-options","text":"name - Name of the target.","title":"General Options"},{"location":"WebService-target/#httprequest-parameters-options","text":" defines a single parameter to be passed in the Http Request: * name - Name of the parameter. * layout - Layout that should be use to calculate the value for the parameter. Layout Required. * parametertype - Type of the parameter. System.Type","title":"HttpRequest Parameters Options"},{"location":"WebService-target/#httprequest-headers-options","text":"
defines a single Http-header to be included in Http Request: name - Name of the header parameter. layout - Layout that should be use to calculate the value for the parameter. Layout Required. NLog 4.6 allows override of Http-header SoapAction for Protocol Soap11","title":"HttpRequest Headers Options"},{"location":"WebService-target/#web-service-options","text":"url - Web service URI. Layout Required. NLog 5.0 changed property-type from string to NLog Layout . Protocol - Protocol to be used when calling web service. Default: Soap11 Possible values: JsonPost - JSON POST - introduced in NLog 4.4 - ContentType \"application/json\" XmlPost - XML POST - introduced in NLog 4.4 - ContentType \"application/xml\" HttpGet - Use HTTP GET Protocol. HttpPost - Use HTTP POST Protocol. ContentType \"application/x-www-form-urlencoded\" Soap11 - Use SOAP 1.1 Protocol. Remember to configure Namespace + MethodName Soap12 - Use SOAP 1.2 Protocol. Remember to configure Namespace + MethodName Namespace - Web service namespace for soap:Envelope (Soap11 + Soap12) MethodName - Web service method name for soap:Envelope (Soap11 + Soap12) encoding - Encoding. Encoding name like \"utf-8\", \"ascii\" or \"utf-16\". See Encoding class on MSDN . Default: Utf-8 includeBOM - Skip or add Byte-order-mark (BOM) for UTF-8. Only used if encoding is set to UTF-8, because a BOM is optional in UTF-8. default: false . For more info on BOM, check Wikipedia . Possible options: null : doesn\u2019t change BOM. true : always include UTF-8 BOM UTF-8 encodings. false : default, always skip BOM on UTF-8 encodings. escapeDataRfc3986 - NLog will by default encode parameters as UTF8 and escape special characters according to Rfc2396. To escape data according to standard Rc3986, set this option to 'true' (Available from NLog 4.4) escapeDataNLogLegacy - NLog will by default encode parameters as UTF8 and escape special characters according to Rfc2396. To escape data according to the old non-standard NLog style, set this option to 'true' (Available from NLog 4.4) NLog v6 no longer supports this encoding, and marked option obsolete. Expect100Continue - Indicates whether to use http 100-Continue behavior, where the client sends headers and expects a 100-Continue response from the server before sending the request body. This feature is enabled by default for .NET Framework and can cause delays especially when http-server does not support the protocol. Setting this to false can improve performance in such cases. Introduced with NLog.Targets.WebService ver. 6.1.1 PreAuthenticate - Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in Headers parameters) ProxyType - Configuration of HttpWebRequest.Proxy. Default: DefaultWebProxy (Introduced with NLog 4.5) Possible values: DefaultWebProxy - Default proxy configuration from WebRequest.DefaultWebProxy (defaultProxy in app.config) AutoProxy - WebRequest.GetSystemWebProxy() with default network credentials (Not supported on NetCore) ProxyAddress - User defined proxy address retrieved from the ProxyAddress parameter. NoProxy - Disables use of proxy (fast) ProxyAddress - User defined proxy address, include port separated by a colon (Introduced with NLog 4.5) UserAgent - User defined Http-Header 'User-Agent' for the web-request (Introduced with NLog 4.7.11)","title":"Web Service Options"},{"location":"WebService-target/#remarks","text":"The web service must implement a method that accepts a number of string parameters.","title":"Remarks"},{"location":"WebService-target/#example","text":"","title":"Example"},{"location":"WebService-target/#example-config","text":" ","title":"Example config:"},{"location":"WebService-target/#example-api-controller","text":"public class LogMeController : ApiController { /// /// We need a complex type for modelbinding because /// of content-type: \"application/x-www-form-urlencoded\" /// in /// public class ComplexType { public string Param1 { get; set; } public string Param2 { get; set; } } /// /// Post /// public void Post([FromBody] ComplexType complexType) { //do something } }","title":"Example API controller"},{"location":"WebService-target/#example-with-json-document","text":"NLog v4.5 supports sending custom JSON document using a single nameless parameter, instead individual named parameters: ","title":"Example with JSON document"},{"location":"Webservice-Target-for-Splunk/","text":"Example config for Splunk: You have to authorize against splunk see header attribute Your content must be wrapped in
Alternative TCP/UDP config for Splunk Setup Splunk Input: - From the Splunk Settings , select Data Inputs - Click Add new for TCP (or UDP) - Configure the TCP (or UDP) port to use - On the page Input Settings you can (optionally) specify various things about the data you are going to be sending. There are two particularly useful settings here, the sourcetype and index - Click Review and then Submit Setup NLog Network Target: :\" newLine=\"true\" layout=\"${level}|${logger}|${message}|{exception:format=tostring}\"> Splunk supports SYSLOG format for TCP/UDP, so maybe try out Syslog Target Notice that UDP-protocol has restrictions for log-message size, so they can become discarded.","title":"Webservice Target for Splunk"},{"location":"Webservice-Target-for-Splunk/#example-config-for-splunk","text":"You have to authorize against splunk see header attribute Your content must be wrapped in
","title":"Example config for Splunk:"},{"location":"Webservice-Target-for-Splunk/#alternative-tcpudp-config-for-splunk","text":"Setup Splunk Input: - From the Splunk Settings , select Data Inputs - Click Add new for TCP (or UDP) - Configure the TCP (or UDP) port to use - On the page Input Settings you can (optionally) specify various things about the data you are going to be sending. There are two particularly useful settings here, the sourcetype and index - Click Review and then Submit Setup NLog Network Target: :\" newLine=\"true\" layout=\"${level}|${logger}|${message}|{exception:format=tostring}\"> Splunk supports SYSLOG format for TCP/UDP, so maybe try out Syslog Target Notice that UDP-protocol has restrictions for log-message size, so they can become discarded.","title":"Alternative TCP/UDP config for Splunk"},{"location":"When-Filter/","text":"Filter events in the config. Platforms Supported: All Configuration Syntax Parameters defaultAction - default filter action when no match. Default Ignore . Introduced with NLog 4.6. Before NLog 5.0 the default was Neutral . Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and ignore any following logging-rules . Log - The message should be logged. LogFinal - The message should be logged and ignore any following logging-rules . Neutral - No decision filterdefaultaction - Alternative name for defaultAction to match actual API. Introduced with NLog 5.0 Filtering Options condition - Condition expression. Condition Required. See section Conditions below. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and ignore any following logging-rules . Log - The message should be logged. LogFinal - The message should be logged and ignore any following logging-rules . Neutral - The filter doesn't want to decide whether to log or discard the message. Conditions Conditions are expressions used with the filter. They consist of one or more tests. They are used in the filter to determine if an action will be taken. Predefined Tokens message - LogEvent formatted message logger - Logger name level - LogLevel object exception - Exception object (Introduced with NLog 5.0) ${layout} - All available layout-options (except stacktrace). Condition Language The filter expressions are written in a special mini-language. The language consists of: * relational operators: == , != , < , <= , >= and > Note: Some predefined XML characters may need to be escaped. For example, if you try to use the '<' character, the XML parser will interpret it as an opening tag which results in an error in the configuration file. Instead, use the escaped version of '<' ( < ) in this context. * boolean operators: and , or , not * string literals which are always evaluated as layouts - ${somerenderer} * boolean literals - true and false * numeric literals - e.g. 12345 (integer literal) and 12345.678 (floating point literal) * log level literals - LogLevel.Trace , LogLevel.Debug , ... LogLevel.Fatal * predefined keywords to access the most common log event properties - level , message and logger * braces - to override default priorities and group expressions together * condition functions - to perform string and object tests * Single quotes should be escaped with another single quote. Condition Functions The following condition functions are available: * contains(s1,s2) Determines whether the second string is a substring of the first one. Returns: true when the second string is a substring of the first string, false otherwise. * ends-with(s1,s2) Determines whether the second string is a suffix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise. * equals(o1,o2) Compares two objects for equality. Returns: true when two objects are equal, false otherwise. Notice that 'o1' == 'o2' or 'o1' != 'o2' will be faster and reduces memory allocations. * length(s) Returns the length of a string. Notice that 's' != '' is faster than length('s') > 0 , and reduces memory allocation. * starts-with(s1,s2) Determines whether the second string is a prefix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise. * regex-matches(input, pattern, options) Introduced in NLog 4.5. Indicates whether the regular expression pattern finds a match in the specified input string. options is an optional comma separated list of values from the RegexOptions enumeration. Returns : true when a match is found in the input string, false otherwise. Example : regex-matches('${message}', '^foo$', 'ignorecase,singleline') Quotes Single quotes should be escaped with another single quote. Example: contains('${message}', 'Cannot insert the value NULL into column ''Col1') Extensibility New custom condition functions methods can also be added. NLog 4.7 allows you to register your own condition methods using LogFactory.Setup() . Where a lambda can be registered like this: LogManager.Setup().SetupExtensions(s => s.RegisterConditionMethod(\"hasParameters\", evt => evt.Parameters?.Length > 0) ); And a static method like this: LogManager.Setup().SetupExtensions(s => s.RegisterConditionMethod(\"hasPriority\", typeof(NLogConditionMethods).GetMethod(\"HasPriority\", BindingFlags.Static)) ); Alternative way of adding custom condition methods is creating a public static class with a static function and mark the class and method with the attributes [ConditionMethods] and [ConditionMethod] respectively. You can find a sample implementation of a custom filter here Then you have to tell NLog where to find your assembly (Ex. NLog.ConditionMethodsAssembly.dll ) ... Examples Here are several examples with conditions: 100\" action=\"Ignore\" /> = LogLevel.Debug and contains(message, 'PleaseDontLogThis')) or level==LogLevel.Warn\" action=\"Ignore\" /> ","title":"When Filter"},{"location":"When-Filter/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"When-Filter/#parameters","text":"defaultAction - default filter action when no match. Default Ignore . Introduced with NLog 4.6. Before NLog 5.0 the default was Neutral . Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and ignore any following logging-rules . Log - The message should be logged. LogFinal - The message should be logged and ignore any following logging-rules . Neutral - No decision filterdefaultaction - Alternative name for defaultAction to match actual API. Introduced with NLog 5.0","title":"Parameters"},{"location":"When-Filter/#filtering-options","text":"condition - Condition expression. Condition Required. See section Conditions below. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and ignore any following logging-rules . Log - The message should be logged. LogFinal - The message should be logged and ignore any following logging-rules . Neutral - The filter doesn't want to decide whether to log or discard the message.","title":"Filtering Options"},{"location":"When-Filter/#conditions","text":"Conditions are expressions used with the filter. They consist of one or more tests. They are used in the filter to determine if an action will be taken.","title":"Conditions"},{"location":"When-Filter/#predefined-tokens","text":"message - LogEvent formatted message logger - Logger name level - LogLevel object exception - Exception object (Introduced with NLog 5.0) ${layout} - All available layout-options (except stacktrace).","title":"Predefined Tokens"},{"location":"When-Filter/#condition-language","text":"The filter expressions are written in a special mini-language. The language consists of: * relational operators: == , != , < , <= , >= and > Note: Some predefined XML characters may need to be escaped. For example, if you try to use the '<' character, the XML parser will interpret it as an opening tag which results in an error in the configuration file. Instead, use the escaped version of '<' ( < ) in this context. * boolean operators: and , or , not * string literals which are always evaluated as layouts - ${somerenderer} * boolean literals - true and false * numeric literals - e.g. 12345 (integer literal) and 12345.678 (floating point literal) * log level literals - LogLevel.Trace , LogLevel.Debug , ... LogLevel.Fatal * predefined keywords to access the most common log event properties - level , message and logger * braces - to override default priorities and group expressions together * condition functions - to perform string and object tests * Single quotes should be escaped with another single quote.","title":"Condition Language"},{"location":"When-Filter/#condition-functions","text":"The following condition functions are available: * contains(s1,s2) Determines whether the second string is a substring of the first one. Returns: true when the second string is a substring of the first string, false otherwise. * ends-with(s1,s2) Determines whether the second string is a suffix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise. * equals(o1,o2) Compares two objects for equality. Returns: true when two objects are equal, false otherwise. Notice that 'o1' == 'o2' or 'o1' != 'o2' will be faster and reduces memory allocations. * length(s) Returns the length of a string. Notice that 's' != '' is faster than length('s') > 0 , and reduces memory allocation. * starts-with(s1,s2) Determines whether the second string is a prefix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise. * regex-matches(input, pattern, options) Introduced in NLog 4.5. Indicates whether the regular expression pattern finds a match in the specified input string. options is an optional comma separated list of values from the RegexOptions enumeration. Returns : true when a match is found in the input string, false otherwise. Example : regex-matches('${message}', '^foo$', 'ignorecase,singleline')","title":"Condition Functions"},{"location":"When-Filter/#quotes","text":"Single quotes should be escaped with another single quote. Example: contains('${message}', 'Cannot insert the value NULL into column ''Col1')","title":"Quotes"},{"location":"When-Filter/#extensibility","text":"New custom condition functions methods can also be added. NLog 4.7 allows you to register your own condition methods using LogFactory.Setup() . Where a lambda can be registered like this: LogManager.Setup().SetupExtensions(s => s.RegisterConditionMethod(\"hasParameters\", evt => evt.Parameters?.Length > 0) ); And a static method like this: LogManager.Setup().SetupExtensions(s => s.RegisterConditionMethod(\"hasPriority\", typeof(NLogConditionMethods).GetMethod(\"HasPriority\", BindingFlags.Static)) ); Alternative way of adding custom condition methods is creating a public static class with a static function and mark the class and method with the attributes [ConditionMethods] and [ConditionMethod] respectively. You can find a sample implementation of a custom filter here Then you have to tell NLog where to find your assembly (Ex. NLog.ConditionMethodsAssembly.dll ) ... ","title":"Extensibility"},{"location":"When-Filter/#examples","text":"Here are several examples with conditions: 100\" action=\"Ignore\" /> = LogLevel.Debug and contains(message, 'PleaseDontLogThis')) or level==LogLevel.Warn\" action=\"Ignore\" /> ","title":"Examples"},{"location":"When-Layout-Renderer/","text":"Only outputs the inner layout when the specified condition has been met. See Conditions . Platforms Supported: All Configuration Syntax ${when:when=Condition:inner=Layout:else=Layout} or by using ambient property to modify output of other layout renderer: ${other:when=Condition} Parameters Transformation Options when - Condition that must be met for the inner layout to be printed. Condition Required. inner - Wrapped layout. Layout else - Layout if the condition is not true (introduced in NLog 4.3.5) Examples print the message when the logger name is equal to \"logger\": ``` ${message:when=logger=='logger'} convert a layout string result to a bit (1 or 0) that can be inserted into a SQL bit field.: ${when:when='${aspnet-request:serverVariable=HTTPS}' == 'on':inner=1:else=0} Write \"Good\" if the loglevel is trace/debug/info and otherwise \"Bad\": ${when:when=level<=LogLevel.Info:inner=Good:else=Bad} Write suffix to property-value when available: ${when:when='${event-properties:item=PropName}'=='':else= ${event-properties:item=PropName} Secs} Only write the message if it does not start with `Published` using a [condition function](https://github.com/NLog/NLog/wiki/When-Filter#condition-functions): ${when:when=not starts-with(message, 'Published'):inner=${message}} ``` Escaping Since NLog 4.2 When using : and } in a internal layout those characters need to be escaped (there is no need to escape \\ ). : because it's an option-separator. } because it's the end of the layout Working examples: ${when:when=1 == 1:Inner=Test\\: Hello} ${when:when=1 == 1:Inner=Test\\\\Hello} ${when:when=1 == 1:Inner=Test\\Hello} ${when:when=1 == 1:Inner=Test{Hello\\}} Before NLog 4.2 The colon (:) character should be wrapped within {literal:text=\\:} instead of placed directly within the inner layout. Working Example Configuration layout=\"${when:when=1 == 1:inner=Test${literal:text=\\:} Hello${literal:text=\\:} World}\" Output Test: Hello: World Non-working Example Configuration layout=\"${when:when=1 == 1:inner=Test: Hello: World}\" Output World When the colon character is not wrapped only the last literal instance, in this case the word 'World', appears. :star: Workaround identified by: @reedyrm","title":"When Layout Renderer"},{"location":"When-Layout-Renderer/#configuration-syntax","text":"${when:when=Condition:inner=Layout:else=Layout} or by using ambient property to modify output of other layout renderer: ${other:when=Condition}","title":"Configuration Syntax"},{"location":"When-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"When-Layout-Renderer/#transformation-options","text":"when - Condition that must be met for the inner layout to be printed. Condition Required. inner - Wrapped layout. Layout else - Layout if the condition is not true (introduced in NLog 4.3.5)","title":"Transformation Options"},{"location":"When-Layout-Renderer/#examples","text":"print the message when the logger name is equal to \"logger\": ``` ${message:when=logger=='logger'} convert a layout string result to a bit (1 or 0) that can be inserted into a SQL bit field.: ${when:when='${aspnet-request:serverVariable=HTTPS}' == 'on':inner=1:else=0} Write \"Good\" if the loglevel is trace/debug/info and otherwise \"Bad\": ${when:when=level<=LogLevel.Info:inner=Good:else=Bad} Write suffix to property-value when available: ${when:when='${event-properties:item=PropName}'=='':else= ${event-properties:item=PropName} Secs} Only write the message if it does not start with `Published` using a [condition function](https://github.com/NLog/NLog/wiki/When-Filter#condition-functions): ${when:when=not starts-with(message, 'Published'):inner=${message}} ```","title":"Examples"},{"location":"When-Layout-Renderer/#escaping","text":"","title":"Escaping"},{"location":"When-Layout-Renderer/#since-nlog-42","text":"When using : and } in a internal layout those characters need to be escaped (there is no need to escape \\ ). : because it's an option-separator. } because it's the end of the layout Working examples: ${when:when=1 == 1:Inner=Test\\: Hello} ${when:when=1 == 1:Inner=Test\\\\Hello} ${when:when=1 == 1:Inner=Test\\Hello} ${when:when=1 == 1:Inner=Test{Hello\\}}","title":"Since NLog 4.2"},{"location":"When-Layout-Renderer/#before-nlog-42","text":"The colon (:) character should be wrapped within {literal:text=\\:} instead of placed directly within the inner layout. Working Example Configuration layout=\"${when:when=1 == 1:inner=Test${literal:text=\\:} Hello${literal:text=\\:} World}\" Output Test: Hello: World Non-working Example Configuration layout=\"${when:when=1 == 1:inner=Test: Hello: World}\" Output World When the colon character is not wrapped only the last literal instance, in this case the word 'World', appears. :star: Workaround identified by: @reedyrm","title":"Before NLog 4.2"},{"location":"WhenContains-filter/","text":"Matches when the calculated layout contains the specified substring. This filter is deprecated in favour of \\ which is based on conditions. Platforms Supported: All Configuration Syntax Parameters Filtering Options layout - Layout to be used to filter log messages. Layout Required. substring - Substring to be matched. Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"WhenContains filter"},{"location":"WhenContains-filter/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"WhenContains-filter/#parameters","text":"","title":"Parameters"},{"location":"WhenContains-filter/#filtering-options","text":"layout - Layout to be used to filter log messages. Layout Required. substring - Substring to be matched. Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"Filtering Options"},{"location":"WhenEmpty-Layout-Renderer/","text":"Outputs alternative layout when the inner layout produces empty result. Platforms Supported: All Configuration Syntax ${whenEmpty:whenEmpty=Layout:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:whenEmpty=Layout} Parameters Transformation Options whenEmpty - Layout to be rendered when original layout produced empty result. Layout Required. inner - Wrapped layout. Layout","title":"WhenEmpty Layout Renderer"},{"location":"WhenEmpty-Layout-Renderer/#configuration-syntax","text":"${whenEmpty:whenEmpty=Layout:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:whenEmpty=Layout}","title":"Configuration Syntax"},{"location":"WhenEmpty-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"WhenEmpty-Layout-Renderer/#transformation-options","text":"whenEmpty - Layout to be rendered when original layout produced empty result. Layout Required. inner - Wrapped layout. Layout","title":"Transformation Options"},{"location":"WhenEqual-filter/","text":"Matches when the calculated layout is equal to the specified substring. This filter is deprecated in favour of \\ which is based on contitions. Platforms Supported: All Configuration Syntax Parameters Filtering Options layout - Layout to be used to filter log messages. Layout Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. compareTo - String to compare the layout to. Required. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"WhenEqual filter"},{"location":"WhenEqual-filter/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"WhenEqual-filter/#parameters","text":"","title":"Parameters"},{"location":"WhenEqual-filter/#filtering-options","text":"layout - Layout to be used to filter log messages. Layout Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. compareTo - String to compare the layout to. Required. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"Filtering Options"},{"location":"WhenNotContains-filter/","text":"Matches when the calculated layout does NOT contain the specified substring. This filter is deprecated in favour of \\ which is based on contitions. Platforms Supported: All Configuration Syntax Parameters Filtering Options layout - Layout to be used to filter log messages. Layout Required. substring - Substring to be matched. Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"WhenNotContains filter"},{"location":"WhenNotContains-filter/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"WhenNotContains-filter/#parameters","text":"","title":"Parameters"},{"location":"WhenNotContains-filter/#filtering-options","text":"layout - Layout to be used to filter log messages. Layout Required. substring - Substring to be matched. Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"Filtering Options"},{"location":"WhenNotEqual-filter/","text":"Matches when the calculated layout is NOT equal to the specified substring. This filter is deprecated in favour of \\ which is based on contitions. Platforms Supported: All Configuration Syntax Parameters Filtering Options layout - Layout to be used to filter log messages. Layout Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. compareTo - String to compare the layout to. Required. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"WhenNotEqual filter"},{"location":"WhenNotEqual-filter/#configuration-syntax","text":" ","title":"Configuration Syntax"},{"location":"WhenNotEqual-filter/#parameters","text":"","title":"Parameters"},{"location":"WhenNotEqual-filter/#filtering-options","text":"layout - Layout to be used to filter log messages. Layout Required. action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. compareTo - String to compare the layout to. Required. ignoreCase - Indicates whether to ignore case when comparing strings. Boolean Default: False","title":"Filtering Options"},{"location":"WhenRepeated-Filter/","text":"Matches when the calculated layout has already been logged. Useful if having an aggressive logger, and wants to throttle the output. Introduced with NLog ver. 4.5 Configuration Syntax Can also be combined with FilteringWrapper-target . Parameters Filtering Options layout - Layout to be used to filter log messages. Layout Required. timeoutSeconds - How long to ignore identical messages before logging again (Default 10 secs) action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. includeFirst - Should action also be applied to the initial logevent? When enabled then it will only perform the first logging if the messages continues after the initial timeout. (Default: false) Logging Options FilterCountPropertyName - Tell how many identical log messages has been ignored. By adding LogEvent-Property with this name to the next LogEvent after timeout expires. FilterCountMessageAppendFormat - Tell how many identical log messages has been ignored. By appending to LogEVent-Message to the next LogEvent after timeout expires (Ex. \" (Hits: {0}\") Advanced Parameters MaxLength - Max number of characters to include when checking for identical messages (Default 1000 characters) MaxFilterCacheSize - Max number of unique log messages to keep in cache, before starting to prune (Default 50000) DefaultFilterCacheSize - Initial start size of the cache for keep track of unique log messages (Default 1000) OptimizeBufferDefaultLength - Initial allocated size of the reusable buffers (Default 1000)","title":"WhenRepeated Filter"},{"location":"WhenRepeated-Filter/#configuration-syntax","text":" Can also be combined with FilteringWrapper-target .","title":"Configuration Syntax"},{"location":"WhenRepeated-Filter/#parameters","text":"","title":"Parameters"},{"location":"WhenRepeated-Filter/#filtering-options","text":"layout - Layout to be used to filter log messages. Layout Required. timeoutSeconds - How long to ignore identical messages before logging again (Default 10 secs) action - Action to be taken when filter matches. Required. Possible values: Ignore - The message should not be logged. IgnoreFinal - The message should not be logged and processing should be finished. Log - The message should be logged. LogFinal - The message should be logged and processing should be finished. Neutral - The filter doesn't want to decide whether to log or discard the message. includeFirst - Should action also be applied to the initial logevent? When enabled then it will only perform the first logging if the messages continues after the initial timeout. (Default: false)","title":"Filtering Options"},{"location":"WhenRepeated-Filter/#logging-options","text":"FilterCountPropertyName - Tell how many identical log messages has been ignored. By adding LogEvent-Property with this name to the next LogEvent after timeout expires. FilterCountMessageAppendFormat - Tell how many identical log messages has been ignored. By appending to LogEVent-Message to the next LogEvent after timeout expires (Ex. \" (Hits: {0}\")","title":"Logging Options"},{"location":"WhenRepeated-Filter/#advanced-parameters","text":"MaxLength - Max number of characters to include when checking for identical messages (Default 1000 characters) MaxFilterCacheSize - Max number of unique log messages to keep in cache, before starting to prune (Default 50000) DefaultFilterCacheSize - Initial start size of the cache for keep track of unique log messages (Default 1000) OptimizeBufferDefaultLength - Initial allocated size of the reusable buffers (Default 1000)","title":"Advanced Parameters"},{"location":"Who-Is-Using-NLog/","text":"NLog is being used in a number of software projects, both commercial and open source. If you are using NLog in your product, feel free to expand this page by adding short information about your project and/or company (make sure you have permission to use your company name and/or logo). Open source projects The following open source software projects are using or supporting NLog: * Logging - https://github.com/akovac35/Logging * SimplePM (programming contests management system) - https://github.com/SirkadirovTeam/SimplePM_Server * Castle Project/Windsor Container - https://github.com/castleproject/Core/blob/master/docs/logging.md * Ninject - http://ninject.org/ * Common Infrastructure Libraries for .NET - http://netcommon.sourceforge.net/ * EasyLOB - http://www.easylob.com * TeamCity Configuration Monitor - http://teamcityconfmonitor.codeplex.com/ * MassTransit - http://masstransit-project.com/ * Topshelf - http://topshelf-project.com/ * ServiceStack - https://docs.servicestack.net/logging * ReflectInsight Extensions - https://insightextensions.codeplex.com/ * Fop2DD - https://github.com/KeenSystemsNL/Fop2DD * Ember Media Manager - http://embermediamanager.org/ * ArchiSteamFarm - https://github.com/JustArchiNET/ArchiSteamFarm * Sonarr - https://github.com/Sonarr/Sonarr * Radarr - https://github.com/Radarr/Radarr * Jackett - https://github.com/Jackett/Jackett * SCM Backup - https://scm-backup.org/ Commercial software Gibraltar - https://nlog-project.org/2009/11/01/gibraltar-adapter-for-nlog-released.html TradeBullet - http://www.tradebullet.com LiteStock - http://www.lightweightlabs.com ReflectInsight by ReflectSoftware - http://www.reflectsoftware.com/ Nemo Documents - http://www.nemo-docs.com Misk.com - https://www.misk.com/ VisioForge - http://www.visioforge.com elmah.io - https://elmah.io See also: Articles and tutorials about NLog","title":"Who Is Using NLog"},{"location":"Who-Is-Using-NLog/#open-source-projects","text":"The following open source software projects are using or supporting NLog: * Logging - https://github.com/akovac35/Logging * SimplePM (programming contests management system) - https://github.com/SirkadirovTeam/SimplePM_Server * Castle Project/Windsor Container - https://github.com/castleproject/Core/blob/master/docs/logging.md * Ninject - http://ninject.org/ * Common Infrastructure Libraries for .NET - http://netcommon.sourceforge.net/ * EasyLOB - http://www.easylob.com * TeamCity Configuration Monitor - http://teamcityconfmonitor.codeplex.com/ * MassTransit - http://masstransit-project.com/ * Topshelf - http://topshelf-project.com/ * ServiceStack - https://docs.servicestack.net/logging * ReflectInsight Extensions - https://insightextensions.codeplex.com/ * Fop2DD - https://github.com/KeenSystemsNL/Fop2DD * Ember Media Manager - http://embermediamanager.org/ * ArchiSteamFarm - https://github.com/JustArchiNET/ArchiSteamFarm * Sonarr - https://github.com/Sonarr/Sonarr * Radarr - https://github.com/Radarr/Radarr * Jackett - https://github.com/Jackett/Jackett * SCM Backup - https://scm-backup.org/","title":"Open source projects"},{"location":"Who-Is-Using-NLog/#commercial-software","text":"Gibraltar - https://nlog-project.org/2009/11/01/gibraltar-adapter-for-nlog-released.html TradeBullet - http://www.tradebullet.com LiteStock - http://www.lightweightlabs.com ReflectInsight by ReflectSoftware - http://www.reflectsoftware.com/ Nemo Documents - http://www.nemo-docs.com Misk.com - https://www.misk.com/ VisioForge - http://www.visioforge.com elmah.io - https://elmah.io See also: Articles and tutorials about NLog","title":"Commercial software"},{"location":"Windows-Identity-Layout-Renderer/","text":"Render Windows identity information (username) from the current thread-context. Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsIdentity since NLog 5.0 Configuration Syntax ${windows-identity:userName=Boolean:domain=Boolean} Parameters Rendering Options userName - Indicates whether username should be included. Boolean Default: True domain - Indicates whether domain name should be included. Boolean Default: True Notes ${environment-user} is an alternative that depends on Environment.UserName , which is compatible with both Windows/Linux (and less overhead). ${identity} is an alternative that depends on Thread.CurrentPrincipal . ${aspnet-user-identity} is an alternative that only works on ASP.NET Applications with identity enabled.","title":"Windows Identity Layout Renderer"},{"location":"Windows-Identity-Layout-Renderer/#configuration-syntax","text":"${windows-identity:userName=Boolean:domain=Boolean}","title":"Configuration Syntax"},{"location":"Windows-Identity-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Windows-Identity-Layout-Renderer/#rendering-options","text":"userName - Indicates whether username should be included. Boolean Default: True domain - Indicates whether domain name should be included. Boolean Default: True","title":"Rendering Options"},{"location":"Windows-Identity-Layout-Renderer/#notes","text":"${environment-user} is an alternative that depends on Environment.UserName , which is compatible with both Windows/Linux (and less overhead). ${identity} is an alternative that depends on Thread.CurrentPrincipal . ${aspnet-user-identity} is an alternative that only works on ASP.NET Applications with identity enabled.","title":"Notes"},{"location":"WrapLine-layout-renderer/","text":"Wraps the result of another layout output at specified line length. Platforms Supported: All Introduced in NLog 4.3.4 Configuration Syntax ${wrapline=Integer:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:wrapline=Integer} Parameters Transformation Options inner - Wrapped layout. Layout. Default attribute. wrapline - Indicates wrapping position. Integer greater than 0. Default: 80 Examples ${wrapline:${message}} ${wrapline:Inner=${message}:WrapLine=80} ${message:wrapline=80}","title":"WrapLine layout renderer"},{"location":"WrapLine-layout-renderer/#configuration-syntax","text":"${wrapline=Integer:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:wrapline=Integer}","title":"Configuration Syntax"},{"location":"WrapLine-layout-renderer/#parameters","text":"","title":"Parameters"},{"location":"WrapLine-layout-renderer/#transformation-options","text":"inner - Wrapped layout. Layout. Default attribute. wrapline - Indicates wrapping position. Integer greater than 0. Default: 80","title":"Transformation Options"},{"location":"WrapLine-layout-renderer/#examples","text":"${wrapline:${message}} ${wrapline:Inner=${message}:WrapLine=80} ${message:wrapline=80}","title":"Examples"},{"location":"XML-config-include-Example/","text":"Example with a and in the XML config base file: d:\\nlog-file.config File to be included. Contains one target and needs ${productName} nlog.config The main file. e.g. in the root folder of your application. Contains in this example no targets, only , , ` ","title":"XML config include Example"},{"location":"XML-config-include-Example/#base-file-dnlog-fileconfig","text":"File to be included. Contains one target and needs ${productName} ","title":"base file: d:\\nlog-file.config"},{"location":"XML-config-include-Example/#nlogconfig","text":"The main file. e.g. in the root folder of your application. Contains in this example no targets, only , , ` ","title":"nlog.config"},{"location":"Xml-Encode-Layout-Renderer/","text":"Converts the result of another layout output to be XML-compliant. Platforms Supported: All Configuration Syntax ${xml-encode:xmlEncode=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:xmlEncode=Boolean} Parameters Transformation Options xmlEncode - Indicates whether to apply XML encoding. Boolean Default: True inner - Wrapped layout. Layout","title":"Xml Encode Layout Renderer"},{"location":"Xml-Encode-Layout-Renderer/#configuration-syntax","text":"${xml-encode:xmlEncode=Boolean:inner=Layout} or by using ambient property to modify output of other layout renderer: ${other:xmlEncode=Boolean}","title":"Configuration Syntax"},{"location":"Xml-Encode-Layout-Renderer/#parameters","text":"","title":"Parameters"},{"location":"Xml-Encode-Layout-Renderer/#transformation-options","text":"xmlEncode - Indicates whether to apply XML encoding. Boolean Default: True inner - Wrapped layout. Layout","title":"Transformation Options"},{"location":"XmlLayout/","text":"A specialized layout that renders to XML. Platforms Supported: All Introduced in NLog 4.6 This would write: hello, world Parameters Root ElementName - Name of the top level XML element Default: logevent ElementValue - Value inside the top level XML element Layout ElementEncode - Xml Encode the value for the top level XML element Boolean Default: True > Ensures always valid XML, but gives a performance hit IndentXml - Insert newlines and simplistic indention of output. Boolean . Default: False IncludeEmptyValue - Whether a ElementValue with empty value should be included in the output Boolean Default: False MaxRecursionLimit - How far should the XML serializer follow object references before backing off. Integer. Default 1 ( 0 = No object reflection) IncludeEventProperties - Include all events properties of a logevent? Default: false . Before NLog 5.0 option was named IncludeAllProperties IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc ExcludeProperties - Comma separated string with names which properties to exclude. Only used when IncludeEventProperties is true. Case sensitive. Default empty When a name contains a comma, single quote the value. E.g. 'value,withquote',value2. PropertiesElementName - Element name to use when rendering properties. Support string-format where {0} means property-key-name. Skips closing element tag when having configured PropertiesElementValueAttribute PropertiesElementKeyAttribute - Attribute name to use when rendering property-key. When null (or empty) then key-attribute is not included. Will replace newlines in attribute-value with PropertiesElementValueAttribute - Attribute name to use when rendering property-value. When null (or empty) then value-attribute is not included and value is formatted as XML-element-value. Skips closing element tag when using attribute for value Will replace newlines in attribute-value with PropertiesCollectionItemName - Element name to use for rendering IList -collections items Elements defines childs elements to render: Name - Name of the element. Default 'item' Value - Value inside the element Layout Encode - Xml Encode the value Boolean Default: True Configuration parameters for Root can also be used for each -element. Attributes defines the attributes to render: Name - Name of the attribute. Required. Layout - Layout that will be rendered as the attribute's value. Layout Required. Encode - Xml Encode the attribute value. Boolean Default: True IncludeEmptyValue - - Whether an attribute with empty value should be included in the output Boolean Examples XML with attributes and elements XmlLayout Xml Output My log message My exception message LogEventInfo Properties Default Output XmlLayout Xml Output PropertyValue LogEventInfo Properties with element-name override XmlLayout Xml Output PropertyValue LogEventInfo Properties with element-name as property-name XmlLayout Xml Output PropertyValue LogEventInfo Properties Value as attribute: XmlLayout Xml Output LogEventInfo Properties Dictionary-object Default Output XmlLayout Xml Output DictionaryValue LogEventInfo Properties List-object Default Output XmlLayout Xml Output ListValue1ListValue2 LogEventInfo Properties List-object with element-name override XmlLayout Xml Output ListValue1ListValue2 ","title":"XmlLayout"},{"location":"XmlLayout/#parameters","text":"","title":"Parameters"},{"location":"XmlLayout/#root","text":"ElementName - Name of the top level XML element Default: logevent ElementValue - Value inside the top level XML element Layout ElementEncode - Xml Encode the value for the top level XML element Boolean Default: True > Ensures always valid XML, but gives a performance hit IndentXml - Insert newlines and simplistic indention of output. Boolean . Default: False IncludeEmptyValue - Whether a ElementValue with empty value should be included in the output Boolean Default: False MaxRecursionLimit - How far should the XML serializer follow object references before backing off. Integer. Default 1 ( 0 = No object reflection) IncludeEventProperties - Include all events properties of a logevent? Default: false . Before NLog 5.0 option was named IncludeAllProperties IncludeScopeProperties - Indicates whether to include ScopeProperty-Layout-Renderer dictionary. Default: false . Before NLog 5.0 option was named IncludeMdlc or IncludeMdc ExcludeProperties - Comma separated string with names which properties to exclude. Only used when IncludeEventProperties is true. Case sensitive. Default empty When a name contains a comma, single quote the value. E.g. 'value,withquote',value2. PropertiesElementName - Element name to use when rendering properties. Support string-format where {0} means property-key-name. Skips closing element tag when having configured PropertiesElementValueAttribute PropertiesElementKeyAttribute - Attribute name to use when rendering property-key. When null (or empty) then key-attribute is not included. Will replace newlines in attribute-value with PropertiesElementValueAttribute - Attribute name to use when rendering property-value. When null (or empty) then value-attribute is not included and value is formatted as XML-element-value. Skips closing element tag when using attribute for value Will replace newlines in attribute-value with PropertiesCollectionItemName - Element name to use for rendering IList -collections items","title":"Root"},{"location":"XmlLayout/#elements","text":" defines childs elements to render: Name - Name of the element. Default 'item' Value - Value inside the element Layout Encode - Xml Encode the value Boolean Default: True Configuration parameters for Root can also be used for each -element.","title":"Elements"},{"location":"XmlLayout/#attributes","text":" defines the attributes to render: Name - Name of the attribute. Required. Layout - Layout that will be rendered as the attribute's value. Layout Required. Encode - Xml Encode the attribute value. Boolean Default: True IncludeEmptyValue - - Whether an attribute with empty value should be included in the output Boolean","title":"Attributes"},{"location":"XmlLayout/#examples","text":"","title":"Examples"},{"location":"XmlLayout/#xml-with-attributes-and-elements","text":"XmlLayout Xml Output My log message My exception message ","title":"XML with attributes and elements"},{"location":"XmlLayout/#logeventinfo-properties-default-output","text":"XmlLayout Xml Output PropertyValue ","title":"LogEventInfo Properties Default Output"},{"location":"XmlLayout/#logeventinfo-properties-with-element-name-override","text":"XmlLayout Xml Output PropertyValue ","title":"LogEventInfo Properties with element-name override"},{"location":"XmlLayout/#logeventinfo-properties-with-element-name-as-property-name","text":"XmlLayout Xml Output PropertyValue ","title":"LogEventInfo Properties with element-name as property-name"},{"location":"XmlLayout/#logeventinfo-properties-value-as-attribute","text":"XmlLayout Xml Output ","title":"LogEventInfo Properties Value as attribute:"},{"location":"XmlLayout/#logeventinfo-properties-dictionary-object-default-output","text":"XmlLayout Xml Output DictionaryValue ","title":"LogEventInfo Properties Dictionary-object Default Output"},{"location":"XmlLayout/#logeventinfo-properties-list-object-default-output","text":"XmlLayout Xml Output ListValue1ListValue2 ","title":"LogEventInfo Properties List-object Default Output"},{"location":"XmlLayout/#logeventinfo-properties-list-object-with-element-name-override","text":"XmlLayout Xml Output ListValue1ListValue2 ","title":"LogEventInfo Properties List-object with element-name override"},{"location":"_Sidebar/","text":"Home Getting started NLog Introduction Example - ASP.NET Core Example - .NET Core Console How to use structured logging Troubleshooting Internal Log FAQ Articles about NLog Configuration All targets, layouts and layout renderers Popular: File-target ColoredConsole-target Database-target Mail-target Using NLog with NLog.config Using NLog with appsettings.json Programmatic Configuration Configure from code Sandcastle documentation Advanced Add LogEvent Context details Filtering log messages Optimize Logging Performance NLog properties with Microsoft Extension Logging NLog GetCurrentClassLogger and Microsoft ILogger Using Time Sources Installing targets Visual Studio support Who is using NLog Advanced Examples Extending NLog Write custom extensions How to write a custom target How to write a custom layout renderer Writing custom conditions Properties constraints for custom extensions Register your custom component","title":" Sidebar"},{"location":"_Sidebar/#home","text":"Getting started NLog Introduction Example - ASP.NET Core Example - .NET Core Console How to use structured logging Troubleshooting Internal Log FAQ Articles about NLog","title":"Home"},{"location":"_Sidebar/#configuration","text":"All targets, layouts and layout renderers Popular: File-target ColoredConsole-target Database-target Mail-target Using NLog with NLog.config Using NLog with appsettings.json","title":"Configuration"},{"location":"_Sidebar/#programmatic-configuration","text":"Configure from code Sandcastle documentation","title":"Programmatic Configuration"},{"location":"_Sidebar/#advanced","text":"Add LogEvent Context details Filtering log messages Optimize Logging Performance NLog properties with Microsoft Extension Logging NLog GetCurrentClassLogger and Microsoft ILogger Using Time Sources Installing targets Visual Studio support Who is using NLog Advanced Examples","title":"Advanced"},{"location":"_Sidebar/#extending-nlog","text":"Write custom extensions How to write a custom target How to write a custom layout renderer Writing custom conditions Properties constraints for custom extensions Register your custom component","title":"Extending NLog"},{"location":"filters/","text":"See https://github.com/NLog/NLog/wiki/Filtering-log-messages","title":"Filters"}]} \ No newline at end of file diff --git a/wiki/search/worker.js b/wiki/search/worker.js new file mode 100644 index 000000000..8628dbce9 --- /dev/null +++ b/wiki/search/worker.js @@ -0,0 +1,133 @@ +var base_path = 'function' === typeof importScripts ? '.' : '/search/'; +var allowSearch = false; +var index; +var documents = {}; +var lang = ['en']; +var data; + +function getScript(script, callback) { + console.log('Loading script: ' + script); + $.getScript(base_path + script).done(function () { + callback(); + }).fail(function (jqxhr, settings, exception) { + console.log('Error: ' + exception); + }); +} + +function getScriptsInOrder(scripts, callback) { + if (scripts.length === 0) { + callback(); + return; + } + getScript(scripts[0], function() { + getScriptsInOrder(scripts.slice(1), callback); + }); +} + +function loadScripts(urls, callback) { + if( 'function' === typeof importScripts ) { + importScripts.apply(null, urls); + callback(); + } else { + getScriptsInOrder(urls, callback); + } +} + +function onJSONLoaded () { + data = JSON.parse(this.responseText); + var scriptsToLoad = ['lunr.js']; + if (data.config && data.config.lang && data.config.lang.length) { + lang = data.config.lang; + } + if (lang.length > 1 || lang[0] !== "en") { + scriptsToLoad.push('lunr.stemmer.support.js'); + if (lang.length > 1) { + scriptsToLoad.push('lunr.multi.js'); + } + if (lang.includes("ja") || lang.includes("jp")) { + scriptsToLoad.push('tinyseg.js'); + } + for (var i=0; i < lang.length; i++) { + if (lang[i] != 'en') { + scriptsToLoad.push(['lunr', lang[i], 'js'].join('.')); + } + } + } + loadScripts(scriptsToLoad, onScriptsLoaded); +} + +function onScriptsLoaded () { + console.log('All search scripts loaded, building Lunr index...'); + if (data.config && data.config.separator && data.config.separator.length) { + lunr.tokenizer.separator = new RegExp(data.config.separator); + } + + if (data.index) { + index = lunr.Index.load(data.index); + data.docs.forEach(function (doc) { + documents[doc.location] = doc; + }); + console.log('Lunr pre-built index loaded, search ready'); + } else { + index = lunr(function () { + if (lang.length === 1 && lang[0] !== "en" && lunr[lang[0]]) { + this.use(lunr[lang[0]]); + } else if (lang.length > 1) { + this.use(lunr.multiLanguage.apply(null, lang)); // spread operator not supported in all browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Browser_compatibility + } + this.field('title'); + this.field('text'); + this.ref('location'); + + for (var i=0; i < data.docs.length; i++) { + var doc = data.docs[i]; + this.add(doc); + documents[doc.location] = doc; + } + }); + console.log('Lunr index built, search ready'); + } + allowSearch = true; + postMessage({config: data.config}); + postMessage({allowSearch: allowSearch}); +} + +function init () { + var oReq = new XMLHttpRequest(); + oReq.addEventListener("load", onJSONLoaded); + var index_path = base_path + '/search_index.json'; + if( 'function' === typeof importScripts ){ + index_path = 'search_index.json'; + } + oReq.open("GET", index_path); + oReq.send(); +} + +function search (query) { + if (!allowSearch) { + console.error('Assets for search still loading'); + return; + } + + var resultDocuments = []; + var results = index.search(query); + for (var i=0; i < results.length; i++){ + var result = results[i]; + doc = documents[result.ref]; + doc.summary = doc.text.substring(0, 200); + resultDocuments.push(doc); + } + return resultDocuments; +} + +if( 'function' === typeof importScripts ) { + onmessage = function (e) { + if (e.data.init) { + init(); + } else if (e.data.query) { + postMessage({ results: search(e.data.query) }); + } else { + console.error("Worker - Unrecognized message: " + e); + } + }; +} diff --git a/wiki/sitemap.xml b/wiki/sitemap.xml new file mode 100644 index 000000000..15263e61c --- /dev/null +++ b/wiki/sitemap.xml @@ -0,0 +1,1191 @@ + + + + https://nlog-project.org/wiki/All-Event-Properties-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AppDomain-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AppSetting-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-AppBasePath-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Environment-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-HttpContext-Item-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-MVC-Action-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-MVC-Controller-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Bidirectional-Stream-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Client-Certificate-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-ConnectionId-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-ContentLength-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-ContentType-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Duration-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-EndPoint-Group-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-EndPoint-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-EndPoint-Name-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-HTTP-Transport-Type-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Has-Posted-Body-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-IP-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Inherent-KeepAlive-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-IsWebSocket-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Local-IP-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Local-Port-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Remote-Port-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-ServerVariable-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-StreamId-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-TLS-Handshake-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-TLS-Token-Bindng-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Tracking-Consent-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-Trailers-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-WebSocket-Requested-Protocols-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Request-posted-body-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Response-ContentLength-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Response-ContentType-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Response-Cookie-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Response-HTTPS-Compression-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Response-HasStarted-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Response-Headers-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-Response-Trailers-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-User-Claim-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-User-isAuthenticated-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNet-WebRootPath-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetApplication-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetBufferingWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetEnvironment-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetItem-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-Cookie-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-Form-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-Headers-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-Host-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-Method-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-QueryString-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-Referrer-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-RequestAborted-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-RouteParameters-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-Url-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-UserAgent-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetRequest-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetResponse-StatusCode-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetSession-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetSessionId-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetTrace-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetTraceIdentifier-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetUserAuthType-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspNetUserIdentity-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspRequest-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspResponse-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/AspSession-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AssemblyVersion-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/AsyncWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Atomic-File-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/AutoFlushWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Basedir-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/BufferingWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Cached-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Callsite-file-name-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Callsite-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Callsite-line-number-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Chainsaw-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/ColoredConsole-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Combine-XML-config-with-C%23-config/ + 2026-11-10 + + + https://nlog-project.org/wiki/CompoundLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/Conditions/ + 2026-11-10 + + + https://nlog-project.org/wiki/ConfigSetting-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Configuration-API/ + 2026-11-10 + + + https://nlog-project.org/wiki/Configuration-file/ + 2026-11-10 + + + https://nlog-project.org/wiki/Configure-NLog/ + 2026-11-10 + + + https://nlog-project.org/wiki/Configure-component-logging/ + 2026-11-10 + + + https://nlog-project.org/wiki/Configure-from-code/ + 2026-11-10 + + + https://nlog-project.org/wiki/Console-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Context/ + 2026-11-10 + + + https://nlog-project.org/wiki/Counter-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/CsvLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/CurrentDir-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Custom-extension-of-Logger-interface/ + 2026-11-10 + + + https://nlog-project.org/wiki/DB-null-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Data-types/ + 2026-11-10 + + + https://nlog-project.org/wiki/Database-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Date-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Debug-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/DebugSystem-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Debugger-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Dependency-injection-with-NLog/ + 2026-11-10 + + + https://nlog-project.org/wiki/Directory-separator/ + 2026-11-10 + + + https://nlog-project.org/wiki/DocumentUri-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Elmah-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Environment-User-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Environment-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Environment-specific-NLog-Logging-Configuration/ + 2026-11-10 + + + https://nlog-project.org/wiki/Event-Context-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/EventProperties-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Eventlog-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Examples/ + 2026-11-10 + + + https://nlog-project.org/wiki/Exception-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ExceptionData-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Explicit-NLog-configuration-loading/ + 2026-11-10 + + + https://nlog-project.org/wiki/Extending-NLog/ + 2026-11-10 + + + https://nlog-project.org/wiki/FAQ/ + 2026-11-10 + + + https://nlog-project.org/wiki/FallbackGroup-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/File-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/FileContents-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/FileTarget-Archive-Examples/ + 2026-11-10 + + + https://nlog-project.org/wiki/Filesystem-Normalize-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Filtering-log-messages/ + 2026-11-10 + + + https://nlog-project.org/wiki/FilteringWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Fluent-API/ + 2026-11-10 + + + https://nlog-project.org/wiki/Fluent-Configuration-API/ + 2026-11-10 + + + https://nlog-project.org/wiki/Fluent-Logger-API/ + 2026-11-10 + + + https://nlog-project.org/wiki/FormControl-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/GELF-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/GZip-File-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Gc-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Gdc-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/GelfLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/Getting-started-with-.NET-Core-2---Console-application/ + 2026-11-10 + + + https://nlog-project.org/wiki/Getting-started-with-.NET-Core-Console-application/ + 2026-11-10 + + + https://nlog-project.org/wiki/Getting-started-with-ASP.NET-Core-2/ + 2026-11-10 + + + https://nlog-project.org/wiki/Getting-started-with-ASP.NET-Core-3/ + 2026-11-10 + + + https://nlog-project.org/wiki/Getting-started-with-ASP.NET-Core-5/ + 2026-11-10 + + + https://nlog-project.org/wiki/Getting-started-with-ASP.NET-Core-6/ + 2026-11-10 + + + https://nlog-project.org/wiki/GroupByWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Guid-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/HTTP-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Home/ + 2026-11-10 + + + https://nlog-project.org/wiki/Host-AppName-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Host-Environment-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Host-RootDir-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/HostName-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-Log-Exceptions/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-create-Logger-for-sub-classes/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-use-structured-logging/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-write-a-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-write-a-custom-async-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-write-a-custom-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-write-a-custom-target-for-structured-logging/ + 2026-11-10 + + + https://nlog-project.org/wiki/How-to-write-a-custom-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/IIS-site-name-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Identity-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ImpersonatingWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/InstallContext-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Installing-targets/ + 2026-11-10 + + + https://nlog-project.org/wiki/Internal-Logging/ + 2026-11-10 + + + https://nlog-project.org/wiki/JSON-Encode-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/JsonArrayLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/JsonLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/Layout-Renderers/ + 2026-11-10 + + + https://nlog-project.org/wiki/Layout/ + 2026-11-10 + + + https://nlog-project.org/wiki/LayoutWithHeaderAndFooter/ + 2026-11-10 + + + https://nlog-project.org/wiki/Layouts/ + 2026-11-10 + + + https://nlog-project.org/wiki/Left-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Level-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/LimitingWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Literal-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Local-IP-Address-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Log-levels/ + 2026-11-10 + + + https://nlog-project.org/wiki/Log4JXMLEvent-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Log4JXml-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Log4JXmlEventLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/LogEvent-Context-Information/ + 2026-11-10 + + + https://nlog-project.org/wiki/LogReceiverService-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Logger-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Logging-Rules-FinalMinLevel/ + 2026-11-10 + + + https://nlog-project.org/wiki/Logging-Troubleshooting/ + 2026-11-10 + + + https://nlog-project.org/wiki/Longdate-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Lowercase-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/MDC-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/MDLC-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/MSMQ-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Machinename-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Mail-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Memory-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Message-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/MessageBox-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/MethodCall-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/MicrosoftConsoleJsonLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/MicrosoftConsoleLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/MicrosoftILogger-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/NDC-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/NDLC-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/NLog-Install/ + 2026-11-10 + + + https://nlog-project.org/wiki/NLog-Trace-Listener-for-System-Diagnostics-Trace/ + 2026-11-10 + + + https://nlog-project.org/wiki/NLog-config-Example/ + 2026-11-10 + + + https://nlog-project.org/wiki/NLogDir-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/NLogViewer-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/NdlcTiming-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Network-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Newline-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/NoRawValue-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Null-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/ObjectPath-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/OnException-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/OnHasProperties-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/OutputDebugString-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Pad-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/PerfCounter-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Performance/ + 2026-11-10 + + + https://nlog-project.org/wiki/PerformanceCounter-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Platform-Support/ + 2026-11-10 + + + https://nlog-project.org/wiki/PostFilteringWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/ProcessDir-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ProcessId-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ProcessInfo-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ProcessStart-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Processname-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Processtime-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Properties-constraints-for-custom-extensions/ + 2026-11-10 + + + https://nlog-project.org/wiki/QPC-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/RandomizeGroup-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/RegEx-Replace-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Register-your-custom-component/ + 2026-11-10 + + + https://nlog-project.org/wiki/Registry-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Reinitialize-NLog-configuration/ + 2026-11-10 + + + https://nlog-project.org/wiki/RepeatingWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Replace-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Replace-NewLines-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/RetryingWrapper-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/RichTextBox-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Right-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Rot13-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/RoundRobinGroup-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/SL-AppInfo-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ScopeIndent-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ScopeNested-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ScopeProperty-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ScopeTiming-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/SequenceId-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ShortDate-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/SimpleLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/Special-Folder-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/SplitGroup-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Splunk-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/SplunkLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/Stack-Trace-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Substring-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Syslog-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/SyslogLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/Targets-and-Wrappers/ + 2026-11-10 + + + https://nlog-project.org/wiki/Targets/ + 2026-11-10 + + + https://nlog-project.org/wiki/TempDir-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/TextLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/ThreadId-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/ThreadName-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Ticks-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Time-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Time-Source/ + 2026-11-10 + + + https://nlog-project.org/wiki/ToolStripItem-Target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Tools/ + 2026-11-10 + + + https://nlog-project.org/wiki/Trace-Activity-Id-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Trace-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Trim-Whitespace-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Tutorial/ + 2026-11-10 + + + https://nlog-project.org/wiki/Uppercase-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Url-Encode-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Var-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/Visual-Studio-Support/ + 2026-11-10 + + + https://nlog-project.org/wiki/W3CExtendedLogLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/Web-resources/ + 2026-11-10 + + + https://nlog-project.org/wiki/WebService-target---Workaround-for-url-variables/ + 2026-11-10 + + + https://nlog-project.org/wiki/WebService-target/ + 2026-11-10 + + + https://nlog-project.org/wiki/Webservice-Target-for-Splunk/ + 2026-11-10 + + + https://nlog-project.org/wiki/When-Filter/ + 2026-11-10 + + + https://nlog-project.org/wiki/When-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/WhenContains-filter/ + 2026-11-10 + + + https://nlog-project.org/wiki/WhenEmpty-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/WhenEqual-filter/ + 2026-11-10 + + + https://nlog-project.org/wiki/WhenNotContains-filter/ + 2026-11-10 + + + https://nlog-project.org/wiki/WhenNotEqual-filter/ + 2026-11-10 + + + https://nlog-project.org/wiki/WhenRepeated-Filter/ + 2026-11-10 + + + https://nlog-project.org/wiki/Who-Is-Using-NLog/ + 2026-11-10 + + + https://nlog-project.org/wiki/Windows-Identity-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/WrapLine-layout-renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/XML-config-include-Example/ + 2026-11-10 + + + https://nlog-project.org/wiki/Xml-Encode-Layout-Renderer/ + 2026-11-10 + + + https://nlog-project.org/wiki/XmlLayout/ + 2026-11-10 + + + https://nlog-project.org/wiki/_Sidebar/ + 2026-11-10 + + + https://nlog-project.org/wiki/filters/ + 2026-11-10 + + \ No newline at end of file diff --git a/wiki/sitemap.xml.gz b/wiki/sitemap.xml.gz new file mode 100644 index 000000000..43686725b Binary files /dev/null and b/wiki/sitemap.xml.gz differ