Application Insights不包括自定义ITelemetryInitializer设置的属性

问题描述 投票:2回答:1

(添加了下面的更新1,我认为回答这个问题)

在一个相当简单的ASP.NET Core 2 Web应用程序中,我已在Program中初始化,如下所示:

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

我还没有在appSettings.json中配置一个检测键,因为现在我在本地运行。当我运行我的应用程序并在加载主页时强制异常时,我可以看到Visual Studio的遥测搜索Application Insights中记录的异常。

enter image description here

我现在想在每个记录的事件中捕获有关请求的一些细节。我已经遵循了一些指导并创建了ITelemetryInitializer的实现:

public class CustomTelemetryInitializer : ITelemetryInitializer
{
    private const string UserIdKey = "AsosUserId";

    private readonly IUserService _userService;

    public CustomTelemetryInitializer(IUserService userService)
    {
        _userService = userService;
    }

    public void Initialize(ITelemetry telemetry)
    {
        if (!(telemetry is RequestTelemetry requestTelemetry)) return;

        var props = requestTelemetry.Properties;

        if (!props.ContainsKey(UserIdKey))
        {
            var user = _userService.GetCurrentUser();

            if (user != null)
            {
                props.Add(UserIdKey, user.UserId);
            }
        }
    }
}

这主要是在跟随this guideIUserService只是一个使用IHttpContextAccessor获得当前ClaimsPrincipal的服务。您可以看到我正在尝试将用户ID添加到自定义遥测属性中。

我在ITelemetryInitializer注册了这个Startup,如下所示:

services.AddSingleton<ITelemetryInitializer, CustomTelemetryInitializer>();

当我再次运行我的应用程序时,我可以看到调试器正在运行CustomTelemetryInitializer并正确设置属性。但是,当我查看应用洞察中记录的事件时,不会包含自定义属性。它们看起来与上面的截图相同。

我已经尝试将Program中的应用洞察初始化移出,而是在使用Startup注册ITelemetryInitializer后在services.AddApplicationInsightsTelemetry()中初始化它,但这没有任何区别。

谁知道我做错了什么?

更新1

我意识到我犯了一个错误。毕竟,我的自定义属性包含在Request事件中。但不是异常事件。但我现在意识到这些异常事件在ITelemetry中采用了不同的Initialize实现,即TraceTelemetry。所以我没有意识到我是从我的自定义属性中排除这些事件。

c# azure asp.net-core azure-application-insights
1个回答
2
投票

很高兴你想出来了。 SDK中的所有ITelemetry实现都实现了ISupportProperties,它为它提供了Properties集合。如果要将属性附加到每个遥测,您可以转换为ISupportProperties并设置道具。

© www.soinside.com 2019 - 2024. All rights reserved.