【问题标题】:Why can't I subscribe to HttpHandlerDiagnosticListener in a .NET Framework application为什么我不能在 .NET Framework 应用程序中订阅 HttpHandlerDiagnosticListener
【发布时间】:2022-01-03 13:25:40
【问题描述】:

我正在使用下面的代码来启用System.Net.Http.HttpClients 为每个传出的 HTTP 请求创建一个活动。这适用于面向 .NET Core 3.1 的 ASP.NET Core 应用程序,但不适用于面向 .NET Framework 4.7.2 的“经典”ASP.NET 应用程序。

// Using the Subscribe(IObservable<T>, Action<T>) extension method from the System.Reactive package
DiagnosticListener.AllListeners.Subscribe(listener =>
{
    if (listener.Name == "HttpHandlerDiagnosticListener")
    {
        listener.Subscribe(diagnostic =>
        {
            if (diagnostic.Key == "System.Net.Http.HttpRequestOut.Start")
            {
                // ...
            }
            else if (diagnostic.Key == "System.Net.Http.HttpRequestOut.Stop")
            {
                // ...
            }
        }
    }
}

我能想到的主要区别是 ASP.NET Core 应用程序使用 .NET Core 内置的 DiagnosticListener 类型,而“经典”ASP.NET 应用程序需要对 System 的包引用.Diagnostics.DiagnosticSource 使用该类型。

我尝试使用不同版本的 System.Diagnostics.DiagnosticSource 包(4.6.0、4.7.0、4.7.1、5.0.0 和 5.0.1),在每次升级/降级包后重建我的项目,但无济于事。

我找到了GitHub issue about a similar problem in Azure Functions (in-process) applications。他们提到降级到 System.Diagnostics.DiagnosticSource 4.7.0 作为一种解决方法,但在我的测试中不起作用。

【问题讨论】:

    标签: .net system.diagnostics


    【解决方案1】:

    the summary of the HttpHandlerDiagnosticListener in the System.Diagnostics.DiagnosticSource package找到答案:

    HttpHandlerDiagnosticListener 是 .NET 4.6 及更高版本的 DiagnosticListener,其中 HttpClient 没有内置的 DiagnosticListener。此类不用于 .NET Core,因为 .NET Core 中的 HttpClient 已经发出 DiagnosticSource 事件。此类弥补了 .NET 4.6 及更高版本中的缺陷。 HttpHandlerDiagnosticListener 没有公共构造函数。要使用它,应用程序只需要调用 DiagnosticListener.AllListeners 和 DiagnosticListener.AllListenerObservable.Subscribe(IObserver{DiagnosticListener}),然后在 IObserver{DiagnosticListener}.OnNext(DiagnosticListener) 方法中,当它看到 System.Net.Http 时。桌面源,订阅吧。这将触发此 DiagnosticListener 的初始化。

    所以我把我的代码改成了这样,它可以工作了:

    if (listener.Name == "System.Net.Http.Desktop")
    {
        listener.Subscribe(diagnostic =>
        {
            if (diagnostic.Key == "System.Net.Http.Desktop.HttpRequestOut.Start")
            {
                // ...
            }
            else if (diagnostic.Key == "System.Net.Http.Desktop.HttpRequestOut.Stop")
            {
                // ...
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      相关资源
      最近更新 更多