404
+ +Page not found
+ + +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 @@ + + +
+ + + + +Page not found
+ + +Log event all context data.
+++Platforms Supported: All
+Introduced in NLog v4.0.
+
To log one property, use ${event-properties}. See also NLog Context.
${all-event-properties:format=String:separator=String:includeEmptyValues=boolean:includeScopeProperties=boolean}
+
+[key], and the placeholder for value is, [value].[key]=[value],false++Introduced in NLog 4.1. Deprecated with NLog v4.6.8. Removed again with NLog v5 (Net45 required)
+
false++Introduced in NLog 4.6.4.
+
Key1,Key2++Introduced in NLog 4.6.8
+
++Introduced in NLog 5.0
+
Render the application domain name.
+++Platforms Supported: All
+
${appdomain:format=Format}
+
+Long.
+possible options: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
+
+
+ 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.
+
${appsetting:item=String:default=String}
+
+++Introduced with NLog v4.5, and replaces the
+Name-option.
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}
+
+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.
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}
+
${aspnet-appbasepath}
+
+Application base path is also known as the content root, while wwwroot-path is root directory for static content.
+ +ASP.NET EnvironmentName (ASPNETCORE_ENVIRONMENT)
++Platforms Supported: Limited (Only supported in Asp.NetCore)
+Introduced with NLog.Web.AspNetCore v4.4.0
+
${aspnet-environment}
+
+The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or "environment" as specified in any other configuration source.
ASP.NET Item variable from HttpContext.Items dictionary. Useful for storing state per request basis.
++Platforms Supported: All
+
${aspnet-item:variable=String:objectpath=String:format=String}
+
+++Introduced with NLog.Web v5.1, and replaces the
+Variable-option
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.2 and replaces
+EvaluateAsNestedProperties-option
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"
+
+
+ ASP.NET MVC Action-Name by lookup of action-value in HttpContext.Current.GetRouteData
++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-mvc-action}
+
+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.
+ +ASP.NET MVC Controller-Name by lookup of controller-value in HttpContext.Current.GetRouteData
++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-mvc-controller}
+
+Use this layout renderer to insert the Controller from MVC Pipeline.
+See also AspNetRequest-RouteParameters-Layout-Renderer for lookup of other Route-Parameter Values.
+ +ASP.NET Request capable of upgrading connection to an opaque, bidirectional stream.
+1 = Capable / Upgradable0 = Not available++Platforms Supported: Limited (Only supported in Asp.NetCore)
+Introduced with NLog.Web.AspNetCore v5.1.0
+
${aspnet-request-bidirectional-stream}
+
+
+ ASP.NET Request Client Certificate
+++Platforms Supported: All
+Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0
+
${aspnet-request-client-certificate}
+
+
+ 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
+
${aspnet-request-connection-id}
+
+
+ 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
+
${aspnet-request-contentlength}
+
+
+ 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
+
${aspnet-request-contenttype}
+
+
+ ASP.NET Request Duration.
+++Platforms Supported: All
+Introduced with NLog.Web.AspNetCore v5.0.0 and NLog.Web v5.0.0
+
${aspnet-request-duration}
+
+TimeSpan.ToString(format). string. Default null (Outputs milliseconds)CultureInfo.InvariantCultureASP.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
+
${aspnet-request-endpoint-group}
+
+See also ${aspnet-request-endpoint} and ${aspnet-request-endpoint-name}
+ +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
+
${aspnet-request-endpoint}
+
+See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint-name}
+ +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
+
${aspnet-request-endpoint-name}
+
+See also ${aspnet-request-endpoint-group} and ${aspnet-request-endpoint}
+ +ASP.NET supported transport types that the client can use to send HTTP requests (bitwise combination).
+++Platforms Supported: Limited (Only supported in Asp.NetCore)
+Introduced with NLog.Web.AspNetCore v5.1.0
+
${aspnet-request-http-transport-type}
+
+
+ ASP.NET Http Request includes posted-body payload:
+1 = CanHaveBody or ContentLength > 00 = Not available++Platforms Supported: > Platforms Supported: Limited (Only supported in ASP.NET Core v5+)
+Introduced with NLog.Web.AspNetCore v5.1.1
+
${aspnet-request-has-posted-body}
+
+
+ Render Client IP address
+++Platforms Supported: All
+Introduced in NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0
+
${aspnet-request-ip}
+
+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
+
REMOTE_ADDR-ServerVariablesSee also AspNetRequest Host Layout Renderer
+ +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
+
${aspnet-request-inherent-keep-alive}
+
+
+ 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
+
${aspnet-request-is-web-socket}
+
+
+ ASP.NET Request HttpContext.Connection.LocalIpAddress
+++Platforms Supported: All
+Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0
+
${aspnet-request-local-ip}
+
+
+ ASP.NET Request HttpContext.Connection.LocalPort
+++Platforms Supported: All
+Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0
+
${aspnet-request-local-port}
+
+
+ ASP.NET Request HttpContext.Connection.RemotePort
+++Platforms Supported: All
+Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0
+
${aspnet-request-remote-port}
+
+
+ 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
+
${aspnet-request-servervariable:item=APP_POOL_ID}
+
+
+ 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
+
${aspnet-request-stream-id}
+
+
+ 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
+
${aspnet-request-tls-handshake:property=Protocol}
+
+++Introduced with NLog.Web.AspNetCore v6.1.0
+
++Introduced with NLog.Web.AspNetCore v6.1.0
+
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
+
${aspnet-request-tls-token-binding:property=provider}
+
+ASP.NET Tracking Consent
+++Platforms Supported: Limited (Only supported in Asp.NetCore)
+Introduced with NLog.Web.AspNetCore v5.1.0
+
${aspnet-request-tracking-consent:property=CanTrack}
+
+1), or if consent is not required (0)ASP.NET Request Trailers
+++Platforms Supported: Limited (Only supported in Asp.NetCore)
+Introduced with NLog.Web.AspNetCore v5.1.0
+
${aspnet-request-trailersitems=String[]:outputFormat=Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+Key1,Key2 (Not specified means all)++Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the
+TrailerNames-option.
Key1,Key2Flat.Flat - Key-value-pair as standard stringJsonArray - Key-value-pair in JSON-arrayJsonDictionary - Key-value-pair as JSON-dictionary,. Only applies when OutputFormat is Flat.=. Only applies when OutputFormat is Flat. false.false.++Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1
+
ASP.NET Request HttpContext.WebSockets.WebSocketRequestedProtocols
+++Platforms Supported: All
+Introduced with NLog.Web.AspNetCore v5.1.0 and NLog.Web v5.1.0 (NET46)
+
${aspnet-request-web-socket-requested-protocols}
+
+Flat.Flat - Key-value-pair as standard stringJsonArray - Key-value-pair in JSON-array
itemSeparator Separator between items. Default: ,. Only applies when OutputFormat is Flat.
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 usingNLogRequestPostedBodyModule.⚠️ 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.
${aspnet-request-posted-body}
+
+NLogRequestPostedBodyMiddleware as middleware in the Configure method of Startup class // 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
'application/', 'json''application/', 'xml''application/', 'html''text/', '''', 'charset'Predicate<HttpContext> ShouldCapture()
See also: HTTP-Request-Logging
+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
+ +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
+
${aspnet-response-contentlength}
+
+
+ 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
+
${aspnet-response-contenttype}
+
+
+ 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
+
${aspnet-response-cookie:items=String[]:outputFormat=Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+Key1,Key2 (Not specified means all) ++Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the
+cookieNames-option.
Key1,Key2Flat.Flat - Key-value-pair as standard stringJsonArray - Key-value-pair in JSON-arrayJsonDictionary - Key-value-pair as JSON-dictionary.
itemSeparator - Separator between items. Default: ,. Only applies when OutputFormat is Flat.
=. Only applies when OutputFormat is Flat.;. Only applies when OutputFormat is Flat and Verbose is True.false.false.++Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1
+
In C# code:
+Request.Cookies["key1"] = "value1";
+Request.Cookies["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+${aspnet-response-cookie:CookieNames=key1}
+
+Will print:
+"key1=value1"
+
+${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"}]
+
+${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"]
+
+${aspnet-response-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+
+ ASP.NET Response HTTPS Compression Mode
+++Platforms Supported: Limited (Only supported in Asp.NetCore)
+Introduced with NLog.Web.AspNetCore v5.1.0
+
${aspnet-response-https-compression}
+
+
+ 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
+
${aspnet-response-has-started}
+
+
+ ASP.NET Response Headers key/value pairs.
+++Platforms Supported: All
+Introduced in NLog.Web 5.1.0 and NLog.Web.AspNetCore 5.1.0
+
${aspnet-response-headers:items=String[]:outputFormat=Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+Key1,Key2 (Not specified means all)++Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the
+headerNames-option.
Key1,Key2Flat.Flat - Key-value-pair as standard stringJsonArray - Key-value-pair in JSON-arrayJsonDictionary - Key-value-pair as JSON-dictionary,. Only applies when OutputFormat is Flat.=. Only applies when OutputFormat is Flat. false.false.++Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1
+
Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Response Headers collection.
+In C# code:
+Response.Headers["key1"] = "value1";
+Response.Headers["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+${aspnet-response-headers:items=key1}
+
+Will print:
+"key1=value1"
+
+${aspnet-response-headers:items=key1,id}
+
+Will print:
+"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+${aspnet-response-headers:items=key1:OutputFormat=JSON}
+
+Will print:
+[{"key1":"value1"}]
+
+${aspnet-response-headers:items=key1,id:OutputFormat=JSON}
+
+Will print:
+[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+${aspnet-response-headers:items=key1:OutputFormat=JsonDictionary}
+
+Will print:
+{"key1":"value1"}
+
+${aspnet-response-headers:items=key1:ValuesOnly=true}
+
+Will print:
+"value1"
+
+${aspnet-response-headers:items=key1:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1"]
+
+${aspnet-response-headers:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+
+ ASP.NET Response Trailers
+++Platforms Supported: Limited (Only supported in Asp.NetCore)
+Introduced with NLog.Web.AspNetCore v5.1.0
+
${aspnet-response-trailers:items=String[]:outputFormat=Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+Key1,Key2 (Not specified means all)++Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the
+TrailerNames-option.
Key1,Key2Flat.Flat - Key-value-pair as standard stringJsonArray - Key-value-pair in JSON-arrayJsonDictionary - Key-value-pair as JSON-dictionary,. Only applies when OutputFormat is Flat.=. Only applies when OutputFormat is Flat. false.false.++Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1
+
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
+
${aspnet-user-claim:ClaimTypes.Name}
+
+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.
+
NLog.Web.AspNetCore v5.3.3 supports the following formatting options, when outputting all value by not specifying any ClaimType:
+Flat.Flat - Key-value-pair as standard stringJsonArray - Key-value-pair in JSON-arrayJsonDictionary - Key-value-pair as JSON-dictionary,. Only applies when OutputFormat is Flat.=. Only applies when OutputFormat is Flat. false.false.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 ApplicationIdRender if user is authenticated. Renders 0 or 1.
++Platforms Supported: All
+Introduced in NLog Web.AspNetCore 4.4.0 & NLog.Web 4.5.0
+
${aspnet-user-isAuthenticated}
+
+
+ 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
+
${aspnet-webrootpath}
+
+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.
+ +ASP.NET Application Dictionary Value.
+++Platforms Support: Limited (Not supported in ASP.NET Core - ServerVariables are non-existing in ASP.NET Core. )
+
${aspnet-application:variable=String}
+
+++Introduced with NLog.Web v5.1, and replaces the
+Variable-option
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.2.1
+
Use this layout renderer to output the value of the specified variable stored in the ASP.NET Application dictionary
+ +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
+
<targets>
+ <target xsi:type="AspNetBufferingWrapper"
+ name="String"
+ bufferGrowLimit="Integer"
+ growBufferAsNeeded="Boolean"
+ bufferSize="Integer">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+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
+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 >= LogLevel.Info">
+ <target xsi:type="File" fileName="request-failed-${shortdate}.log" />
+ <when exists="level >= LogLevel.Warn" filter="level >= LogLevel.Debug"/>
+ </target>
+ </target>
+</targets>
+
+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.
+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>
+
+
+ ASP.NET Item variable from HttpContext.Items dictionary. Useful for storing state per request basis.
++Platforms Supported: All
+
${aspnet-item:item=String:objectpath=String:format=String}
+
+++Introduced with NLog.Web v5.1, and replaces the
+Variable-option
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.2 and replaces
+EvaluateAsNestedProperties-option
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"
+
+
+ ASP.NET Request Cookie key/value pairs.
+++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-request-cookie:items=String[]:outputFormat=Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+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
Flat.Flat - Key-value-pair as standard stringJsonArray - 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
+
=. Only applies when OutputFormat is Flat.++Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5
+
false.++Introduced in NLog.Web / NLog.Web.AspNetCore v4.6
+
false.++Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1
+
Use this layout renderer to log the value of the specified cookie(s) stored in the ASP.NET Request Cookies collection.
+In C# code:
+Request.Cookies["key1"] = "value1";
+Request.Cookies["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+${aspnet-request-cookie:items=key1}
+
+Will print:
+"key1=value1"
+
+${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"}]
+
+${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"]
+
+${aspnet-request-cookie:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+
+ ASP.NET Request Form key/value pairs.
+++Platforms Supported: All
+Introduced in NLog.Web 4.7
+
${aspnet-request-form:items=String[]:exclude=String[]:outputFormat=Enum
+ :itemSeparator=Layout:valueSeparator=Layout
+ :valuesOnly=Boolean}
+
+Key1,Key2 (Not specified means all)++Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.2, and replaces the
+include-option.
Key1,Key2.Flat.Flat - Key-value-pair as standard stringJsonArray - 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),. Only applies when OutputFormat is Flat.=. Only applies when OutputFormat is Flat.false.false.++Introduced in NLog.Web / NLog.Web.AspNetCore 5.1.1
+
Use this layout renderer to log the ASP.NET Request Form collection.
+In C# code:
+httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues>{
+ { "id","1" },
+ { "name","Test Person" },
+ { "token","86abe8fe-2237-4f87-81af-0a4e522b4140" }
+});
+
+${aspnet-request-form}
+
+Will print:
+"id=1,name=Test Person,token=86abe8fe-2237-4f87-81af-0a4e522b4140"
+
+${aspnet-request-form:OutputFormat=JSON}
+
+Will print:
+[{"id":"1"},{"name":"Test Person"},{"token":"86abe8fe-2237-4f87-81af-0a4e522b4140"}]
+
+${aspnet-request-form:items=id,name}
+
+Will print:
+"id=1,name=Test Person"
+
+${aspnet-request-form:Exclude=token}
+
+Will print:
+"id=1,name=Test Person"
+
+${aspnet-request-form:ItemSeparator=${newline}}
+
+Will print:
+"id=1\r\nname=Test Person\r\ntoken=86abe8fe-2237-4f87-81af-0a4e522b4140"
+
+
+ ASP.NET Request Headers key/value pairs.
+++Platforms Supported: All
+Introduced in NLog.Web 4.9 and NLog.Web.AspNetCore 4.9
+
${aspnet-request-headers:headerNames=String[]:outputFormat=Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+Key1,Key2 (Not specified means all)++Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the
+headerNames-option.
Key1,Key2Flat.Flat - Key-value-pair as standard stringJsonArray - 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),. Only applies when OutputFormat is Flat.=. Only applies when OutputFormat is Flat. false. false.++Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1
+
Use this layout renderer to log the value of the specified headers(s) stored in the ASP.NET Request Headers collection.
+In C# code:
+Request.Headers["key1"] = "value1";
+Request.Headers["id"] = "d4b20a34-6231-4201-83a6-c72599e41164";
+
+${aspnet-request-headers:HeaderNames=key1}
+
+Will print:
+"key1=value1"
+
+${aspnet-request-headers:HeaderNames=key1,id}
+
+Will print:
+"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON}
+
+Will print:
+[{"key1":"value1"}]
+
+${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON}
+
+Will print:
+[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+${aspnet-request-headers:HeaderNames=key1:OutputFormat=JsonDictionary}
+
+Will print:
+{"key1":"value1"}
+
+${aspnet-request-headers:HeaderNames=key1:ValuesOnly=true}
+
+Will print:
+"value1"
+
+${aspnet-request-headers:HeaderNames=key1:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1"]
+
+${aspnet-request-headers:HeaderNames=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+
+ ASP.NET Request DNS name of the remote client
+++Platforms Supported: All (ASP.NET Core + ASP.NET)
+Introduced in NLog.Web 4.3
+
${aspnet-request-host}
+
+Host-HeaderREMOTE_ADDR-ServerVariableSee also AspNet Request IP Layout Renderer
+ +ASP.NET HTTP Method. GET/POST/PUT etc.
+++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-request-method}
+
+Use this layout renderer to insert the HTTP Request Method.
+ +ASP.NET Request Query String key/value pairs.
+++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-request-querystring:items=String:outputFormat:Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+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.
+
Key1,Key2++Introduced with NLog.Web v5.2.2
+
Flat.Flat - Key-value-pair as standard stringJsonArray - 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),. Only applies when OutputFormat is Flat.++Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5
+
=. Only applies when OutputFormat is Flat.++Introduced in NLog.Web.AspNetCore 4.4 / NLog.Web 4.5
+
false.++Introduced in NLog.Web / NLog.Web.AspNetCore v4.6
+
false.++Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1
+
Use this layout renderer to insert the value of the specified query string parameters stored in the ASP.NET Query String collection.
+In C# code:
+Response.Redirect("myPage.aspx?key1=value1&id=d4b20a34-6231-4201-83a6-c72599e41164");
+
+${aspnet-request-querystring:items=key1}
+
+Will print:
+"key1=value1"
+
+${aspnet-request-querystring:items=key1,id}
+
+Will print:
+"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+${aspnet-request-querystring:items=key1:OutputFormat=JSON}
+
+Will print:
+[{"key1":"value1"}]
+
+${aspnet-request-querystring:items=key1,id:OutputFormat=JSON}
+
+Will print:
+[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+${aspnet-request-querystring:items=key1:OutputFormat=JsonDictionary}
+
+Will print:
+{"key1":"value1"}
+
+${aspnet-request-querystring:items=key1:ValuesOnly=true}
+
+Will print:
+"value1"
+
+${aspnet-request-querystring:items=key1:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1"]
+
+${aspnet-request-querystring:items=key1,id:OutputFormat=JSON:ValuesOnly=true}
+
+Will print:
+["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+
+ ASP.NET Request HTTP URL Referrer.
+++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-request-referrer}
+
+
+ <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
+ +ASP.NET Request RouteParameters key/value pairs.
+++Platforms Supported: All
+Introduced in NLog.Web 5.0 and NLog.Web.AspNetCore 5.0
+
${aspnet-request-routeparameters:items=String:outputFormat=Enum
+ :itemSeparator=String:valueSeparator=String
+ :valuesOnly=Boolean}
+
+Key1,Key2 (Not specified means all)++Introduced with NLog.Web / NLog.Web.AspNetCore v5.2.1, and replaces the
+RouteParameterKeys-option.
Flat.Flat - Key-value-pair as standard stringJsonArray - Key-value-pair in JSON-arrayJsonDictionary - Key-value-pair as JSON-dictionary,. Only applies when OutputFormat is Flat.=. Only applies when OutputFormat is Flat. false.false.++Introduced in NLog.Web / NLog.Web.AspNetCore v5.1.1
+
Use this layout renderer to log the value of the specified route-parameter(s) stored in the ASP.NET GetRouteData() Values collection.
+${aspnet-request-routeparameters:Items=key1}
+
+Will print:
+"key1=value1"
+
+${aspnet-request-routeparameters:items=key1,id}
+
+Will print:
+"key1=value1,id=d4b20a34-6231-4201-83a6-c72599e41164"
+
+${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray}
+
+Will print:
+[{"key1":"value1"}]
+
+${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray}
+
+Will print:
+[{"key1":"value1","id":"d4b20a34-6231-4201-83a6-c72599e41164"}]
+
+${aspnet-request-routeparameters:items=key1:OutputFormat=JsonDictionary}
+
+Will print:
+{"key1":"value1"}
+
+${aspnet-request-routeparameters:items=key1:ValuesOnly=true}
+
+Will print:
+"value1"
+
+${aspnet-request-routeparameters:items=key1:OutputFormat=JsonArray:ValuesOnly=true}
+
+Will print:
+["value1"]
+
+${aspnet-request-routeparameters:items=key1,id:OutputFormat=JsonArray:ValuesOnly=true}
+
+Will print:
+["value1","d4b20a34-6231-4201-83a6-c72599e41164"]
+
+
+ ASP.NET Request URL
+++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-request-url:IncludeHost=boolean:IncludePort=boolean:IncludeQueryString=boolean:IncludeScheme=boolean}
+
+Scheme, Host, Path++Introduced with NLog v5.1.1
+
Host). Default is true.Port). Default is false.Query). Default is false.http:// or https://) (Assigns Properties |= Scheme). Default is true.++Introduced in NLog.Web.AspNetCore v4.4.1 and NLog.Web v4.5.1.
+
Path). Default is true.++Introduced in NLog.Web.AspNetCore v5.0 and NLog.Web v5.0.
+
false.++Introduced in NLog.Web.AspNetCore v4.9.2 (Not supported for NLog.Web)
+
${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
+
+
+ Renders the ASP.NET UserAgent from HTTP Request.
+++Platforms Supported: All
+Introduced in NLog.Web 4.3
+
${aspnet-request-useragent}
+
+
+ ASP.NET Request variable.
+++Platforms Supported: All
+
This layout renderer is broken down to separate layout renders who are more ASP.NET Core compatible / future proof:
+AUTH_USER / REMOTE_USER / LOGON_USER)And there are many more NLog LayoutRenderers to choose from
+${aspnet-request:cookie=String:serverVariable=String:queryString=String
+ :item=String:form=String:header=String}
+
+++Not supported on ASP.NET Core until NLog.Web.AspNetCore v5.1
+
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.
+Full URL without domain, eg default.aspx?id=512
${aspnet-request:serverVariable=HTTP_URL}${aspnet-request:queryString}
URL doing the request. Including schema (e.g https://) and querystring
${aspnet-request:header=Referer}
Content-Type like application/json; charset=UTF-8
${aspnet-request:header=Content-Type}
Method like PUT, POST, GET etc
+${aspnet-request:serverVariable=REQUEST_METHOD}
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}
ASP.NET Response Status Code.
+++Platforms Supported: All
+Introduced in NLog.Web 4.9
+
${aspnet-response-statuscode:format=d}
+
+G for string-value and D for integer-value. Default: D++Introduced with NLog.Web 5.2.2
+
ASP.NET Item Variable from Session Dictionary
+++Platforms Supported: All
+
${aspnet-session:item=String:objectpath=String:format=String:ValueType=String|Int32}
+
+++Introduced with NLog.Web v5.1, and replaces the
+Variable-option
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.0
+
++Introduced with NLog.Web v5.2 and replaces
+EvaluateAsNestedProperties-option
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 valuetypestring, 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
+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"
+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"
+ +ASP.NET Session ID.
+++Platforms Supported: All
+
${aspnet-sessionid}
+
+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
+ +Writes log messages to the ASP.NET Trace using TraceContext from HttpContext.
+++Platforms Supported: Limited - .NET Framework only and requires nuget-package NLog.Web
+
<targets>
+ <target xsi:type="AspNetTrace" name="String" layout="Layout" />
+</targets>
+
+Read more about using the Configuration File.
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}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.
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;
+ }
+ }
+}
+
+
+ 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
+
${aspnet-TraceIdentifier:ignoreActivityId=boolean}
+
+HttpContext.TraceIdentifier instead of System.Diagnostics.Activity.Current.IdSystem.Diagnostics.Activity.Current.Id. HttpContext.TraceIdentifierHttpWorkerRequest.RequestTraceIdentifier.CorrelationManager.ActivityId.See code
+ +ASP.NET HttpContext User.Identity.AuthenticationType
+++Platforms Supported: All
+
${aspnet-user-authtype}
+
+
+ ASP.NET HttpContext User.Identity.Name
+++Platforms Supported: All
+
Similar to AUTH_USER / REMOTE_USER / LOGON_USER in Server Variables.
${aspnet-user-identity}
+
+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)
For additional details about the user identity, then one can also use ${aspnet-user-claim}
+ +Moved to AspNetRequest Layout Renderer
+ +Outputs log messages through the ASP Response object.
+Supported in .NET and Mono
+<targets>
+ <target xsi:type="AspResponse" name="String" addComments="Boolean" layout="Layout" />
+</targets>
+
+Read more about using the configuration file.
+<!-- --> comments around all written texts. Boolean${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}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>
+
+
+ ASP Session variable.
+Supported in .NET and Mono
+${asp-session:variable=String}
+
+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.
+
${assembly-version:name=string:type=Enum:format=string}
+
+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
+
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.
+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}
+
+
+ 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
+
<targets>
+ <target xsi:type="AsyncWrapper"
+ name="String"
+ queueLimit="Integer"
+ timeToSleepBetweenBatches="Integer"
+ batchSize="Integer"
+ overflowAction="Enum">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+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:
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
+
Remember to Flush before application exit, is very important when enabling use of the Asynchronous target wrapper.
+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>
+
+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>
+
+<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>
+
+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.
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.
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
+
<targets>
+ <target xsi:type="AtomFile"
+ name="string"
+ fileName="Layout"
+ layout="Layout"
+ concurrentWrites="boolean"
+ keepFileOpen="boolean"
+ />
+</targets>
+
+++Default:
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
truefalse. Default: trueAlso inherits all parameters from the standard File-Target.
+Uses libc open() with O_APPEND flag, which is supported on Linux and other Unix-like operating systems.
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
+
<targets>
+ <target xsi:type="AutoFlushWrapper" name="String" condition="Condition">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+++Introduced in NLog 4.4
+
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.
NLog.LogManager.Flush() or NLog.LogManager.Shutdown(). Useful when combined with BufferingWrapper and overflowAction=Discard.++Introduced in NLog 4.6.6
+
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>
+
+
+ The current application AppDomain.BaseDirectory, and usually the location of application-binaries.
+++Platforms Supported: All
+See also ${processdir}, ${specialfolder}, ${currentdir}, ${tempdir}
+
${basedir:dir=String:file=String:processDir=boolean}
+
+false. ++Alternative one can use the
+${processdir}introduced with NLog v4.7.1
++Introduced with NLog v4.6.8
+
See also: FileTarget FileName Directory
+ +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
+
<targets>
+ <target xsi:type="BufferingWrapper"
+ name="String"
+ bufferSize="Integer"
+ flushTimeout="Integer"
+ slidingTimeout="Boolean"
+ overflowAction="Enum">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+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:
flushTimeout option.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.
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.
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>
+
+
+ Applies caching to another layout output.
+++Platforms Supported: All
+
${cached:cached=Boolean:clearCache=ClearCacheOption:inner=Layout:cacheKey=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:cached=Boolean}
+
+None, OnInit, Onclose. ClearCacheOption Default: OnInit, OnClose. ++Introduced in NLog 4.2.
+
null.++Introduced in NLog 4.3.9
+
++Introduced in NLog 4.6.8
+
${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.The value of the inner layout will be rendered only once and reused subsequently.
+ +The call site source file name. For full callsite use CallSiteLayoutRenderer
+Introduced in NLog v4.5
+Supported in .NET and Mono.
+${callsite-filename:includeSourcePath=Boolean:skipFrames=Integer}
+
+++Introduced with NLog 4.7.1
+
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.
+ +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
+
${callsite:className=Boolean:fileName=Boolean:includeSourcePath=Boolean:methodName=Boolean}
+
+TrueTrue++Introduced with NLog v4.4
+
FalseTrueTrueTrue++Introduced with NLog v4.3.9. Before NLog 5.0 the default value was
+False.
True++Introduced with NLog v4.5. Before NLog 5.0 the default value was
+False.
0++Introduced with NLog 4.7.1
+
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>
+
+
+ The call site source-code line-number. For full callsite use ${callsite}
+++Platforms Supported: All
+Introduced in NLog v4.1
+
${callsite-linenumber:skipFrames=Integer}
+
+++Introduced with NLog 4.7.1
+
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.
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
+<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.
+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:
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:
+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:
+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
+16with NLog v4.5 (Before0)
onConnectionOverflow - Action that should be taken when open connections are higher than limit maxConnections.
+++Introduced with NLog v4.2.1. Default became
+Blockwith NLog v4.5 (BeforeAllowNewConnnection)
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
+
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.
+<?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>
+
+
+ Writes log messages to the console with customizable coloring.
+++Platforms Supported: All
+
There is also the simple Console-Target without any overhead from coloring.
+<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.
+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
+
${longdate}|${level:uppercase=true}|${logger}|${message}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 tofalse.
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
+
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 |
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 \
false falsetext can include special characters for matching, but only highlight letter-/digit-part.NLog v6 no longer supports word-highlight using Regular Expressions (RegEx) and removed these options:
+false, the regex cache is used. Setting this to true can improve performance, but costs memory. Default: false| 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 | +
var consoleTarget = new ColoredConsoleTarget();
+
+var highlightRule = new ConsoleRowHighlightingRule();
+highlightRule.Condition = ConditionParser.ParseExpression("level == LogLevel.Info");
+highlightRule.ForegroundColor = ConsoleOutputColor.Green;
+consoleTarget.RowHighlightingRules.Add(highlightRule);
+
+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
+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}")
See Stackoverflow
+Or use The Visual Studio extension VSColorOutput (VS2015-2019). Then you could also use the regular Console target.
+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
+ +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
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();
+ }
+}
+
+
+
+ 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
+
+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" }
+
+<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" }
+
+
+ See https://github.com/NLog/NLog/wiki/When-Filter#conditions
+ +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
+
${configsetting:item=String:default=String}
+
+. for nested objects.${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;
+
+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
moved here: https://github.com/NLog/NLog/wiki/Configure-from-code
+ +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.
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
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.
+ +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).
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.
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.
+ +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.
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 logwriteTo – comma separated list of targets to write tofinal – no rules are processed after a final rule matchesenabled - 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.4The 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.
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>
+
+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)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.
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:
+level, minlevel etc):<variable name='globalLevel' value='debug'/>
+
+<rules>
+ <logger minlevel='${globalLevel}'/>
+</rules>
+
+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
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:
+${varName}${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:
${var:password:default=unknown}keepVariablesOnReload="false".++NLog 4.4 introduced
+keepVariablesOnReloadand before NLog 5.0 the default value wasfalse
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>
+
+
+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
+ +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.
+ +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.
+ +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 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
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.
+ +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
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 layoutNested 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 :)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.
+ +Moved here https://github.com/NLog/NLog/wiki/Configuration-file
+ +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").
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}
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
+ +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/
+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");
+});
+
+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;
+
+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.
+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.
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
+
+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}
+ +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.
+<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.
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}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 tofalse.
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
+WriteBufferwhich was introduced with v4.6.8.
<target name="Console" xsi:type="Console" layout="${longdate} ${logger} ${level} ${message}"/>
+
+
+ Besides the information included with the log message, then there are several options for capturing additional local context state with the LogEvent:
+LogEventInfo.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.
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.BeginScopewith NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided properties.
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.BeginScopewith NLog.Extension.Logging, then it will automatically update NLog ScopeContext with provided scope-name.
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
+}
+
+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.
+ +A counter value (increases on each layout rendering).
+++Platforms Supported: All
+
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}
+
+A specialized layout that renders CSV-formatted events.
+++Platforms Supported: All
+
<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>
+
+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
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:
, character (ASCII 44).CustomColumnDelimiter.| character (ASCII 124).; character (ASCII 59).<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>
+
+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>
+
+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}"),
+ }
+}
+
+
+ The current working directory of the application.
+++Platforms Supported: All
+Introduced in NLog v4.5.
+See also ${basedir}, ${specialfolder}, ${processdir}, ${tempdir}
+
${currentdir:dir=String:file=String}
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.
+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
+ +There can be different reasons for extending the NLog logging interface:
+There already exists several libraries that provides an abstract interface:
+There are two ways to extend the NLog Logger.
+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);
+ }
+}
+
+
+ DB null for a database
+++Platforms Supported: All
+
Introduced in NLog 4.6. Most usefull for the Database target
+${db-null}
+
+Render a DbNull value for the database parameter
The data types used in NLog
+true or false in the XML.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!
+<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.
+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.
+textStoredProcedure - The commandText is the stored procedure name.TableDirect -Text - regular querycommandText - 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 \
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 \
"NpgsqlDbType.Json" with NpgsqlParameter.
+ Introduced in NLog 4.6. Since NLog 4.7 not case-sensitive any morenull for nullable types and null and '' for strings. See Installing targets.
+textStoredProcedure - The command-text is the stored procedure name.TableDirect -Text - regular querytextStoredProcedure - The command-text is the stored procedure name.TableDirect -Text - regular queryIntroduced 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
+<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>
+
+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.
allowDbNull exampleWhere null and empty string-value is converted to DbNull-value:
+<parameter name="@activityid" layout="${activityid}" dbType="DbType.Guid" allowDbNull="true" />
+
+<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>
+
+This approach keeps the NLog.config file simpler, and helps confine +database logic to the database.
+<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>
+
+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
+
+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-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);
+
+Install package: https://www.nuget.org/packages/Microsoft.Data.SqlClient/
+dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"
+
+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"
+
+Install package: https://www.nuget.org/packages/System.Data.SQLite
+dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
+
+Install package: https://www.nuget.org/packages/Microsoft.Data.SQLite/
+dbProvider="Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"
+
+Install package: https://www.nuget.org/packages/Npgsql/
+dbProvider="Npgsql.NpgsqlConnection, Npgsql"
+
+dbProvider="Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess"
+
+dbProvider="Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite"
+
+ <target xsi:type="Database"
+ name="MdbLog"
+ dbProvider="oledb"
+ connectionString="Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\path\to\my.mdb">
+ ...
+
+
+ Current date and time.
+++Platforms Supported: All
+Alternative ${longdate} or ${shortdate} can be used for high performance timestamp-logging.
+
${date:universalTime=Boolean:format=String:culture=Culture}
+
+++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
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)
Mock target for unit-testing. If looking for output to System.Diagnostics.Debug then use DebugSystem-target.
++Platforms Supported: All
+
<targets>
+ <target xsi:type="Debug" name="String" layout="Layout" />
+</targets>
+
+Read more about using the Configuration File.
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}(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
+ +Sends log messages through System.Diagnostics.Debug.WriteLine
+++Platforms Supported: All (Introduced with NLog 5.0)
+
<targets>
+ <target xsi:type="DebugSystem" name="String" layout="Layout" />
+</targets>
+
+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
Writes log messages to the attached managed debugger (Ex. Visual Studio Output Window). See also System.Diagnostics.Debugger.Log
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="Debugger" name="String" layout="Layout" />
+</targets>
+
+Read more about using the Configuration File.
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}${logger}++Introduced with NLog v6.1
+
OnOverflow-action (0 means unlimited) . Default: 0.++Introduced with NLog v6.1
+
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.From stackoverflow
+<targets>
+ <target name="debugger" xsi:type="Debugger" layout="${level}|${message:withException=true}"/>
+</targets>
+
+<rules>
+ <logger name="*" minlevel="Trace" writeTo="debugger" />
+</rules>
+
+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
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.
+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.CreateInstanceas 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
+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
+ +Renders the OS dependent directory separator
+Introduced in NLog 4.7
+++Platforms Supported: All
+
${dir-separator}
+
+Same result as Path.DirectorySeparatorChar
URI of the HTML page which hosts the current Silverlight application.
+++Supported in Silverlight (NLog 5.0 does not support Silverlight)
+
${document-uri}
+
+
+ Thread User identity information (username).
+++Platforms Supported: All
+Introduced with NLog ver. 4.6.4
+
${environment-user:userName=Boolean:domain=Boolean}
+
+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.
+ +The environment variable like USERNAME, TMP, USERPROFILE, COMPUTERNAME, PROCESSOR_ARCHITECTURE etc.
++Platforms Supported: All
+
${environment:variable=String}
+
+USERNAME, TMP, USERPROFILE, COMPUTERNAME, PROCESSOR_ARCHITECTURE etc.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:
+setdir env: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" />
+
+
+ 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>
+
+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).
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
+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)
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:
+appsettings.Production.json or environment variables)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)
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
+ +Log event property data.
+++Platforms Supported: All
+
${event-properties:item=MyValue}
+
+Note that ${event-properties} syntax replaces the now deprecated ${event-context} syntax.
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"
+
+
+ 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.
${event-properties:item=String:culture=String:format=String:objectpath=String}
+
+true. Introduced in NLog 5.0Id, Details.Title. Introduced in NLog 4.6.3CultureInfo.InvariantCultureformat=@ means serialize object properties into Json-format. Introduced in NLog 4.5.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"
+
+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"
+
+++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
+
+NLog 5.0 provides Fluent-Logger-API for building LogEvents:
+_logger.ForInfoEvent()
+ .Message("This is a fluent message {0}.", "test")
+ .Property("PropertyName", "PropertyValue")
+ .Log();
+
+When LogEvent Property cannot be found (or has blank value), then one can use whenEmpty to specify fallback value:
+${event-properties:EventId:whenEmpty=42}
+
+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
+ +Writes log message to the Windows Event Log.
+++Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsEventLog since NLog 5.0
+
<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.
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}. Note: max size of 31839 characters (limitation of the EventLog API). ++NLog 6.0 changed property-type from string to NLog Layout.
+
++NLog 4.0 changed property-type from string to NLog Layout.
+
++NLog 5.0 changed property-type from string to NLog Layout.
+
++NLog 5.0 changed property-type from standard NLog Layout to typed-layout.
+
++NLog 5.0 changed property-type from standard NLog Layout to typed-layout.
+
++NLog 6.0 changed property-type from string to NLog Layout.
+
++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.
+
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.
+
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).
+
<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");
+
+
+ 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
+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!
+ +Exception information provided together with the LogEvent. See also How to properly log exceptions.
+++Platforms Supported: All
+
${exception:format=String:innerFormat=String:maxInnerExceptionLevel=Integer:innerExceptionSeparator=String
+ :separator=String:exceptionDataSeparator=string}
+
+ToString,Data. Must be a comma-separated list of exception properties:++Notice before NLog 5.0, then default was just
+message.
Exception.MessageException.GetType().FullNameException.GetType().NameException.ToString()Exception.TargetSiteException.StackTraceException.Data Exception.Source. Introduced in NLog 4.6.7Exception.TargetSite. Introduced in NLog 4.6.7Exception.HResult. 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
+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
+
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.
${exception:format=message}
+
+ToString will also print the innerException:
${exception:format=toString}
+
+Also print exception data, e.g.
+var ex = new Exception();
+ex.Data.Add("data1", "val2");
+throw ex;
+
+${exception:format=toString,Data}
+
+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=@}
+
+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=@}
+
+
+ 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)
+
${exceptiondata:item=String:format=String:BaseException=Boolean}
+
+@ means serialize object properties into Json-format)falseℹ️ See also Environment specific NLog Logging Configuration
+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");
+
+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);
+
+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);
+
+⚠️ 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);
+
+
+ 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.
+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()
${threadid} with help from Layout Renderers.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
+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:
+LoggingConfiguration.AddRule and ReconfigExistingLoggers is threadsafeWhy is trace and debug logs missing in ASP.NET Core?
+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’re writing a library yourself, then the user who's using your library can choose which implementation to use.
+There are some downsides:
+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 <assemblybinding>-magic! So in short: your library should target NLog 4.0 and in the future NLog 5.0.
Provides fallback-on-error.
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="FallbackGroup" name="String" returnToFirstOnSuccess="Boolean">
+ <target xsi:type="wrappedTargetType" ... />
+ <target xsi:type="wrappedTargetType" ... />
+ ...
+ <target xsi:type="wrappedTargetType" ... />
+ </target>
+</targets>
+
+Boolean. Default falseFallback 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>
+
+
+
+ 
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/Time | Thumbnail | Dimensions | User | Comment | |
|---|---|---|---|---|---|
| current | 20:12, 5 June 2010 | 728×450 (59 KB) | Admin (Talk | contribs) |
The following page links to this file: +
+ 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/Time | Thumbnail | Dimensions | User | Comment | |
|---|---|---|---|---|---|
| current | 20:17, 5 June 2010 | 864×581 (105 KB) | Admin (Talk | contribs) |
The following page links to this file: +
Writes log messages to one or more files.
+++Platforms Supported: All
+
<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.
+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:
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:
+
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", orarchiveNumbering="Sequence"with customarchiveFileName-path
++NLog 5.0 added support for
+archiveNumbering="Sequence"with customarchiveFileName-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
+archiveNumberingandarchiveDateFormat.
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 newArchiveSuffixFormat
archiveDateFormat.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:
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 newArchiveSuffixFormat
yyyyMMddyyyyMMddHHmmyyyyMMddHHyyyyMMDefault 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 witharchiveOldFileOnStartupandarchiveAboveSize.
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
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 useKeepFileOpen=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
+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>
+
+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:
+CommonApplicationData.Example using CommonApplicationData which is good when running as Windows Service:
fileName="${specialfolder:folder=CommonApplicationData:cached=true}/AppName/logfile.txt"C:/ProgramData/AppName/logfile.txtTo 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/");
+
+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>
+
+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).
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).
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.
+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>
+
+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>
+
+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>
+
+
+ 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)
+
${file-contents:encoding=Encoding:fileName=Layout}
+
+If the file content doesn't change, then adding the option :cached=true will give a performance boost.
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.
+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>
+
+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:
+<?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>
+
+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>
+
+ <target name="file" xsi:type="File"
+ ...
+ fileName="logfile.txt"
+ archiveFileName="log.{####}.txt"
+ archiveNumbering="Rolling" />
+
+
+Example of file names (newest files first):
+ <target name="file" xsi:type="File"
+ ...
+ fileName="logfile.txt"
+ archiveFileName="log.{####}.txt"
+ archiveNumbering="Sequence" />
+
+
+Example of file names (newest files first):
+ <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):
+ <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):
+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
+
+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>
+
+
+ Filters characters not allowed in the file names by replacing them with safe character.
+++Platforms Supported: All
+
${filesystem-normalize:fSNormalize=Boolean:inner=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:fSNormalize=Boolean}
+
+Log messages may be filtered via either routing or filtering.
+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>
+
+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.
+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");
+});
+
+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
+
+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");
+
+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
+
+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.
+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.
+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.
These filters are deprecated. They have been replace by the <when> filter, which exposes uses modifiable conditions for filtering log events.
<whenContains> filter - Matches when the calculated layout contains the specified substring. <whenEqual> filter - Matches when the calculated layout is equal to the specified substring. <whenNotContains> filter - Matches when the calculated layout does NOT contain the specified substring. <whenNotEqual> filter - Matches when the calculated layout is NOT equal to the specified substring. Filters log entries based on a condition.
+++Platforms Supported: All
+
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>
+
+++Introduced with NLog 4.6.4
+
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>
+
+
+ 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.
+++⚠️ 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();
+}
+
+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();
+}
+
+
+ The NLog Fluent Configuration API allows you to configure NLog directly in C# instead of XML.
+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
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();
+});
+
+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")
+);
+
+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)
+);
+
+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)
+);
+
+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))
+);
+
+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
+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
+Ensure NLog config has been loaded, and fail with exception when not:
+NLog.LogManager.Setup().LoadConfigurationFromFile(optional: false);
+
+Load NLog config from custom location (like assembly resource):
+var fileXmlContent = File.ReadAllText(xmlFilePath);
+NLog.LogManager.Setup().LoadConfigurationFromXml(fileXmlContent);
+
+
+ NLog 5.0 introduces new fluent LogEventBuilder that can be activated with one of these extensions methods for ILogger:
ForLogEvent - Builds base LogEventForTraceEvent - Builds LogEvent with Trace-LogLevelForDebugEvent - Builds LogEvent with Debug-LogLevelForInfoEvent - Builds LogEvent with Info-LogLevelForWarnEvent - Builds LogEvent with Warn-LogLevelForErrorEvent - Builds LogEvent with Error-LogLevelForFatalEvent - Builds LogEvent with Fatal-LogLevelForExceptionEvent - Builds LogEvent with Exception and Error-LogLevelTo 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.
+
_logger.ForInfoEvent()
+ .Message("This is a fluent message {0}.", "test")
+ .Property("PropertyName", "PropertyValue")
+ .Log();
+
+try
+{
+ string text = File.ReadAllText(path);
+}
+catch (Exception ex)
+{
+ _logger.ForExceptionEvent(ex)
+ .Message("Error reading file '{0}'.", path)
+ .Property("Test", "InfoWrite")
+ .Log();
+}
+
+
+ Page move to FormControlTarget - NLog.Windows.Forms
+ +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.
+<targets>
+ <target xsi:type="Gelf"
+ name="String"
+ address="Layout">
+ <gelffield name="String" layout="Layout" /><!-- repeated -->
+ </target>
+</targets>
+
+Read more about using the Configuration File.
+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
+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:
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:
+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.
+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):
+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
+
<?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>
+
+
+ Writes LogEvents to file using GZip compression, by extending the standard NLog File Target.
+++Platforms Supported: All - Requires nuget-package NLog.Targets.GZipFile
+
<targets>
+ <target xsi:type="GZipFile"
+ name="string"
+ fileName="Layout"
+ layout="Layout"
+ compressionLevel="CompressionLevel"
+ keepFileOpen="boolean"
+ enableArchiveFileCompression="boolean"
+ archiveOldFileOnStartup="boolean"
+ />
+</targets>
+
+++Default:
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
Optimal - Optimize for small file sizeFastest - Optimize for speedNoCompression - Disables GZip compressionfalse. Default: truefalse. Default: trueAlso inherits all parameters from the standard File-Target.
+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> |
The information about the garbage collector.
+++Platforms Supported: All
+
${gc:property=Enum}
+
+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
Global Diagnostic Context (GDC) - Dictionary structure for global settings for the entire application-instance.
+++Platforms Supported: All (NLog 4.1 allows storing any
+Objecttype, not justString)
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
+${gdc:item=String}
+
+CultureInfo.InvariantCultureformat=@ means serialize object properties into Json-format.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}
+
+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}
+
+When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.
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>
+
+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
+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.
+In Visual Studio 2017, using .NET 4.6.1+ or .NET Core 2
+
Install:
+e.g.
+ <ItemGroup>
+ <PackageReference Include="NLog" Version="5.4.0" />
+ <PackageReference Include="NLog.Extensions.Logging" Version="5.4.0" />
+ </ItemGroup>
+
+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>
+
+ 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);
+ }
+ }
+
+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();
+}
+
+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
+
+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.
+Install the NLog.Extensions.Logging NuGet package:
+++dotnet add package NLog.Extensions.Logging
+
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.
NLog supports several configuration approaches:
+AddNLog() automatically loads the "NLog" section if present, with environment overrides.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:
+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.
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.
+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.
+ +⚠️ 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
+In Visual Studio 2017.
+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.*" />
+
+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
Enable copy to bin folder for nlog.config
+
or edit .csproj file manually and add:
<ItemGroup>
+ <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
+ </ItemGroup>
+
+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
+
+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
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();
+ }
+
+
+When starting the ASP.NET Core website, we get two files:
+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
+
+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.
+
+Next step, see Configure NLog with nlog.config
+ +⚠️ Missing the trace/debug logs? Check your appsettings.json
+ℹ️ See also example in GitHub
+This tutorial is for ASP.NET Core 3.1
+In Visual Studio 2019.
+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.*" />
+
+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.
Enable copy to bin folder for nlog.config
+
or edit .csproj file manually and add:
<ItemGroup>
+ <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
+ </ItemGroup>
+
+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
+
+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
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();
+ }
+
+
+
+When starting the ASP.NET Core website, we get two files:
+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
+
+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
+
+
+Next step, see Configure NLog with nlog.config
+ +⚠️ Missing the trace/debug logs? Check your appsettings.json
+ℹ️ See also example in GitHub
+This tutorial is for ASP.NET Core 5.
+In Visual Studio 2019. Version 16.8+ is needed
+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>
+
+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.
+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
+ }
+}
+
+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
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();
+ }
+
+
+
+When starting the ASP.NET Core website, we get two files:
+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
+
+
+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!
+
+Next step, see Configure NLog with nlog.config
+ +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.
+Install the NLog ASP.NET Core NuGet package:
+++dotnet add package NLog.Web.AspNetCore
+
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.
NLog supports several configuration approaches:
+UseNLog() automatically loads the "NLog" section if present, with environment overrides.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:
+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.
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.
+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)
+
<targets>
+ <target xsi:type="GroupByWrapper"
+ name="String"
+ key="Layout">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+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>
+
+
+ Globally-unique identifier (GUID).
+++Platforms Supported: All
+
${guid:format=String}
+
+NFalse++Introduced with NLog 4.5
+
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.
+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>
+ ...
+
+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=''
+ >
+
+
+The URL to send messages to (mandatory)
+HTTP method to use (GET,POST,PUT, etc.)
+The Authorization Header value to pass.
+Number of messages to be sent together in one call separated by an empty new line
+Maximum number of messages awaiting to be send. Please note, that if this value is set, the logger might be blocking.
+Some SSL certificates might be invalid or not-trusted.
+Force all messages to be delivered before shutting down.
+HTTP ContentType Header value.
+HTTP Accept Header value.
+How many connections might be used at the same time. Changes ServicePointManager.DefaultConnectionLimit, which might affect other parts of your system.
+See this article.
+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.
+How long should the client wait to connect (default is 30 seconds).
+Reduces the amount of memory consumed at the expense of increased CPU usage.
+Designates a proxy server to use. Must include protocol (http|https) and port
+If proxy authentication is needed, you can specify it with a domain prefix, i.e. DOMAIN\USER.
+Password to use for proxy authentication.
+<?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>
+
+
+ 
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
+ +HostEnvironment ApplicationName
+++Platforms Supported: All
+Introduced with NLog.Extensions.Hostting v6.0 and NLog.Web.AspNetCore v6.0
+
${host-appname}
+
+
+ HostEnvironment EnvironmentName (DOTNET_ENVIRONMENT / ASPNETCORE_ENVIRONMENT)
++Platforms Supported: All
+Introduced with NLog.Extensions.Hostting v6.0 and NLog.Web.AspNetCore v6.0
+
${host-environment}
+
+The host automatically sets this property to the value of the ASPNETCORE_ENVIRONMENT environment variable, or "environment" as specified in any other configuration source.
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
+
${host-rootdir}
+
+Application base path is also known as the content root, while wwwroot-path is root directory for static content.
+ +The computer DNS HostName that the process is running on.
+++Platforms Supported: All
+Introduced with NLog 4.6
+
${hostname}
+
+See also ${machinename} For NetBIOS name
+See also ${local-ip} For IP Address
+ +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.
+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
+}
+
+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>
+
+
+ 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();
+}
+
+
+ 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/
+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
+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.
+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()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"}
+
+
+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
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.
+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>
+
+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.
+Create a new class that NLog.IValueFormatter and set NLog.Config.ConfigurationItemFactory.Default.ValueFormatter
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;
+ }
+ }
+
+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.
The Names of the parameters should be unique
+e.g. Order {orderId}
Use ${message:raw=true}
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>
+
+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"
+
+
+ ++Introduced with NLog 4.6
+
It is really easy:
+NLog.Targets.AsyncTaskTargetWriteAsyncTask(LogEventInfo logEvent, CancellationToken token) method.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!
+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 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).
There are several options:
+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
+}
+
+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).
+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).
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!
+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.
logEventInfo.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);
+
+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}
+});
+
+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.
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!");
+ }
+}
+
+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.
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:
+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.
++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!");
+ }
+}
+
+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}
++Introduced with NLog 4.5
+
It is really easy:
+NLog.Targets.TargetWithContextWrite(LogEventInfo logEvent) method.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
+
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
+ }
+ }
+}
+
+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.
+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>
+
+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).
It’s really easy:
+NLog.Targets.TargetWithLayoutWrite() method.this.Layout.Render() to get the message text, then send the text to the destination media.⚠️ 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
+
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
+ }
+ }
+}
+
+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)
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.
+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="..." />
IIS site name - printing HostingEnvironment.SiteName
++Platforms Supported: All (Supported in AspNet and AspNetCore)
+
${iis-site-name}
+
+
+ Thread identity information (name and authentication information).
+++Platforms Supported: All
+
${identity:authType=Boolean:separator=String:name=Boolean
+ :isAuthenticated=Boolean}
+
+${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.
+Set AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal) in the Main method of your application, otherwise this renderer could render empty unexpectedly. (Read more)
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
+
<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>
+
+userName - Username to change context to.
+++NLog.WindowsIdentity v5.3 changed data-type from
+Stringto Layout
password - User account password.
+++NLog.WindowsIdentity v5.3 changed data-type from
+Stringto Layout
domain - Windows domain name for user account. Default: .
++NLog.WindowsIdentity v5.3 changed data-type from
+Stringto 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:
Impersonation - Impersonation Level.
+logOnType - Logon Type.
+Possible values:
Service - Logon as a Service.
+logOnProvider - Type of the logon provider.
+Possible values:
Installation Context Parameter Value.
+++Platforms Supported: All
+
${install-context:parameter=String}
+
+See also Installing targets
+See also InstallNLogConfig
+Some targets support installing. Current the following targets support installing
+Install all targets used in the config:
+LogManager.Configuration.Install(new InstallationContext());
+
+Uninstall all targets used in the config:
+LogManager.Configuration.Uninstall(new InstallationContext());
+
+<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>
+
+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();
+
+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.
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.
+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.
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");
+ }
+}
+
+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)
+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.Escapes output of another layout using JSON rules.
+++Platforms Supported: All
+
${json-encode:jsonEncode=Boolean:inner=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:jsonEncode=Boolean}
+
+++Introduced in NLog 4.4.7
+
/ will be converted to \/. Default true++Introduced in NLog 4.6.8
+
${event-properties:item=MyValue:jsonEncode=true}
+
+
+ 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" ]
+
+Layout (Ex. SimpleLayout, JsonLayout, etc.)false.[]. Default: true.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" />
+
+true
+ > Introduced in NLog 4.1true
+ > Introduced in NLog 4.4.7false
+ > Introduced in NLog 4.5false,
+ > Introduced in NLog 4.6.8. Before NLog 5.0 the default was true. After NLog 6.0 it has no effect.true.++Introduced in NLog 4.1. Before NLog 6.0 the default was
+false
false.++Introduced in NLog v5.1.4
+
{}. Default = true.++Introduced in NLog 4.3.7
+
false.++Introduced in NLog 4.4.10
+
false.++Before NLog 5.0 option was named IncludeAllProperties
+
false.++Before NLog 5.0 option was named IncludeMdlc or IncludeMdc
+
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
+
++Introduced in NLog 4.7.7
+
true.++Introduced in NLog 4.4.7
+
1 (0 = No object reflection)++Introduced in NLog 4.5. Before NLog 5.0 the default was
+0(No object reflection)
/ will be converted to \/. Default = false.++Introduced in NLog 4.6.8. Before NLog 5.0 the default was
+true
IncludeEventProperties for compact Json-documents. Default = false.++Introduced in NLog 6.1
+
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
+ }
+};
+
+<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!"
+ }
+}
+
+
+ Layout renderers are template macros that are used in Layouts, e.g. ${message}, ${level} etc
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}
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.
+ +See Layouts
+ +A specialized layout that supports header and footer.
+++Platforms Supported: All
+
<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>
+
+NLog Layout allows converting a LogEvent into a formatted string, which is highly customizable. The most common used Layout-type is the SimpleLayout which allows one to combine one or many LayoutRenderers to generate customized output.
+The default Layout for NLog Target is this:
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}
+
+Many more LayoutRenderers can be found here: https://nlog-project.org/config/?tab=layout-renderers
+NLog Layout-format recognizes the colon-character : as option-delimiter, but only when used inside ${ and }. To avoid unexpected results, then one can escape using back-slash like this: \:. Ex. ${date:format=HH\:mm\:ss}
Besides SimpleLayout there also exists JsonLayout, XmlLayout, CsvLayout, etc. These are optimized for generating log-output that conforms to the expected dataformat. See also: https://nlog-project.org/config/?tab=layouts
NLog Layout are often used (and it is also encouraged) as datatype for NLog Target configuration properties. Forexample the NLog FileTarget has FileName-property. This enables use of LayoutRenderers for specifying relative directory-path, or to find specifc log-directory-path from configuration-files (Ex. ${appsetting} or ${configsetting})
+This allows one to keep environment specific configuration away from the pure NLog-configuration, and it instead lookup settings from deployed configuration-files or machine environment-variables using NLog LayoutRenderers.
+Example ${configsetting:Options.ConnectionString} can lookup value from appsettings.json:
{
+ "Options":{
+ "ConnectionString":"UseDevelopmentStorage=true",
+ }
+}
+
+NLog 5.0 introduces Layout<T> that makes it even easier to use NLog Layout for configuration-options. Before one usually had to do this:
int eventId = 0;
+string renderEventId = EventIdLayout.Render(logEvent);
+if (string.IsNullOrEmpty(renderEventId) || !int.TryParse(renderEventId, out eventId))
+{
+ eventId = 42; // fallback default value
+}
+
+Now with Layout<int> then one can do this:
int eventId = EventIdLayout.RenderValue(logEvent, defaultValue: 42);
+
+An example of a simple layout looks like:
+layout="${machinename} ${message}"
+
+This layout is used in the NLog.config file like:
+<?xml version="1.0" encoding="utf-8" ?>
+<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd">
+
+ <targets>
+ <target name="console" xsi:type="ColoredConsole"
+ layout="${machinename} ${message}"/>
+ </targets>
+
+ <rules>
+ <logger name="*" minlevel="Trace" writeTo="console" />
+ </rules>
+</nlog>
+
+
+ Left part of a text.
+++Platforms Supported: All
+Introduced in NLog 4.6
+
Related:
+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.
+The log level.
+++Platforms Supported: All
+
${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}
+
+false++Introduced with NLog v5.0 to simplify default Layout, instead of using the ambient uppercase-property
+
| 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 | +
Configuration:
+${level}
+
+Code:
+logger.Debug("Test Message")
+
+Result:
+Debug
+
+Configuration:
+${level:format=FirstCharacter}
+
+Code:
+logger.Debug("Test Message")
+
+Result:
+D
+
+
+ Limits the number of logs written to the wrapped target in a given time interval.
+++Platforms Supported: All
+Introduced in NLog 4.4.
+
<targets>
+ <target xsi:type="LimitingWrapper"
+ name="String"
+ messageLimit="Integer"
+ interval="TimeSpan">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+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)
A string literal.
+++Platforms Supported: All
+
${literal:text=String}
+
+This is used to escape '${' sequence as ;${literal:text=${}'.
Configuration:
+${literal:text=Some Text with ${ in it}
+
+Code:
+logger.Debug("Test Message")
+
+Result:
+Some Text with ${ in it
+
+
+ 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
+
${local-ip:addressFamily=InterNetwork}
+
+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}
+
+
+ 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.
+${log4jxmlevent:includeEventProperties=Boolean:includeSourceInfo=Boolean:includeCallSite=Boolean
+ :includeNdc=Boolean:ndcItemSeparator=String:appInfo=String:indentXml=Boolean}
+
+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.
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.
+<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.
+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:
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:
+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:
+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:
+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.
+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):
+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
+
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.
+<?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>
+
+
+ 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.
+<targets>
+ <target xsi:type="SomeTarget">
+ <layout xsi:type="Log4JXmlEventLayout" includeEventProperties="true">
+ <parameter name="processId" value="${processid}" /> <!-- Repeated -->
+ </layout>
+ </target>
+</targets>
+
+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.
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
+
Moved to https://github.com/NLog/NLog/wiki/Context
+ +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
+
<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.
+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.
useBinaryEncoding - Indicates whether to use binary message encoding. Boolean
+parameters - The list of parameters. Collection
+Each collection item is represented by \
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
+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.
+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);
+ }
+ }
+ }
+}
+
+
+ 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
+
${logger:shortName=Boolean}
+
+++Introduced with NLog v5.3
+
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.
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:
<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>
+
+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.
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
+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>
+
+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.
When no log output is produced, the issue may originate in NLog configuration, the application, or the runtime environment. Common causes include:
+NLog.config has:NLog.LogManager.Shutdown() during application shutdown to flush pending events.NLog.config).These steps help isolate the problem area: +configuration loading → initialization → rule matching → target writing → application execution
+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.
NLog.config has:nlog.config (all lowercase as case-sensitive)Web.config or App.config and override logging configurationNLog 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>
+
+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>
+
+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();
+ }
+}
+
+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:
+NLog.LogManager.Shutdown().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();
+ }
+}
+
+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".
+Focus on observable behavior:
+Answering these typically identifies the failing component quickly.
+ +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.
+
${longdate:universalTime=Boolean}
+
+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)
Converts the result of another layout output to lower case.
+++Platforms Supported: All
+
${lowercase:lowercase=Boolean:inner=Layout:culture=Culture}
+
+or by using ambient property to modify output of other layout renderer:
+${other:lowercase=Boolean}
+
+${lowercase:${level}}
+${lowercase:Inner=${level}}
+${level:lowercase=true}
+
+
+ ++⚠️ 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
+Objecttype, not justString)
MDC is considered legacy, and instead is recommended to use MDLC that includes support for async Tasks. See also NLog Context
+${mdc:item=String}
+
+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}
+
+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}
+
+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
+
+When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.
++⚠️ 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
+Objecttype, not justString)
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.
+${mdlc:item=String}
+
+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}
+
+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
+
+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");
+}
+
+
+
+ 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
+
<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.
+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
+truetofalsewith 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
+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
+SingleTransactionwith NLog.MSMQ ver. 5.3, that should support transactional queues.
The NetBIOS Machine name that the process is running on.
+++Platforms Supported: All
+
${machinename}
+
+NetBIOS name is limited to MAX_COMPUTERNAME_LENGTH which is 15 for Windows.
+${hostname} has support for the full DNS-name.
+ +Sends log messages by email using SMTP protocol.
+++Platforms Supported: All - Requires nuget-package NLog.Targets.Mail since NLog v6, or alternative MailKit
+
<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.
+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
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
NonUrgent / Low , Normal , Urgent / High (Supports MimeKit.MessagePriority)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:
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:
+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:
+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
+
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.MailKitor 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
+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.
+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 <john.doe@example.com>
<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" />
+
+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>
+
+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>
+
+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>
+
+
+ Writes log messages to an ArrayList in memory for programmatic retrieval.
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="Memory" name="String" layout="Layout" />
+</targets>
+
+Read more about using the Configuration File.
+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
+
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
+var target = LogManager.Configuration.FindTargetByName<MemoryTarget>("target1");
+var logEvents = target.Logs;
+
+
+ The formatted log message.
+++Platforms Supported: All
+
${message:exceptionSeparator=String:withException=Boolean:raw=Boolean}
+
+++Introduced with NLog 4.5
+
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}
Page move to MessageBoxTarget - NLog/NLog.Windows.Forms
+ +Calls the specified static method on each log message and passes contextual parameters to it.
+++Platforms Supported: All
+
<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.
+public and static."NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests"<parameter /> element with the following attributes:Note: Since NLog 4.3 these parameters can be optional.
+++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");
+ }
+}
+
+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 \
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.
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");
+ }
+}
+
+
+ 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}" } }
+
+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
+
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.
+
+(null) means skip timestamp. Can be any argument accepted by DateTime.ToString(format).++Introduced with NLog.Extensions.Logging ver. 5.0
+
false.++Introduced with NLog.Extensions.Logging ver. 5.0
+
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.
+LayoutLayoutLayoutvar 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");
+
+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");
+}
+
+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");
+
+
+ ++⚠️ 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
+${ndc:bottomFrames=Integer:topFrames=Integer:separator=String}
+
+-1 is no limit. Integer. Default -1.-1 is no limit. Integer. Default -1string. Default (space)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()
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
++⚠️ 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.
+${ndlc:bottomFrames=Integer:topFrames=Integer:separator=String}
+
+-1 is no limit. Integer. Default -1.-1 is no limit. Integer. Default -1string. Default (space)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();
+ }
+}
+
+
+ Standard install
+NLog.config xml-fileNLog.config.That's it, you can now compile and run your application and it will be able to use NLog.
+Next step, see Tutorial
+If something is not working as expected then check here: +* Troubleshooting Configuration +* Troubleshooting Logging +* Check Internal Logging +* FAQ +* External articles and tutorials
+ +Captures output from System Diagnostics Trace and redirects to NLog Targets.
+++Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6
+
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>
+
+System.Diagnostics.Trace.Listeners.Clear();
+System.Diagnostics.Trace.Listeners.Add(new NLog.NLogTraceListener { Name = "NLog" });
+System.Diagnostics.Trace.WriteLine("Hello World");
+
+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>
+
+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.
+ +Save this file as "nlog.config" in the root of your application (Add to project with 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">
+ 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>
+
+```xml
+ +<!-- 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>
+
+
+The directory where NLog.dll is located.
+++Platforms Supported: All
+
${nlogdir:dir=String:file=String}
+
+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
+<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.
+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:
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:
+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:
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
+16with NLog v4.5 (Before0)
onConnectionOverflow - Action that should be taken if the will be more connections than maxConnections.
+++Introduced with NLog v4.2.1. Default became
+Blockwith NLog v4.5 (BeforeAllowNewConnnection)
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
+
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.
+<?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>
+
+
+ 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.
+${ndlctiming:currentScope=Boolean:scopeBeginTime=Boolean:format=String}
+
+Boolean. Default False.Boolean. Default FalseTimeSpan.ToString(format). string. Default nullSends 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.
+<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.
+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:
None - No end of line characters.
+compress - Use compression to reduce message size. Default: None
++Introduced with NLog 5.0
+
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:
+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
+
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
+
A newline literal.
+++Platforms Supported: All
+
${newline}
+
+
+ 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.
${date:format=yyyy-MM-dd:norawvalue=true}
+
+
+ Discards log messages. Used mainly for debugging and benchmarking.
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="Null" name="String" formatMessage="Boolean" layout="Layout" />
+</targets>
+
+Read more about using the Configuration File.
+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}
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>
+
+
+ Render a property of an object.
+Introducted in NLog 4.6.7
+++Platforms Supported: All
+
${object-path:${exception}:path=String:Format=String:Culture=String}
+${exception:objectpath=String} // Ambient way
+
+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
+
+
+ Only outputs the inner layout when exception has been defined for log message.
+++Platforms Supported: All
+
${onexception:inner=Layout}
+
+Only outputs the inner layout when event properties from structured logging are included with the logevent.
+++Platforms Supported: All
+Introduced with NLog 4.7
+
${onHasProperties:inner=Layout}
+
+${onHasProperties:, Properties\: ${all-event-properties}}
+
+
+ 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
+
<targets>
+ <target xsi:type="OutputDebugString" name="String" layout="Layout" />
+</targets>
+
+Read more about using the Configuration File.
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}++Introduced with NLog 5.0
+
++Introduced with NLog 5.0
+
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
Applies padding to another layout output.
+++Platforms Supported: All
+
${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}
+
+Char Default: (space character)IntegerBoolean Default: FalseLayoutfixedLength=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: LeftPerformanceCounterTarget updates specified Windows Performance Counter on each write.
+++Platforms Supported: Limited - Windows only and requires nuget-package NLog.PerformanceCounter since NLog 5.0
+
<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.
+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:
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
+
Alternative one can use NLog.ETW for writing to ETW EventCounter using EtwEventCounter-Target.
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.
+When using the NLog Logger, then there are some things that affects optimal performance:
+LogManager.GetLogger() and LogManager.GetCurrentClassLogger(), instead use static readonly variables.string.format and string interpolation (Ex $"Hello {world}") but pass the arguments to the log method.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.
+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}.
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.
+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.
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 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
+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.
+ +Render value retrieved from Windows Performance Counter.
+++Platforms Supported: Limited - Windows only and requires nuget-package NLog.PerformanceCounter since NLog 5.0
+
${performancecounter:Category=String:Counter=PerformanceCounterType:Instance=String
+ :IncrementValue=Integer:MachineName:string
+ format=String:culture=Culture}
+
+++NLog 4.6 will automatically use current process as Instance-Id when
+Category= "Process" (Supports multi-instance)
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
+
The platform support is now integrated with the config options list.
+See https://nlog-project.org/config/
+screenshot:
+
Filters buffered log entries based on a set of conditions that are evaluated on a group of events.
+++Platforms Supported: All
+
<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>
+
+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 >= LogLevel.Info">
+ <target xsi:type="File" fileName="${basedir}/file.txt" />
+ <when exists="level >= LogLevel.Warn" filter="level >= LogLevel.Debug"/>
+ </target>
+ </target>
+</targets>
+
+
+ The current process executable directory of the application.
+++Platforms Supported: All
+Introduced in NLog v4.7.1.
+See also ${basedir}, ${specialfolder}, ${currentdir}, ${tempdir}
+
${processdir:dir=String:file=String}
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.
+This is the same as using ${basedir:processDir=true}.
See also: FileTarget FileName Directory
+ +The identifier of the current process.
+++Platforms Supported: All
+
${processid}
+
+
+ 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}
${processinfo:property=Enum:format=string}
+
+WorkingSet64 - Working Set Size (64-bit)
+format formatstring in the value is formatable. Ex. formatting process StartTime. Introduced in NLog 4.4
+The start time of the current process.
+++Platforms Supported: All
+Introduced with NLog v6.2
+
${processstart:Format=String:UniversalTime=Boolean}
+
+ToString(...) Format specifier. Default = yyyy-MM-dd HH:mm:ssFalse.Invariant.The name of the current process.
+++Platforms Supported: All
+
${processname:fullName=Boolean}
+
+The process lifetime in short sortable format HH:mm:ss.fff.
++Platforms Supported: All
+See also ${time}, ${date}, ${longdate}, ${shortdate}
+
${processtime:invariant=Boolean}
+
+++Introduced with NLog 4.5.2
+
++Introduced with NLog 5.0
+
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)
Custom Targets, layout etc. could have properties. When configuring from the XML config, there are some limitations on the types.
+Supported types for Targets, Layouts and Layout renderers:
+EncodingCultureInfoTypeLineEndingMode UriLayout, SimpleLayout & ConditionExpressionstringTypeDescriptor from stringIntroduced 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>
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
+ +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)
+
${qpc:normalize=Boolean:difference=Boolean:alignDecimalPoint=Boolean
+ :precision=Integer:seconds=Boolean}
+
+Sends log messages to a randomly selected target.
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="RandomizeGroup" name="String">
+ <target xsi:type="wrappedTargetType" ... />
+ <target xsi:type="wrappedTargetType" ... />
+ ...
+ <target xsi:type="wrappedTargetType" ... />
+ </target>
+</targets>
+
+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.
+${regex-replace:searchFor=String:wholeWords=Boolean:replaceWith=String
+ :ignoreCase=Boolean:inner=Layout}
+
+StringBoolean Default: FalseBoolean Default: False(?<groupname>subexpression)true can improve regex performance, but costs memory. Boolean Default: FalseReplace sensitive data, that starts with password= or password:
<variable name="replacePasswords"
+ value="${regex-replace:inner=${message}:searchFor=(?i)(?<=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)
+ +NLog extensions must be registered before they can be used in NLog configuration. This can be done in different ways:
+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()
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>
+
+Include your assembly with the <extensions> syntax. Use the assembly name (not the filename)
<nlog>
+ <extensions>
+ <add assembly="MyAssemblyName"/>
+ </extensions>
+
+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.
+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
+
+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));
+
+
+
+⚠️ 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.
+ +A value from the Registry.
+++Platforms Supported: Limited - Windows only and requires nuget-package NLog.WindowsRegistry since NLog 5.0
+
${registry:value=Layout:key=Layout:defaultValue=Layout:view=enum:requireEscapingSlashesInDefaultValue=boolean}
+
+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.
boolean. Require escaping backward slashes in DefaultValue. Need to be backwardscompatible. Default true. Will be removed in the future. 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.
+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.
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
+
+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.
+ +Repeats each log event the specified number of times.
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="RepeatingWrapper" name="String" repeatCount="Integer">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+Replaces a string in the output of another layout with another string.
+++Platforms Supported: All
+
${replace:searchFor=String:wholeWords=Boolean:replaceWith=String
+ :ignoreCase=Boolean:inner=Layout}
+
+StringBoolean Default: FalseBoolean Default: FalseNLog v6 does not support Regular Expressions (RegEx), and have removed these options:
+Boolean Default: False(?<groupname>subexpression)++Introduced with NLog 3.1
+
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.
+Replace sensitive data, that starts with password= or password:
<variable name="replacePasswords"
+ value="${replace:inner=${message}:searchFor=(?i)(?<=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)
+ +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}
+
${replace-newlines:inner=Layout:replacement=String}
" " (space)logger.Info("foo {0}", "bar" + System.Environment.NewLine + "123");
+
+${replace-newlines:${message}}
+
+Will result in "foo bar 123"
+${replace-newlines:replacement=|:${message}}
+
+Will result in "foo bar|123"
+ +Retries in case of write error.
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="RetryingWrapper" name="String" retryDelayMilliseconds="Integer" retryCount="Integer">
+ <target xsi:type="wrappedTargetType" ...target properties... />
+ </target>
+</targets>
+
+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
+
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:
+Page moved to RichTextBoxTarget - NLog.Windows.Forms
+ +Right part of a text
+++Platforms Supported: All
+Introduced in NLog 4.6
+
Related:
+${right:inner=Layout:length=Integer}
+
+Read more about using the Configuration File.
+Decodes text "encrypted" with ROT-13.
+++Platforms Supported: All
+
${rot13:inner=Layout:text=Layout}
+
+inner - Wrapped layout. Layout
+text - Layout to be wrapped. Layout
+This variable is for backwards compatibility
See https://en.wikipedia.org/wiki/ROT13.
+ +Distributes log events to targets in a round-robin fashion.
+++Platforms Supported: All
+
<targets>
+ <target xsi:type="RoundRobinGroup" name="String">
+ <target xsi:type="wrappedTargetType" ... />
+ <target xsi:type="wrappedTargetType" ... />
+ ...
+ <target xsi:type="wrappedTargetType" ... />
+ </target>
+</targets>
+
+Information about Silverlight application.
+Supported in Silverlight (Deprecated with NLog 5.0)
+${sl-appinfo:option=Enum}
+
+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.
+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.
+${scopeindent:indent=Layout}
+
+Layout. Default (double space)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();
+ }
+}
+
+
+ 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}
+${scopenested:bottomFrames=Integer:topFrames=Integer:separator=String}
+
+-1 is no limit. Integer. Default -1.-1 is no limit. Integer. Default -1string. Default (space)@ for Json-Array.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"))
+{
+}
+
+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");
+}
+
+Indent log-messages based on how many nested levels in ScopeContext using ${scopeindent}
+${scopeindent}${message}
+
+
+ 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}
+${scopeproperty:item=String}
+
+@ for Json.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
+}
+
+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
+}
+
+When ScopeContext Property cannot be found (or has blank value), then one use whenEmpty to specify fallback value:
+${scope-property:UserId:whenEmpty=42}
+
+
+ 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}
+${scopetiming:currentScope=Boolean:StartTime=Boolean:format=String}
+
+Boolean. Default False.Boolean. Default FalseTimeSpan.ToString(format). string. Default nullThe 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}
+${sequenceid}
+
+
+ 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.
+
${shortdate:universalTime=Boolean}
+
+Represents a string with embedded placeholders that can render contextual information from the LogEvent.
+++Platforms Supported: All
+
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>
+
+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
+ +System special folder path (includes My Documents, My Music, Program Files, Desktop, and more).
+++Platforms Supported: All
+See also ${processdir} , ${basedir} , ${currentdir} , ${tempdir}
+
${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"C:/ProgramData/AppName/logfile.txtfolder - 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
+C:\Users\%USERNAME%\AppData\Roaming$HOME/.config (or $XDG_CONFIG_HOME if set)/data/Containers/Data/Application/@GENERATED_NAME@/Documents/.config/data/data/@PACKAGE_NAME@/files/.configC:\Users\%USERNAME%\AppData\Local$HOME/.local/share (or $XDG_DATA_HOME if set)/data/Containers/Data/Application/@GENERATED_NAME@/Documents/data/data/@PACKAGE_NAME@/files/.local/shareC:\ProgramData/usr/share/usr/share/usr/shareC:\Users\%USERNAME%\Documents$HOME/data/Containers/Data/Application/@GENERATED_NAME@/Documents/data/data/@PACKAGE_NAME@/filesC:\Users\%USERNAME%\Desktop$HOME/Desktop (or $XDG_DESKTOP_DIR if set)/data/Containers/Data/Application/@GENERATED_NAME@/Documents/Desktop/data/data/@PACKAGE_NAME@/files/DesktopC:\Users\%USERNAME%$HOME/data/Containers/Data/Application/@GENERATED_NAME@/data/data/@PACKAGE_NAME@/filesC:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Templates$HOME/Templates (or $XDG_TEMPLATES_DIR if set)/data/Containers/Data/Application/@GENERATED_NAME@/Documents/Templates/data/data/@PACKAGE_NAME@/files/TemplatesC:\ProgramData\Microsoft\Windows\Templates/usr/share/templates/usr/share/templates/usr/share/templatesC:\WINDOWS\resources/LibraryWrites log events to all wrapped targets.
+++Platforms Supported: All
+
ℹ️ For better performance, specify targets directly on the logging rule, optionally using NLog variables.
+<targets>
+ <target xsi:type="SplitGroup" name="String">
+ <target xsi:type="wrappedTargetType" ... />
+ <target xsi:type="wrappedTargetType" ... />
+ ...
+ <target xsi:type="wrappedTargetType" ... />
+ </target>
+</targets>
+
+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.
+<targets>
+ <target xsi:type="Splunk"
+ name="String"
+ address="Layout">
+ <splunkField name="String" layout="Layout" /><!-- repeated -->
+ </target>
+</targets>
+
+Read more about using the Configuration File.
+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
+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:
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:
+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.
+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):
+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
+
<?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>
+
+
+ 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>
+
+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
+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>
Render Stack trace of a log event.
+++Platforms Supported: All
+
${stacktrace:format=Enum:topFrames=Integer:skipFrames=Integer:separator=String}
+
+ ++Introduced with NLog 4.7.1
+
false++Introduced with NLog 5.0
+
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
+
+Program.Main
+Program.TestLogging
+NLogLoggerHelper.LogEvent
+
+[Int32 Main()]
+[Void TestLogging()]
+[Void WriteToLog(NLog.Logger, NLog.LogLevel, System.String)]
+
+
+ Substring the result
+++Platforms Supported: All
+Introduced in NLog 4.6
+
Related:
+ +${substring:inner=Layout:length=Integer:start=Integer}
+
+Read more about using the Configuration File.
+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.
+<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.
+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
+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:
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:
+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.
+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):
+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
+
<?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>
+
+
+ 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>
+
+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
+Moved to Targets
+ +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.
+List of NLog targets can found here: https://nlog-project.org/config/?tab=targets
+ +NLog can be extended with custom new targets. For more information, see: Extending-NLog
+ +The temporary directory on the local machine.
+++Platforms Supported: All
+See also ${basedir}, ${processdir}, ${specialfolder}, ${currentdir}
+
${tempdir:dir=String:file=String}
+
+Page moved here: https://github.com/NLog/NLog/wiki/SimpleLayout
+ +The identifier of the current thread.
+++Platforms Supported: All
+
${threadid}
+
+
+ The name of the current thread.
+++Platforms Supported: All
+
${threadname}
+
+
+ The Ticks value of current date and time.
+++Platforms Supported: All
+
${ticks}
+
+
+ The time in a 24-hour, sortable format HH:mm:ss.ffff.
++Platforms Supported: All
+See also ${processtime}, ${date}, ${longdate}, ${shortdate}
+
${time:universalTime=Boolean:invariant=Boolean}
+
+++Introduced with NLog 4.5.2
+
++Introduced with NLog 5.0
+
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)
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:
+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>
+
+The time source can be configured by inserting the following before any log +messages are printed:
+NLog.Time.TimeSource.Current = new NLog.Time.AccurateUtcTimeSource();
+
+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.
+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>
+
+
+ Page moved to ToolStripItemTarget - NLog.Windows.Forms
+ +Logs produced by NLog can be analyzed using a number of GUI tools:
+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
+ +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.
+
${activityid}
+
+++⚠️ 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.
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.
Sends log messages through System.Diagnostics.Trace.
+++Platforms Supported: All - Requires nuget-package NLog.Targets.Trace since NLog v6
+
<targets>
+ <target xsi:type="Trace" name="String" layout="Layout" />
+</targets>
+
+${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}Trace.WriteLine independent of LogLevel. Default: False++Introduced with NLog 4.5, fixes the issue with output being prefixed with exe-filename.
+
Trace.Fail for LogLevel.Fatal, instead of Trace.Error. Default: False++Introduced with NLog 4.7, avoids
+Enviroment.FailFastthat can happen for default trace listener.
++Introduced with NLog 5.0
+
++Introduced with NLog 5.0
+
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
Trims the whitespace from the result of another layout renderer.
+++Platforms Supported: All
+
${trim-whitespace:trimWhiteSpace=Boolean:inner=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:trimWhiteSpace=Boolean}
+
+NLog can be setup with the following steps:
+ +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.
+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.
+ +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.
+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
+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.
+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();
+ }
+}
+
+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");
+
+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");
+}
+
+NLog.configNLog 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.
+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.
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.
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.
+ +Converts the result of another layout output to upper case.
+++Platforms Supported: All
+
${uppercase:uppercase=Boolean:inner=Layout:culture=Culture}
+
+or by using ambient property to modify output of other layout renderer:
+${other:uppercase=Boolean}
+
+true with Inner, required when using as ambient.${uppercase:${level}}
+${uppercase:Inner=${level}}
+${level:uppercase=true}
+
+
+ Encodes the result of another layout output for use with URLs.
+++Platforms Supported: All
+
${url-encode:spaceAsPlus=Boolean:inner=Layout}
+
+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.
+
${var:name=String:default=String}
+
+null<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>
+
+// create or edit
+LogManager.Configuration.Variables["user"] = "admin";
+LogManager.Configuration.Variables["password"] = "123";
+// or remove
+LogManager.Configuration.Variables.Remove("password");
+
+${var:password:default=unknown}<variable> is optional if no default is neededautoReload="true", unless also using keepVariablesOnReload="true" (Before NLog 5.0 then keepVariablesOnReload was default false)NLog integrates with Visual Studio®
+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"/>
+
+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.
+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).
+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();
+
+
+ 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.
+layout - The layout value of the W3C Extended Field
+directive
+Available W3C log-parsers:
+See also: Extending-NLog
+See also: Who Is Using NLog
+ +++⚠️ NLog 5.0 now supports Layout for the
+Url-parameter, so this work-around is no longer needed.
*a target configured as in: https://github.com/NLog/NLog/wiki/Webservice-Target-for-Splunk
+<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>
+
+<?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>
+
+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();
+//...
+
+
+ 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.
+<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>
+
+<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
<header> defines a single Http-header to be included in Http Request:
++NLog 4.6 allows override of Http-header
+SoapActionfor ProtocolSoap11
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:
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:
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)
+The web service must implement a method that accepts a number of string parameters.
+<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>
+
+
+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
+ }
+}
+
+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>
+
+
+ <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>
+
+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.
+ +Filter events in the config.
+++Platforms Supported: All
+
<rules>
+ <logger ... >
+ <filters defaultAction="Neutral | Ignore | Log | LogFinal | IgnoreFinal">
+ <when condition="Condition" action="Enum"/>
+ </filters>
+ </logger>
+</rules>
+
+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
+
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 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.
message - LogEvent formatted messagelogger - Logger namelevel - LogLevel objectexception - Exception object (Introduced with NLog 5.0)${layout} - All available layout-options (except stacktrace).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.
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 thanlength('s') > 0, and reduces memory allocation. +*starts-with(s1,s2)Determines whether the second string is a prefix of the first one. Returns:truewhen the second string is a prefix of the first string,falseotherwise. +*regex-matches(input, pattern, options)Introduced in NLog 4.5. Indicates whether the regular expressionpatternfinds a match in the specifiedinputstring.optionsis an optional comma separated list of values from the RegexOptions enumeration.
+Returns :truewhen a match is found in the input string,falseotherwise.
+Example :regex-matches('${message}', '^foo$', 'ignorecase,singleline')
Single quotes should be escaped with another single quote. +Example:
+contains('${message}', 'Cannot insert the value NULL into column ''Col1')
+
+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>
+
+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, '"Bob"')" action="Ignore" /> <!-- "Bob" -->
+ </filters>
+ </logger>
+</rules>
+
+
+ Only outputs the inner layout when the specified condition has been met. See Conditions.
+++Platforms Supported: All
+
${when:when=Condition:inner=Layout:else=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:when=Condition}
+
+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}} +```
+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 layoutWorking 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\}}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
+ +Matches when the calculated layout contains the specified substring. This filter is deprecated in favour of \
++Platforms Supported: All
+
<rules>
+ <logger ... >
+ <filters>
+ <whenContains layout="Layout" substring="String" action="Enum" ignoreCase="Boolean"/>
+ </filters>
+ </logger>
+</rules>
+
+Outputs alternative layout when the inner layout produces empty result.
+++Platforms Supported: All
+
${whenEmpty:whenEmpty=Layout:inner=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:whenEmpty=Layout}
+
+Matches when the calculated layout is equal to the specified substring. This filter is deprecated in favour of \
++Platforms Supported: All
+
<rules>
+ <logger ... >
+ <filters>
+ <whenEqual ignoreCase="Boolean" layout="Layout" action="Enum" compareTo="String"/>
+ </filters>
+ </logger>
+</rules>
+
+Matches when the calculated layout does NOT contain the specified substring. This filter is deprecated in favour of \
++Platforms Supported: All
+
<rules>
+ <logger ... >
+ <filters>
+ <whenNotContains layout="Layout" substring="String" action="Enum" ignoreCase="Boolean"/>
+ </filters>
+ </logger>
+</rules>
+
+Matches when the calculated layout is NOT equal to the specified substring. This filter is deprecated in favour of \
++Platforms Supported: All
+
<rules>
+ <logger ... >
+ <filters>
+ <whenNotEqual ignoreCase="Boolean" layout="Layout" action="Enum" compareTo="String"/>
+ </filters>
+ </logger>
+</rules>
+
+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
+<rules>
+ <logger ... >
+ <filters defaultAction="Log">
+ <whenRepeated layout="Layout" timeoutSeconds="30" action="Ignore" />
+ </filters>
+ </logger>
+</rules>
+
+Can also be combined with FilteringWrapper-target.
+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).
+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/
+See also: Articles and tutorials about NLog
+ +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
+
${windows-identity:userName=Boolean:domain=Boolean}
+
+${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.
+Wraps the result of another layout output at specified line length.
+++Platforms Supported: All
+Introduced in NLog 4.3.4
+
${wrapline=Integer:inner=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:wrapline=Integer}
+
+${wrapline:${message}}
+${wrapline:Inner=${message}:WrapLine=80}
+${message:wrapline=80}
+
+
+
+ Example with a <include /> and <variable /> in the XML 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>
+
+
+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>
+
+
+
+ Converts the result of another layout output to be XML-compliant.
+++Platforms Supported: All
+
${xml-encode:xmlEncode=Boolean:inner=Layout}
+
+or by using ambient property to modify output of other layout renderer:
+${other:xmlEncode=Boolean}
+
+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>
+
+logeventLayoutElementEncode - 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
+
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
IList-collections items<element> defines childs elements to render:
LayoutBoolean Default: True++Configuration parameters for Root can also be used for each
+<element>-element.
<attribute> defines the attributes to render:
Layout Required.Boolean Default: TrueBooleanXmlLayout
+<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>
+
+XmlLayout
+<layout xsi:type="XmlLayout" includeEventProperties="true">
+</layout>
+
+Xml Output
+<logevent>
+ <property key="PropertyName">PropertyValue</property>
+</logevent>
+
+XmlLayout
+<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesElementName="myparm">
+</layout>
+
+Xml Output
+<logevent>
+ <myparm key="PropertyName">PropertyValue</myparm>
+</logevent>
+
+XmlLayout
+<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesElementKeyAttribute="" propertiesElementName="{0}">
+</layout>
+
+Xml Output
+<logevent>
+ <PropertyName>PropertyValue</PropertyName>
+</logevent>
+
+XmlLayout
+<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesElementValueAttribute="value">
+</layout>
+
+Xml Output
+<logevent>
+ <property key="PropertyName" value="PropertyValue"/>
+</logevent>
+
+XmlLayout
+<layout xsi:type="XmlLayout" includeEventProperties="true">
+</layout>
+
+Xml Output
+<logevent>
+ <property key="PropertyName"><property key="DictionaryKey">DictionaryValue</property></property>
+</logevent>
+
+XmlLayout
+<layout xsi:type="XmlLayout" includeEventProperties="true">
+</layout>
+
+Xml Output
+<logevent>
+ <property key="PropertyName"><item>ListValue1</item><item>ListValue2</item></property>
+</logevent>
+
+XmlLayout
+<layout xsi:type="XmlLayout" includeEventProperties="true" propertiesCollectionItemName="element">
+</layout>
+
+Xml Output
+<logevent>
+ <property key="PropertyName"><element>ListValue1</element><element>ListValue2</element></property>
+</logevent>
+
+
+ See https://github.com/NLog/NLog/wiki/Filtering-log-messages
+ +' + escapeHtml(summary) +'
' + 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