Configure a Spring Boot Initializer app to use Application Insights

This article walks you through creating a Spring Boot application using Spring Initializr. It uses Azure Application Insights Spring Boot Starter for end-to-end monitoring of Java applications on cloud.

Prerequisites

The following prerequisites are required in order to complete the steps in this article:

  • An Azure subscription. If you don't already have an Azure subscription, you can activate your MSDN subscriber benefits or sign up for a free Azure account.
  • A supported Java Development Kit (JDK). For more information about the JDKs available for use when developing on Azure, see https://aka.ms/azure-jdks.
  • Apache Maven, version 3.0 or later.
  • Web Flux and Netty APIs are not currently supported with the Application Insights Spring Boot starter.

Create a custom application using Spring Initializr

  1. Browse to https://start.spring.io/.

  2. Specify that you want to generate a Maven project with Java, enter the Group and Artifact names for your application, and then select web dependency in the dependencies section.

    Basic Spring Initializr options

    Note

    Spring Initializr will use the Group and Artifact names to create the package name; for example: com.example.demo.

  3. Click the button to Generate Project.

  4. When prompted, download the project to a path on your local computer.

  5. After you have extracted the files on your local system, your custom Spring Boot application will be ready for editing.

    Custom Spring Boot project files

Create an Application Insights Resource on Azure

  1. Browse to Azure at https://portal.azure.com/ and click +New.

    Azure

  2. Click Management Tools, and then click Application Insights.

    Azure

  3. On the New Application Insights Resource page, specify the following information:

    • Enter the Name for your Application Insights resource.
    • Choose the Application Type to Java Web Application.
    • Specify your Subscription, Resource group and Location.
    • Select Pin to dashboard option, if you would like to pin the resource on your Azure.

    When you have specified these options, click Create to create your Application Insights resource.

    Azure

  4. Once your resource has been created, you will see it listed on your Azure Dashboard, as well as under the All Resources pages. You can click on your resource on any of those locations to open the overview page of the Application Insights resource. From this overview page please copy the instrumentation key.

    Azure

Configure your downloaded Spring Boot Application to use Application Insights

  1. Locate the POM.xml file in the root directory of your app, and add the following dependency in its dependencies section.
 <dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>applicationinsights-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
  1. Locate the application.properties file in the resources directory of your app, or create the file if it does not already exist.

    Locate the application.properties file

  2. Open the application.properties file in a text editor, and add the following lines to the file, and replace the sample values with the appropriate properties with appropriate credentials:

    # Specify the instrumentation key of your Application Insights resource.
    azure.application-insights.instrumentation-key=[your ikey from the resource]
    # Specify the name of your springboot application. This can be any logical name you would like to give to your app.
    spring.application.name=[your app name]
    

    For more ways to fine-tune Application Insights, refer to Application Insights Springboot starter readme.

    Note

    Use different Application Insights instrumentation keys (such as different resources) for different profiles like PROD, DEV, etc. Refer to Spring Boot Profile Specific Properties for additional information.

  3. Save and close the application.properties file.

  4. Create a folder named controller under the source folder for your package; for example:

    D:\Microsoft\demo\src\main\java\com\example\demo\controller

    -or-

    /users/example/home/demo/src/main/java/com/example/demo/controller

  5. Create a new file named TestController.java in the controller folder. Open the file in a text editor and add the following code to it:

     package com.example.demo;
    
     import com.microsoft.applicationinsights.TelemetryClient;
     import java.io.IOException;
     import org.springframework.beans.factory.annotation.Autowired;
     import org.springframework.web.bind.annotation.GetMapping;
     import org.springframework.web.bind.annotation.RequestMapping;
     import org.springframework.web.bind.annotation.RestController;
     import com.microsoft.applicationinsights.telemetry.Duration;
    
     @RestController
     @RequestMapping("/sample")
     public class TestController {
    
         @Autowired
         TelemetryClient telemetryClient;
    
         @GetMapping("/hello")
         public String hello() {
    
             //track a custom event  
             telemetryClient.trackEvent("Sending a custom event...");
    
             //trace a custom trace
             telemetryClient.trackTrace("Sending a custom trace....");
    
             //track a custom metric
             telemetryClient.trackMetric("custom metric", 1.0);
    
             //track a custom dependency
             telemetryClient.trackDependency("SQL", "Insert", new Duration(0, 0, 1, 1, 1), true);
    
             return "hello";
         }
     }
    

    Replace com.example.demo with the package name for your project.

  6. Save and close the TestController.java file.

  7. Build your Spring Boot application with Maven and run it. For example:

    mvn clean package
    mvn spring-boot:run
    
  8. Test the web app by browsing to http://localhost:8080/sample/hello using a web browser, or use the syntax like the following example if you have curl available:

    curl http://localhost:8080/sample/hello
    

    You should see the "hello!" message from your sample controller displayed. Application Insights will automatically collect this request and send it as a telemetry item with its associated custom event, custom metric, custom dependency, and custom trace as specified in the controller logic.

    After a few seconds you should see the data on Azure.

    Azure

Click on the Application Map tile to view high-level components and their interaction with each other. This is a recommended place to get a high level overview of entire application. Each Spring Boot Microservice is recognized by the spring application name. Remember to set it.

Azure

Configure Springboot Application to send log4j logs to Application Insights

  1. Modify the POM.xml file of the project and add/modify the dependencies section with following.
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>applicationinsights-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>applicationinsights-logging-log4j2</artifactId>
        <version>2.1.1</version>
    </dependency>
</dependencies>
  1. Save and close the POM.xml file.

  2. In \src\main\resources folder, create a new file log4j2.xml and configure it. For example:

<?xml version="1.0" encoding="UTF-8" ?>
<Configuration packages="com.microsoft.applicationinsights.log4j.v2">
  <Properties>
    <Property name="LOG_PATTERN">
      %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
    </Property>
  </Properties>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
    <ApplicationInsightsAppender name="aiAppender">
    </ApplicationInsightsAppender>
  </Appenders>
  <Loggers>
    <Root level="trace">
      <AppenderRef ref="Console"  />
      <AppenderRef ref="aiAppender"  />
    </Root>
  </Loggers>
</Configuration>
  1. Build and run the Spring Boot application again as shown above.

Within a few seconds, you should see all the spring logs being available on Azure.

Azure

You can even look at the detailed log messages and do analysis on Analytics Portal.

Azure

Next steps

To learn more about Spring and Azure, continue to the Spring on Azure documentation center.

Additional Resources

For more information about using Spring Boot applications on Azure, see the following articles:

Application Insights supports automatic collection of external dependencies and its correlation with incoming requests. Currently we support autocollection of Oracle, MsSQL, MySQL and Redis. For more details on enabling autocollection please follow the article how to use Application Insights Java agent.

For more information about Azure Application Insights, and its monitoring capabilities, see the Application Insights home page.

For more information about additional configuration details of Application Insights Spring Boot Starter, please refer to this link.

For feature requests and potential bugs, please open issues on our GitHub repository.

For more information about using Azure with Java, see the Azure for Java Developers and the Working with Azure DevOps and Java.

The Spring Framework is an open-source solution that helps Java developers create enterprise-level applications. One of the more popular projects built on top of that platform is Spring Boot, which provides a simplified approach for creating stand-alone Java applications. To help developers get started with Spring Boot, several sample Spring Boot packages are available at https://github.com/spring-guides/. In addition to choosing from the list of basic Spring Boot projects, Spring Initializr helps developers get started with creating custom Spring Boot applications.