- Notifications
You must be signed in to change notification settings - Fork1.4k
How to write a custom async target
Introduced with NLog 4.6
It is really easy:
- Create a class that inherits from
NLog.Targets.AsyncTaskTarget
- Override the
WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
method. - In the body of this method invoke
this.RenderLogEvent(this.Layout, logEvent)
to get the message text, and invokethis.GetAllProperties(logEvent)
to get structured properties.
usingNLog;usingNLog.Config;usingNLog.Targets;namespaceMyNamespace{[Target("MyFirst")]publicsealedclassMyFirstTarget:AsyncTaskTarget{publicMyFirstTarget(){this.IncludeEventProperties=true;// Include LogEvent Properties by default}publicLayoutHost{get;set;}="localhost";protectedoverrideTaskWriteAsyncTask(LogEventInfologEvent,CancellationTokentoken){stringlogMessage=this.RenderLogEvent(this.Layout,logEvent);stringhostName=this.RenderLogEvent(this.Host,logEvent);IDictionary<string,object>logProperties=this.GetAllProperties(logEvent);returnSendTheMessageToRemoteHost(hostName,logMessage,logProperties);}privateasyncTaskSendTheMessageToRemoteHost(stringhostName,stringmessage,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. TheOverflowAction
will then take over (Default =Discard
to avoid eating all memory).
There are several options:
- TaskTimeoutSeconds - How many seconds a Task is allowed to run before it is cancelled (Default 150 secs)
- RetryDelayMilliseconds - How many milliseconds to wait before next retry (Default 500ms, and will be doubled on each retry).
- RetryCount - How many attempts to retry the same Task, before it is aborted (Default 0)
If wanting to have more control of when to retry (Checking theException
), or perform connection recovery on failure, then override this method:
protectedoverrideboolRetryFailedAsyncTask(Exceptionexception,CancellationTokencancellationToken,intretryCountRemaining,outTimeSpanretryDelay){returnbase.RetryFailedAsyncTask(exception,cancellationToken,retryCountRemaining,outretryDelay);// Default behavior}
Activated when overriding this method:
protectedoverrideTaskWriteAsyncTask(IList<LogEventInfo>logEvents,CancellationTokencancellationToken){// 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.
<targettype="MyFirst"name="first"includeEventProperties="true"> <contextpropertyname="MachineName"layout="${machinename}" /> <contextpropertyname="ThreadId"layout="${threadid}" /></target>
The structured properties can be retrieved insideWriteAsyncTask
-method by callingthis.GetAllProperties(logEvent)
.
-Troubleshooting Guide - See available NLog Targets and Layouts:https://nlog-project.org/config
- All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json