Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/NLogPublic

How to write a custom async target

Rolf Kristensen edited this pageMay 11, 2025 ·25 revisions

Introduced with NLog 4.6

It is really easy:

  • Create a class that inherits fromNLog.Targets.AsyncTaskTarget
  • Override theWriteAsyncTask(LogEventInfo logEvent, CancellationToken token) method.
  • In the body of this method invokethis.RenderLogEvent(this.Layout, logEvent) to get the message text, and invokethis.GetAllProperties(logEvent) to get structured properties.

⚠️ Don't forget toregister your custom component when loading NLog config!

Example

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 Features

AsyncTaskTarget has an internal queue (Initial capacity is 10000), so if the Tasks constantly performs timeout then at one point the queue will be filled. TheOverflowAction will then take over (Default =Discard to avoid eating all memory).

Timeout and Retry Logic

There are several options:

  • TaskTimeoutSeconds - How many seconds a Task is allowed to run before it is cancelled (Default 150 secs)
  • RetryDelayMilliseconds - How many milliseconds to wait before next retry (Default 500ms, and will be doubled on each retry).
  • RetryCount - How many attempts to retry the same Task, before it is aborted (Default 0)

If wanting to have more control of when to retry (Checking theException), or perform connection recovery on failure, then override this method:

protectedoverrideboolRetryFailedAsyncTask(Exceptionexception,CancellationTokencancellationToken,intretryCountRemaining,outTimeSpanretryDelay){returnbase.RetryFailedAsyncTask(exception,cancellationToken,retryCountRemaining,outretryDelay);// Default behavior}

Batch Logic

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).

TargetWithContext Features

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

Configuration

Programmatic Configuration

Advanced

Extending NLog

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp