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?
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