Introduced with NLog 4.6
It is really easy:
NLog.Targets.AsyncTaskTarget
WriteAsyncTask(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:
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)
.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4