我尝试从Application Insights 源代码中搜索 Instrumentation 密钥的配置。
我可以在TelemetryConfigurationFactory 类中看到如下代码片段。
/**
* Setting an instrumentation key:
* First we try the system property '-DAPPLICATION_INSIGHTS_IKEY=i_key' or '-DAPPINSIGHTS_INSTRUMENTATIONKEY=i_key'
* Next we will try the environment variable 'APPLICATION_INSIGHTS_IKEY' or 'APPINSIGHTS_INSTRUMENTATIONKEY'
* Next we will try to fetch the i-key from the ApplicationInsights.xml
* @param userConfiguration The configuration that was represents the user's configuration in ApplicationInsights.xml.
* @param configuration The configuration class.
*/
private void setInstrumentationKey(ApplicationInsightsXmlConfiguration userConfiguration, TelemetryConfiguration configuration) {
try {
String ikey;
// First, check whether an i-key was provided as a java system property i.e. '-DAPPLICATION_INSIGHTS_IKEY=i_key', or '-DAPPINSIGHTS_INSTRUMENTATIONKEY=i_key'
ikey = System.getProperty(EXTERNAL_PROPERTY_IKEY_NAME);
if (!Strings.isNullOrEmpty(ikey)) {
configuration.setInstrumentationKey(ikey);
return;
}
ikey = System.getProperty(EXTERNAL_PROPERTY_IKEY_NAME_SECONDARY);
if (!Strings.isNullOrEmpty(ikey)) {
configuration.setInstrumentationKey(ikey);
return;
}
// Second, try to find the i-key as an environment variable 'APPLICATION_INSIGHTS_IKEY' or 'APPINSIGHTS_INSTRUMENTATIONKEY'
ikey = System.getenv(EXTERNAL_PROPERTY_IKEY_NAME);
if (!Strings.isNullOrEmpty(ikey)) {
configuration.setInstrumentationKey(ikey);
return;
}
ikey = System.getenv(EXTERNAL_PROPERTY_IKEY_NAME_SECONDARY);
if (!Strings.isNullOrEmpty(ikey)) {
configuration.setInstrumentationKey(ikey);
return;
}
// Else, try to find the i-key in ApplicationInsights.xml
if (userConfiguration != null) {
ikey = userConfiguration.getInstrumentationKey();
if (ikey == null) {
return;
}
ikey = ikey.trim();
if (ikey.length() == 0) {
return;
}
configuration.setInstrumentationKey(ikey);
}
} catch (Exception e) {
InternalLogger.INSTANCE.error("Failed to set instrumentation key: '%s'", e.getMessage());
}
}
似乎 Instrumentation 键可以配置为 ajava system property
或 作为environment variable
or in ApplicationInsights.xml
。
根据您的描述,您的代码中的 System.getEnv("XXX") 返回 null。您可以检查以下可能的原因:
使用我的电脑 > 高级 > 环境变量使变量对所有新进程可见。
2.试图读取变量的进程已经在运行。重新启动它。
3.Tomcat的启动脚本在调用java.exe之前取消设置变量
4.Tomcat 在它的 Java 代码中取消设置变量。
另外,您可以参考这个线程:System.getenv() 在环境变量存在时返回 null。
希望它可以帮助你。