首页 > 解决方案 > 在 global.asax.cs 中分配后未填充 Insights InstrumentationKey

问题描述

我有一个.NET Framework 4.6.1使用这些 Nuget 包的 Web API 解决方案:

  <package id="Microsoft.ApplicationInsights" version="2.9.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.9.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.9.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Web" version="2.9.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.9.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.9.1" targetFramework="net461" />
  <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.5" targetFramework="net461" />

global.asax.cs我有这个代码:

protected void Application_Start()
{
    TelemetryConfiguration.Active.InstrumentationKey = ConfigurationManager.AppSettings[$"Insights-{EnvironmentConfig.EnvironmentName}"];

    GlobalConfiguration.Configure(WebApiConfig.Register);
}

我可以确认ConfigurationManager.AppSettings[]值检索确实检索到有效的 Insights 键。

在控制器中我有:

public class MyController : ApiController
{
    TelemetryClient telemetryClient = new TelemetryClient(TelemetryConfiguration.Active);

    [Route("api/DoSomething")]
    [HttpPost]
    public async Task<HttpResponseMessage> DoSomething()
    {
        try
        {
            // stuff happens
        }
        catch (Exception ex)
        {
            telemetryClient.TrackException(ex); // does not log
            throw ex;
        }
    }
}

如果我在// stuff happens(那里当然有实际代码)设置一个停止点并检查telemetryClient我可以看到该InstrumentationKey属性是空的。这意味着我需要在实例化TelemetryClient类并故意填充它的任何地方添加一行。

我怎样才能让它从头global.asax.cs开始填充?

标签: azure-application-insights.net-4.6.1

解决方案


尝试了两个 appsetting 属性ConfigurationManager.AppSettingsWebConfigurationManager.AppSettings我可以查看 Instrumentation键TelemetryConfiguration登录Application Insights

我们正在添加我们的检测密钥,TelemetryConfig其中可用Telemetryconfig.

protected void Application_Start()
{    
        TelemetryConfiguration.Active.InstrumentationKey = ConfigurationManager.AppSettings[$"Insights-{EnvironmentConfig.EnvironmentName}"];
    
        //TelemetryConfiguration.Active.InstrumentationKey = WebConfigurationManager.AppSettings[$"Insights-{EnvironmentConfig.EnvironmentName}"];
    
        GlobalConfiguration.Configure(WebApiConfig.Register);
 }

在此处输入图像描述

在此处输入图像描述


推荐阅读