将最新版本的 Application Insight 与 .net 核心一起使用 API

Use latest version of Application Insight with .net core API

我在 .net core 3.0 中有一个现有的 API 项目,并且还使用异常中间件来记录异常。现在有一个要求,我们需要在 API 中实现应用程序洞察力。我浏览了很多链接,但了解到一些方法对于 app.UseApplicationInsightsExceptionTelemetry() and UseApplicationInsightsRequestTelemetry 这样的新版本已经过时了。即使我尝试在中间件的 catch 块中使用 TelemetryClient,但它已经过时了。那么,能否请您提供足够的信息,让我知道如何记录异常。下面是我需要将错误记录到应用程序洞察中的一些代码片段。

在您的启动程序中,在方法 public void ConfigureServices(IServiceCollection services) 中添加这样的应用程序见解:

services.AddApplicationInsightsTelemetry();

现在您可以像这样使用 TelemetryClient

    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, TelemetryClient telemetryClient)
        {
            telemetryClient.TrackTrace($"Middleware {nameof(CustomMiddleware)} invoked");

            await _next(context);
        }
    }

有关完整解决方案,请参阅 this repo