简体   繁体   English

NLog 目标中的 HttpClient

[英]HttpClient in an NLog target

I need to create a Target that uses HttpClient.我需要创建一个使用 HttpClient 的目标。 HttpClient does not contain any synchronous methods, they are all Task returning Async calls. HttpClient 不包含任何同步方法,它们都是 Task 返回 Async 调用。 What is the best way to use this in an NLog target, seeing as the api does not seem to be async/await aware?在 NLog 目标中使用它的最佳方法是什么,因为 api 似乎没有 async/await 意识?

If you want to make things simple then you can just do a Wait() on the async-task.如果您想让事情变得简单,那么您可以在异步任务上执行 Wait() 。 Then just wrap your custom-target using the AsyncTargetWrapper.然后只需使用 AsyncTargetWrapper 包装您的自定义目标。 Then you also don't have to worry about having too many active http-requests.然后你也不必担心有太多的活动 http-requests。

But NLog has no issue with targets that performs deferred log write-operations.但是 NLog 对于执行延迟日志写入操作的目标没有问题。 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)唯一需要的合同是在延迟的日志写入操作最终完成后调用与 LogEventInfo 一起提供的 async-continuation(也许查看 NetworkTarget 以获得一些灵感)

Update NLog 4.6更新 NLog 4.6

NLog 4.6 introduces AsyncTaskTarget that ensures correct ordering, and also makes it easy to perform batching. NLog 4.6 引入了AsyncTaskTarget以确保正确的排序,并且还可以轻松执行批处理。

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或者从这个 PR 中窃取代码: https ://github.com/NLog/NLog/pull/2006

I have implemented httpclient with aysnc-wrapper target.我已经用 aysnc-wrapper 目标实现了 httpclient。 You can install and use it from nuget package https://www.nuget.org/packages/NLog.HttpClient您可以从 nuget 包https://www.nuget.org/packages/NLog.HttpClient安装和使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM