以编程方式设置 Application Insights 检测密钥会引发错误

Programmatically setting Application Insights instrumentation key throws error

为了在多个环境中支持 Application Insights,我们按照 this post 中的建议,以编程方式设置 Instrumentation Key

我们将 ApplicationInsights.config 中的 <InstrumentationKey> 留空,而是在 web.config:

中添加了一个应用程序设置
<add key="ApplicationInsightsInstrumentationKey" value="1234-5678-9xxx" />

Application_Start 中,我们执行以下操作来设置检测密钥:

var instrumentationKey = ConfigurationManager.AppSettings["ApplicationInsightsInstrumentationKey"];

if (string.IsNullOrWhiteSpace(instrumentationKey))
{
    throw new ConfigurationErrorsException("Missing app setting 'ApplicationInsightsInstrumentationKey' used for Application Insights");
}

TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;

new TelemetryClient().TrackEvent("Application started");

但是,这会产生一个异常,提示“TelemetryChannel 必须先初始化才能发送遥测”。

谷歌搜索此异常消息没有任何结果,但我想在跟踪事件之前还需要一些额外的东西?

从 ApplicationInsights.config 中删除 <InstrumentationKey /> 元素似乎可以解决问题。

我做了完全相同的事情,在 Application_Start() 中为 Web 应用程序设置了 iKey,然后在控制台应用程序中新建了一个 TelemetryClient。我 没有 我的 ApplicationInsights.config 中有任何元素,甚至没有一个空白元素。我在那个配置文件中保留了一条评论,说密钥是以编程方式设置的。