Skip to content

Commit

Permalink
Azure Application Insights SpringBoot Starter (#646)
Browse files Browse the repository at this point in the history
* Added application insights starter for spring boot

* Added a way to disable default modules, added documentation and readme

* Polish readme

* Added properties to disable quick pulse integration, all web modules;
Clarified all default values in readme;
Changed default logging level to error;
Added @ConditionalOnWebApplication for web configurations.

* Fixed bean ordering issue

* Added properties for channel and new sampler, created TelemetryType enum for property auto complete

* Added documentation to added properties, added default values, updated readme.

* Changed sampling configuration, added more tests for autoconfiguration

* Changed constants with default values to public in order to use them in spring boot starter

* Added explicit dependency on TelemetryConfiguration for QuickPulse bean

* Polish

* Updated documentation regarding configuration values window

* Updated documentation of properties

* update build script to fix pom generation, enforced InternalLoggerBean to be created first

* improving the way to locate agent and registering web app

* adding way to get empty telemetry configuration object

* adding max_instant_rety configuration for boot

* refactoring spelling error

* fix a test

* fixing broken initialization

* changing SpringBootContextInitializer to TelemetryInitializer, contextTags are not reflected on UX if not in bond schema definition

* updating enabling web modules and enabling AI, adding autoconfiguration for JMX counters and JVM counters

* migrate tests to junit4

* adding more tests

* Heartbeat updates to accomodate autoconfig in SpringBoot

* Adding auto cofiguration for SpringBoot

* removing SpringBootInitializer to push meta deta, instead moving to heartbeat

* autoconfigure cloud_RoleName, removed field injection to constructor and setter injection, added java docs, added tests and improved README

* fixing dependency version

* specifying the version number

* resolving merge conflict, removed unused Operating system conditional, some refactoring to make the AutoConfiguration class simple

* remove unused imports

* modifying version number

* updating the archive base name for consistency, adding javadocs

* adding null check, some fixes and reducing styling

* fix test and intermediate commit

* removing TelemetryType enum for better maintanability, refactoring starter accordingly, making HeartBeatPayloadProviderInterface bean, fixing critical issue with sampling configuration

* Revert "improving the way to locate agent and registering web app"

This reverts commit bc19586.

* modularizing way to specify version number of starter, adding starter version number to HB telemetry

* reverting a file and fixing dual initialization

* adding the configuration parity tests

* updating readme with migration steps

* Smoke Tests for SpringBoot Application using SpringBoot AI Starter (#665)

* smoke test for SpringBoot

* smoke test app springboot

* trying java 7

* trying source and target compatibility

* fixing assert

* enabling the temporarily disbabled smoke tests

* Reverting temporary adjustments
  • Loading branch information
dhaval24 authored May 16, 2018
1 parent f79cdb8 commit cbb51bd
Show file tree
Hide file tree
Showing 35 changed files with 2,592 additions and 120 deletions.
201 changes: 201 additions & 0 deletions azure-application-insights-spring-boot-starter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@

**Application Insights Spring Boot Starter**

This Starter provides you the minimal and required configuration to use Application Insights in your Spring Boot application.

**Requirements**
Spring Boot 1.5+ or 2.0+

**Quick Start**

*1. Add dependency*
Gradle:
```groovy
compile "com.microsoft.azure:azure-application-insights-spring-boot-starter:${version}"
```

Maven:
```xml
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-application-insights-spring-boot-starter</artifactId>
<version>${version}</version>
</dependency>
```

*2. Provide Instrumentation Key*

Add property
```
azure.application-insights.instrumentation-key=<key from the Azure Portal>
```
into your `application.properties`

*3. Run your application*

Start your spring boot application as usual and in few minutes you'll start getting events.

**Additional Configuration**

#### Sending custom telemetry
```java
@RestController
public class TelemetryController {

@Autowired
private TelemetryClient telemetryClient;

@RequestMapping("/telemetry")
public void telemetry() {
telemetryClient.trackEvent("my event");
}
}
```


#### Sending logs to the application insight

Follow the instructions from [Spring Boot logging documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html) to configure custom logback or log4j2 appender.

`logback-spring.xml`:
```xml
<appender name="aiAppender"
class="com.microsoft.applicationinsights.logback.ApplicationInsightsAppender">
</appender>
<root level="trace">
<appender-ref ref="aiAppender" />
</root>
```

`log4j2.xml`:
```xml
<Configuration packages="com.microsoft.applicationinsights.log4j.v2">
<Appenders>
<ApplicationInsightsAppender name="aiAppender" />
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="aiAppender"/>
</Root>
</Loggers>
</Configuration>
```

#### Register own telemetry module, processor or initializer by defining it as a bean in the configuration
```java
@SpringBootApplication
public class MyApplication {

public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}

@Bean
public TelemetryModule myTelemetryModule() {
return new MyTelemetryModule();
}

@Bean
public TelemetryInitializer myTelemetryInitializer() {
return new MyTelemetryInitializer();
}

@Bean
public TelemetryProcessor myTelemetryProcessor() {
return new MyTelemetryProcessor();
}

@Bean
public ContextInitializer myContextInitializer() {
return new MyContextInitializer();
}
}
```


#### Configure more parameters using `application.properties`
```properties
# Instrumentation key from the Azure Portal. Required.
azure.application-insights.instrumentation-key=00000000-0000-0000-0000-000000000000

# Enable/Disable tracking. Default value: true.
azure.application-insights.enabled=true

# Enable/Disable web modules. Default value: true.
azure.application-insights.web.enabled=true

# Logging type [console, file]. Default value: console.
azure.application-insights.logger.type=console
# Logging level [all, trace, info, warn, error, off]. Default value: error.
azure.application-insights.logger.level=error

# Enable/Disable QuickPulse (Live Metrics). Default value: True
azure.application-insights.quick-pulse.enabled=true

# Enable/Disable developer mode, all telemetry will be sent immediately without batching. Significantly affects performance and should be used only in developer environment. Default value: false.
azure.application-insights.channel.in-process.developer-mode=false
# Endpoint address, Default value: https://dc.services.visualstudio.com/v2/track.
azure.application-insights.channel.in-process.endpoint-address=https://dc.services.visualstudio.com/v2/track
# Maximum count of telemetries that will be batched before sending. Must be between 1 and 1000. Default value: 500.
azure.application-insights.channel.in-process.max-telemetry-buffer-capacity=500
# Interval to send telemetry. Must be between 1 and 300. Default value: 5 seconds.
azure.application-insights.channel.in-process.flush-interval-in-seconds=5
# Size of disk space that Application Insights can use to store telemetry in case of network outage. Must be between 1 and 1000. Default value: 10 megabytes.
azure.application-insights.channel.in-process.max-transmission-storage-files-capacity-in-mb=10
# Enable/Disable throttling on sending telemetry data. Default value: true.
azure.application-insights.channel.in-process.throttling=true

# Percent of telemetry events that will be sent to Application Insights. Percentage must be close to 100/N where N is an integer.
# E.g. 50 (=100/2), 33.33 (=100/3), 25 (=100/4), 20, 1 (=100/100), 0.1 (=100/1000). Default value: 100 (all telemetry events).
azure.application-insights.telemetry-processor.sampling.percentage=100
# If set only telemetry of specified types will be included. Default value: all telemetries are included;
azure.application-insights.telemetry-processor.sampling.include=
# If set telemetry of specified type will be excluded. Default value: none telemetries are excluded.
azure.application-insights.telemetry-processor.sampling.exclude=

# Enable/Disable default telemetry modules. Default value: true.
azure.application-insights.default-modules.ProcessPerformanceCountersModule.enabled=true
azure.application-insights.default-modules.JvmPerformanceCountersModule.enabled=true
azure.application-insights.default-modules.WebRequestTrackingTelemetryModule.enabled=true
azure.application-insights.default-modules.WebSessionTrackingTelemetryModule.enabled=true
azure.application-insights.default-modules.WebUserTrackingTelemetryModule.enabled=true
azure.application-insights.default-modules.WebPerformanceCounterModule.enabled=true
azure.application-insights.default-modules.WebOperationIdTelemetryInitializer.enabled=true
azure.application-insights.default-modules.WebOperationNameTelemetryInitializer.enabled=true
azure.application-insights.default-modules.WebSessionTelemetryInitializer.enabled=true
azure.application-insights.default-modules.WebUserTelemetryInitializer.enabled=true
azure.application-insights.default-modules.WebUserAgentTelemetryInitializer.enabled=true

#Enable/Disable heartbeat module. Default value : true
azure.application-insights.heart-beat.enabled=true
#Default heartbeat interval is 15 minutes. Minimum heartbeat interval can be 30 seconds.
azure.application-insights.heart-beat.heart-beat-interval=900
#If set of properties are specified they would be excluded from Heartbeat payload
azure.application-insights.heart-beat.excluded-heart-beat-properties-list=
#If set of HeartBeat providers are specified they would be excluded
azure.application-insights.heart-beat.excluded-heart-beat-provider-list=
```

### Completely disable Application Insights using `application.properties`
```properties
azure.application-insights.enabled=false
azure.application-insights.web.enabled=false
```
Note: Do not configure `azure.application-insights.instrumentation-key` property for optimal performance
and avoiding any Application Insights beans creation by Spring.


## Migrating from XML based configuration ##
1. Please remove ApplicationInsights.xml file from the project resources or class path.
2. Add applicationinsights-spring-boot-starter-<version_number>.jar file to pom.xml or build.gradle (you do not need to specify applicationinsights-core and web jars independently).
The starter takes are of it for you.
3. Please configure springboot Application.properties file with Application Insights Instrumentation key.
4. Compile the project and execute it from your IDE or command line using java -jar applicationjarname
5. To specify AI properties using command line please refer to SpringBoot Documentation.
6. To use [ApplicationInsigts Java agent](https://docs.microsoft.com/en-us/azure/application-insights/app-insights-java-agent) please follow official documentation
4. To get an initialized instance of TelemetryClient please use Spring autowired annotation. This will provide a fully initialized instance of TelemetryClient.

```Java
@Autowired
TelemetryClient client;
```
67 changes: 67 additions & 0 deletions azure-application-insights-spring-boot-starter/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import com.microsoft.applicationinsights.build.tasks.PropsFileGen

/*
* ApplicationInsights-Java
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the ""Software""), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/

apply from: "$buildScriptsDir/common-java.gradle"
apply from: "$buildScriptsDir/publishing.gradle"

archivesBaseName = 'applicationinsights-spring-boot-starter'
version = project.properties['spring.boot.starter.version-number']

def starterVersionFileDir = "$project.buildDir/src/generated/main/resources"
task generateVersionProperties(type: PropsFileGen) {
targetFile = new File(starterVersionFileDir, "starter-version.properties")
property "version", project.version
}

processResources.dependsOn generateVersionProperties

sourceSets {
main {
resources {
srcDir starterVersionFileDir
}
}
}

dependencies {
compile (project(':core'))
compile (project(':web'))
provided('org.springframework.boot:spring-boot:1.5.9.RELEASE')
provided('org.springframework.boot:spring-boot-autoconfigure:1.5.9.RELEASE')
provided('org.springframework.boot:spring-boot-starter-web:1.5.9.RELEASE')
provided('org.springframework.boot:spring-boot-configuration-processor:1.5.9.RELEASE')
testCompile('junit:junit:4.12')
testCompile('org.springframework.boot:spring-boot-starter-test:1.5.9.RELEASE')
testCompile('org.assertj:assertj-core:2.6.0')
}

compileJava.dependsOn(processResources)
// region Publishing properties

projectPomName = project.msftAppInsightsJavaSdk + " Spring Boot starter"
projectPomDescription = "This is the Spring Boot starter of " + project.msftAppInsightsJavaSdk

whenPomConfigured = { p ->
def agentArtifactId = project(":agent").jar.baseName
p.dependencies = p.dependencies.findAll { dep -> dep.artifactId != agentArtifactId }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
spring.boot.starter.version-number=1.0.0-BETA
Loading

0 comments on commit cbb51bd

Please sign in to comment.