private void writeSDKInfoFile() { String sdkInfoFilePath = String.format("%s/%s", Constants.AI_SDK_DIRECTORY, Constants.AI_SDK_INFO_FILENAME); String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); String sdkInfo = String.format(Constants.AI_SDK_INFO_FILE_CONTENT_TEMPLATE, instrumentationKey); try { fileFactory.create(sdkInfoFilePath, sdkInfo); } catch (IOException e) { InternalLogger.INSTANCE.error("Failed to write SDK info file for Docker awareness. Error: %s", e.toString()); } } }
@Bean @ConditionalOnMissingBean public TelemetryConfiguration telemetryConfiguration(AzureMonitorConfig config) { // Gets the active instance of TelemetryConfiguration either created by starter or xml TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.getActive(); if (StringUtils.isEmpty(telemetryConfiguration.getInstrumentationKey())) { telemetryConfiguration.setInstrumentationKey(config.instrumentationKey()); } return telemetryConfiguration; }
/** * This bean is already available when the * {@see <a href="https://github.com/Microsoft/ApplicationInsights-Java/tree/master/ * azure-application-insights-spring-boot-starter">Azure Application Insights starter</a>} * is present. */ @Bean @ConditionalOnMissingBean public TelemetryConfiguration telemetryConfiguration(AzureMonitorConfig config) { // Gets the active instance of TelemetryConfiguration either created by starter or xml final TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.getActive(); if (StringUtils.isEmpty(telemetryConfiguration.getInstrumentationKey())) { telemetryConfiguration.setInstrumentationKey(config.instrumentationKey()); } return telemetryConfiguration; }
/** * This bean is already available when the * {@see <a href="https://github.com/Microsoft/ApplicationInsights-Java/tree/master/ * azure-application-insights-spring-boot-starter">Azure Application Insights starter</a>} * is present. */ @Bean @ConditionalOnMissingBean public TelemetryConfiguration telemetryConfiguration(AzureMonitorConfig config) { // Gets the active instance of TelemetryConfiguration either created by starter or xml final TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.getActive(); if (StringUtils.isEmpty(telemetryConfiguration.getInstrumentationKey())) { telemetryConfiguration.setInstrumentationKey(config.instrumentationKey()); } return telemetryConfiguration; }
/** * Retrieves the appId (in correlation format) for the current active config's instrumentation key. */ public static String retrieveApplicationCorrelationId() { String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); String appId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(instrumentationKey); //it's possible the appId returned is null (e.g. async task is still pending or has failed). In this case, just //return and let the next request resolve the ikey. if (appId == null) { InternalLogger.INSTANCE.trace("Application correlation Id could not be retrieved (e.g. task may be pending or failed)"); return ""; } return REQUEST_CONTEXT_HEADER_APPID_KEY + "=" + appId; }
/** * Retrieves the appId (in correlation format) for the current active config's instrumentation key. */ public static String retrieveApplicationCorrelationId() { String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); String appId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(instrumentationKey); //it's possible the appId returned is null (e.g. async task is still pending or has failed). In this case, just //return and let the next request resolve the ikey. if (appId == null) { InternalLogger.INSTANCE.trace("Application correlation Id could not be retrieved (e.g. task may be pending or failed)"); return ""; } return REQUEST_CONTEXT_HEADER_APPID_KEY + "=" + appId; }
/** * Retrieves the appId for the current active config's instrumentation key. */ public static String getAppId() { String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); String appId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(instrumentationKey); //it's possible the appId returned is null (e.g. async task is still pending or has failed). In this case, just //return and let the next request resolve the ikey. if (appId == null) { InternalLogger.INSTANCE.trace("Application correlation Id could not be retrieved (e.g. task may be pending or failed)"); return ""; } return appId; }
/** * Retrieves the appId for the current active config's instrumentation key. */ public static String getAppId() { String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); String appId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(instrumentationKey); //it's possible the appId returned is null (e.g. async task is still pending or has failed). In this case, just //return and let the next request resolve the ikey. if (appId == null) { InternalLogger.INSTANCE.trace("Application correlation Id could not be retrieved (e.g. task may be pending or failed)"); return ""; } return appId; }
/** * Given a request context, it generates a new dependency target, possibly including the appId found in * the given Request-Context. * @param requestContext - the Request-Context header value * @return the dependency target */ public static String generateChildDependencyTarget(String requestContext) { if (requestContext == null || requestContext.isEmpty()) { InternalLogger.INSTANCE.trace("generateChildDependencyTarget: won't continue as requestContext is null or empty."); return ""; } String instrumentationKey = TelemetryConfiguration.getActive().getInstrumentationKey(); if (instrumentationKey == null || instrumentationKey.isEmpty()) { InternalLogger.INSTANCE.error("Failed to generate target correlation. InstrumentationKey is null or empty."); return ""; } String target = generateSourceTargetCorrelation(instrumentationKey, requestContext); if (target == null) { InternalLogger.INSTANCE.warn("Target value is null and hence returning empty string"); return ""; // we want an empty string instead of null so it plays nicer with bytecode injection } return target; }
private void testIkeySystemProperty(String propertyName) { System.setProperty(propertyName, "00000000-0000-0000-0000-000000000001"); context.register(PropertyPlaceholderAutoConfiguration.class, ApplicationInsightsTelemetryAutoConfiguration.class); context.refresh(); TelemetryClient telemetryClient = context.getBean(TelemetryClient.class); TelemetryConfiguration telemetryConfiguration = context.getBean(TelemetryConfiguration.class); assertThat(telemetryConfiguration).isSameAs(TelemetryConfiguration.getActive()); assertThat(telemetryConfiguration.getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000001"); assertThat(telemetryClient.getContext().getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000001"); System.clearProperty(propertyName); }
/** * Checks whether tracking is enabled. * @return 'true' if tracking is disabled, 'false' otherwise. */ public boolean isDisabled() { return (Strings.isNullOrEmpty(configuration.getInstrumentationKey()) && Strings.isNullOrEmpty(getContext().getInstrumentationKey())) || configuration.isTrackingDisabled(); }
public DefaultQuickPulsePingSender(final ApacheSender apacheSender, final String instanceName, final String quickPulseId) { this.apacheSender = apacheSender; final String ikey = TelemetryConfiguration.getActive().getInstrumentationKey(); quickPulsePingUri = QP_BASE_URI + "ping?ikey=" + ikey; final StrBuilder sb = new StrBuilder(); sb.append("{"); sb.append("\"Documents\": null,"); sb.append("\"Instance\":\"" + instanceName + "\","); sb.append("\"InstrumentationKey\": null,"); sb.append("\"InvariantVersion\": 2,"); sb.append("\"MachineName\":\"" + instanceName + "\","); sb.append("\"Metrics\": null,"); sb.append("\"StreamId\": \"" + quickPulseId + "\","); sb.append("\"Timestamp\": \"\\/Date("); pingPrefix = sb.toString(); }
@Test public void shouldSetInstrumentationKeyWhenContextLoads() { EnvironmentTestUtils.addEnvironment(context, "azure.application-insights.instrumentation-key:00000000-0000-0000-0000-000000000000"); context.register(PropertyPlaceholderAutoConfiguration.class, ApplicationInsightsTelemetryAutoConfiguration.class); context.refresh(); TelemetryClient telemetryClient = context.getBean(TelemetryClient.class); TelemetryConfiguration telemetryConfiguration = context.getBean(TelemetryConfiguration.class); assertThat(telemetryConfiguration).isSameAs(TelemetryConfiguration.getActive()); assertThat(telemetryConfiguration.getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000"); assertThat(telemetryClient.getContext().getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000"); }
@Test @Ignore("Boot 2 causes backport issues if depending on RelaxedPropertyBinder") public void shouldSetInstrumentationKeyFromRelaxedCase() { EnvironmentTestUtils.addEnvironment(context, "AZURE.APPLICATION_INSIGHTS.INSTRUMENTATION_KEY: 00000000-0000-0000-0000-000000000000"); context.register(PropertyPlaceholderAutoConfiguration.class, ApplicationInsightsTelemetryAutoConfiguration.class); context.refresh(); TelemetryClient telemetryClient = context.getBean(TelemetryClient.class); TelemetryConfiguration telemetryConfiguration = context.getBean(TelemetryConfiguration.class); assertThat(telemetryConfiguration).isSameAs(TelemetryConfiguration.getActive()); assertThat(telemetryConfiguration.getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000"); assertThat(telemetryClient.getContext().getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000"); }
private void ikeyTest(String configurationIkey, String expectedIkey) { // Make sure that there is no exception when fetching the i-key by having both // the i-key and channel in the configuration, otherwise the channel won't be instantiated AppInsightsConfigurationBuilder mockParser = createMockParser(true, false, false); ApplicationInsightsXmlConfiguration appConf = new ApplicationInsightsXmlConfiguration(); appConf.setInstrumentationKey(configurationIkey); Mockito.doReturn(appConf).when(mockParser).build(any(InputStream.class)); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.getInstrumentationKey(), expectedIkey); assertTrue(mockConfiguration.getChannel() instanceof InProcessTelemetryChannel); }
@Test public void testWithEmptySections() { AppInsightsConfigurationBuilder mockParser = Mockito.mock(AppInsightsConfigurationBuilder.class); ApplicationInsightsXmlConfiguration appConf = new ApplicationInsightsXmlConfiguration(); appConf.setInstrumentationKey(MOCK_IKEY); appConf.setTelemetryInitializers(null); appConf.setContextInitializers(null); appConf.setModules(null); appConf.setSdkLogger(null); Mockito.doReturn(appConf).when(mockParser).build(any(InputStream.class)); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(false, mockConfiguration.isTrackingDisabled()); assertEquals(MOCK_IKEY, mockConfiguration.getInstrumentationKey()); assertThat(mockConfiguration.getContextInitializers(), hasSize(3)); assertThat(mockConfiguration.getChannel(), instanceOf(InProcessTelemetryChannel.class)); }
@Test public void testEmptyConfiguration() { TelemetryConfiguration emptyConfig = TelemetryConfiguration.getActiveWithoutInitializingConfig(); Assert.assertNull(emptyConfig.getInstrumentationKey()); Assert.assertSame(NopTelemetryChannel.instance(), emptyConfig.getChannel()); Assert.assertEquals(0, emptyConfig.getTelemetryModules().size()); Assert.assertFalse(emptyConfig.isTrackingDisabled()); Assert.assertEquals(0, emptyConfig.getContextInitializers().size()); Assert.assertEquals(0, emptyConfig.getTelemetryProcessors().size()); }
@Test public void testInitializeAllDefaults() throws Exception { AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(null); appConf.setInstrumentationKey(MOCK_IKEY); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(false, mockConfiguration.isTrackingDisabled()); assertEquals(MOCK_IKEY, mockConfiguration.getInstrumentationKey()); assertThat(mockConfiguration.getContextInitializers(), Matchers.<ContextInitializer>hasSize(3)); assertThat(mockConfiguration.getTelemetryInitializers(), Matchers.<TelemetryInitializer>empty()); assertThat(mockConfiguration.getTelemetryProcessors(), empty()); assertThat(mockConfiguration.getChannel(), instanceOf(StdOutChannel.class)); }
@Test public void testContextInitializers() { AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(null); appConf.setInstrumentationKey(MOCK_IKEY); ContextInitializersXmlElement contextInitializersXmlElement = new ContextInitializersXmlElement(); ArrayList<AddTypeXmlElement> contexts = new ArrayList<AddTypeXmlElement>(); AddTypeXmlElement addXmlElement = new AddTypeXmlElement(); addXmlElement.setType("com.microsoft.applicationinsights.extensibility.initializer.DeviceInfoContextInitializer"); contexts.add(addXmlElement); contextInitializersXmlElement.setAdds(contexts); appConf.setContextInitializers(contextInitializersXmlElement); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(false, mockConfiguration.isTrackingDisabled()); assertEquals(MOCK_IKEY, mockConfiguration.getInstrumentationKey()); assertThat(mockConfiguration.getContextInitializers(), hasSize(4)); assertThat(mockConfiguration.getTelemetryInitializers(), empty()); assertThat(mockConfiguration.getTelemetryProcessors(), empty()); assertThat(mockConfiguration.getChannel(), instanceOf(StdOutChannel.class)); }
@Test public void testInstrumentationKeyIsResolvedDuringModuleInit() { Assert.assertEquals(0, mockProfileFetcher.callCount()); String ikey = TelemetryConfiguration.getActive().getInstrumentationKey(); //calling resolver now will actually retrieve the appId from the completed task mockProfileFetcher.setResultStatus(ProfileFetcherResultTaskStatus.COMPLETE); mockProfileFetcher.setAppIdToReturn("someAppId"); String appId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(ikey); Assert.assertEquals(1, mockProfileFetcher.callCount()); Assert.assertEquals("cid-v1:someAppId", appId); //calling it again should retrieve appId from cache (i.e. fetcher call count remains 2) appId = InstrumentationKeyResolver.INSTANCE.resolveInstrumentationKey(ikey); Assert.assertEquals(1, mockProfileFetcher.callCount()); Assert.assertEquals("cid-v1:someAppId", appId); }