Application Insights - 从 .net 核心中间件添加属性

C. *_*ijk 0 .net asp.net-core-mvc azure-application-insights .net-core

我正在尝试从我们的 .net 核心 MVC 应用程序中获取一些关于应用程序洞察的额外信息。我发现了以下帖子: 在 Application Insights 指标中为每个请求添加自定义属性

在答案中,他们使用自定义遥测初始值设定项,如果您想要一些请求数据或其他内容,则可以使用。

现在我们的应用程序中有一组中间件。他们将一些标题翻译成可读的内容。

当然,我们可以记录标题并搜索它们可以具有的所有不同值。但是我们希望将中间件的结果转化为应用洞察的属性。

任何人都知道如何将中间件的一些结果用于 Application Insights 请求遥测的属性?

C. *_*ijk 5

从@svoychik 那里得到了正确的想法。中间件将输出值添加到 HttpContext.Items。看例子:

using Microsoft.AspNetCore.Http;
using System.Text;
using System.Threading.Tasks;

namespace Test.API.Middleware
{
    public class ValueMiddleware
    {
        private readonly RequestDelegate next;

        public ApiKeyMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            if (!context.Items.ContainsKey("ApplicationData"))
            {
                httpContext.Items["ApplicationData"] = "Important Data";
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当您需要将所有这些项目纳入应用程序洞察时,您只需使用以下初始化程序:

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Http;

namespace Test.API.TelemetryInitializers : ITelemetryInitializer
{
    public class HttpContextItemsTelemetryInitializer
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        public HttpContextItemsTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public void Initialize(ITelemetry telemetry)
        {
            var context = httpContextAccessor.HttpContext;
            if (context == null)
            {
                return;
            }

            foreach (var item in context.Items)
            {
                var itemKey = item.Key.ToString();

                // Remove some pollution that Microsoft and the systems adds to the HttpContext Items.
                if (itemKey.Contains("Microsoft") || itemKey.Contains("System"))
                {
                    continue;
                }

                if (!telemetry.Context.GlobalProperties.ContainsKey(itemKey))
                {
                    telemetry.Context.GlobalProperties.Add(itemKey, item.Value.ToString());
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Startup.cs 中设置初始化程序和应用程序洞察,如下例所示:

using Test.API.TelemetryInitializers;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace Test.API
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSingleton<ITelemetryInitializer, HttpContextItemsTelemetryInitializer>();
            services.AddApplicationInsightsTelemetry();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware<ValueMiddleware>();
            app.UseMvc();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后它只是将 HttpContext.Items 的所有值添加到您的应用程序洞察中。