1

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?

Lies
  • 516
  • 6
  • 18
Dismissile
  • 32,564
  • 38
  • 174
  • 263

3 Answers3

1

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)

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
1

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

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
0

I have implemented httpclient with aysnc-wrapper target. You can install and use it from nuget package https://www.nuget.org/packages/NLog.HttpClient

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31958046) – spaleet Jun 09 '22 at 10:30