Reputation: 33071
I need to create a Target that uses HttpClient. HttpClient does not contain any synchronous methods, they are all Task returning Async calls. What is the best way to use this in an NLog target, seeing as the api does not seem to be async/await aware?
Upvotes: 1
Views: 587
Reputation: 21
I have implemented httpclient with aysnc-wrapper target. You can install and use it from nuget package https://www.nuget.org/packages/NLog.HttpClient
Upvotes: 0
Reputation: 19867
Update NLog 4.6
NLog 4.6 introduces AsyncTaskTarget that ensures correct ordering, and also makes it easy to perform batching.
Old answer:
Maybe something like this should work:
public class CustomTarget : Target
{
protected override async void Write(NLog.Common.AsyncLogEventInfo logEvent)
{
try
{
await WriteAsync(logEvent.LogEvent).ConfigureAwait(false);
logEvent.Continuation(null);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Failed to sent message");
logEvent.Continuation(ex);
}
}
}
Or steal the code from this PR: https://github.com/NLog/NLog/pull/2006
Upvotes: 1
Reputation: 19867
If you want to make things simple then you can just do a Wait() on the async-task. Then just wrap your custom-target using the AsyncTargetWrapper. Then you also don't have to worry about having too many active http-requests.
But NLog has no issue with targets that performs deferred log write-operations. The only required contract is that the async-continuation provided together with the LogEventInfo is called after the deferred log-write-operation has finally completed (Maybe look at the NetworkTarget for for some inspiration)
Upvotes: 1