Application Insight配置存在一些混淆 . 它可以使用Visual Studio在应用程序本身中配置,也可以在使用Azure Portal的App Service中配置 .
Visual Studio
当我使用Visual Studio到add Application Insights Telemetry到我的asp.net core 2.0网站时,它将以下配置添加到appsettings.json:
{
// Changes to file post adding Application Insights Telemetry:
"ApplicationInsights": {
"InstrumentationKey": "10101010-1010-1010-1010-101010101010"
}
}
然后我在startup.cs中配置AppInsights服务,如下所示:
var instrumentationKey= Configuration.GetSection("ApplicationInsights:InstrumentationKey").Value;
services.AddApplicationInsightsTelemetry(opt => opt.InstrumentationKey = instrumentationKey);
Azure门户
但是,当我在Azure门户中的App Service中打开Application Insights选项卡时,它仍建议连接Application Insight . 然后,向导会向配置添加新的Intrumentation Key:
-
为什么有两个不同的键?
-
遥测技术究竟是什么产生App Service以及.NET Core应用程序本身 .
-
如何避免两次配置InstrumentationKey?
-
仅使用APPINSIGHTS_INSTRUMENTATIONKEY有什么副作用(例如在Visual Studio工具中) . 我的意思是我会在startup.cs中写:
var instrumentationKey= Configuration.GetSection("APPINSIGHTS_INSTRUMENTATIONKEY ").Value;
services.AddApplicationInsightsTelemetry(opt => opt.InstrumentationKey = instrumentationKey);
编辑:
我根据Tseng的回答得出结论,最好在Azure门户和appsettings.json中使用APPINSIGHTS_INSTRUMENTATIONKEY .
ASP.NET Core理解 APPINSIGHTS_INSTRUMENTATIONKEY
和 ApplicationInsights:InstrumentationKey
,但Azure Portal只是第一个,它必须是环境变量 . 如果您使用了第二个,并尝试从代码中的某个位置的config中读取它,您可以轻松地在Azure门户和在Azure中运行的应用程序中使用不同的值 .
此外,如果您从配置中手动读取检测键,则应首先查看 APPINSIGHTS_INSTRUMENTATIONKEY
然后查看 ApplicationInsights:InstrumentationKey
:
var instrumentationKey= Configuration.GetSection("APPINSIGHTS_INSTRUMENTATIONKEY")?.Value
?? Configuration.GetSection("ApplicationInsights:InstrumentationKey")?.Value;
因为 services.AddApplicationInsightsTelemetry(Configuration);
如何工作 . 以防万一Azure Portal中的设置密钥与appsettings.json中的设置密钥不同
1 回答
嗯,第一个是当您不在Azure App Service上托管或者您不想设置环境变量时 . 实际使用哪一个取决于配置构建器的配置方式 .
通常你在
Startup.cs
或Programm.cs
中有类似的东西:使用
.AddXxx
调用的顺序很重要 . 将使用具有匹配键的最后一次注册 . 这里.AddEnvironmentVariables()
是最后一个 . 设置APPINSIGHTS_INSTRUMENTATIONKEY
变量时,它将覆盖用户机密appsettings.Development.json
或appsettings.json
中设置的Appinsights:InstrumentationKey
的所有值 .如果未设置
APPINSIGHTS_INSTRUMENTATIONKEY
,配置库将查看用户机密并在找到时使用它 . 如果未找到,它将搜索appsettings.Development.json
,如果它不包含值搜索appsettings.json
.TL;DR :只有在未设置环境变量时才会使用一个表单appsettings.json .
更新
新答案
如the code中所示,注册它的Application Insight扩展方法将在找到匹配的条目时覆盖环境变量或appsettings.json中的值 .
Note :当您删除
.AddEnvironmentVariables()
时 won't ever 使用Azure门户中设置的值,因为.AddEnvironmentVariables()
使用键APPINSIGHTS_INSTRUMENTATIONKEY
将环境变量加载到配置中(见下文) .当它在那里找不到时,它会尝试appsettings.json
ApplicationInsights:InstrumentationKey
中的常规键 .在你的例子中
传递的值 won't be used 除非你们两个,删除环境变量(或
.AddEnvironmentVariables()
) AND 从appsettings.json
中删除条目 .所以对于大多数常见配置,它足以调用
其中
Configuration
是IConfigurationRoot
. 此重载将从环境变量或appsettings.json(如果找到)加载它 .当你想要对它进行更多的程序控制时,你可以使用