Application Insights for a Java web app

Last Update: 9/26/2016

Application Insights is in Preview.

Application Insights is an extensible analytics service that helps you understand the performance and usage of your live application. Use it to detect and diagnose performance issues and exceptions, and write code to track what users do with your app.

sample data

Application Insights web tests monitor your application's availability.

You'll need:

  • Oracle JRE 1.6 or later, or Zulu JRE 1.6 or later
  • A subscription to Microsoft Azure. (You could start with the free trial.)

1. Get an Application Insights instrumentation key

  1. Sign in to the Microsoft Azure Portal
  2. Create a new Application Insights resource

    Click + and choose Application Insights

  3. Set the application type to Java web application.

    Fill a name, choose Java web app, and click Create

  4. Find the instrumentation key of the new resource. You'll need to paste this into your code project shortly.

    In the new resource overview, click Properties and copy the Instrumentation Key

2. Add the Application Insights SDK for Java to your project

Choose the appropriate way for your project.

If you're creating a Dynamic Web project in Eclipse...

Use the Application Insights SDK for Java plug-in.

If you're using Maven...

If your project is already set up to use Maven for build, merge the following snippet of code to your pom.xml file.

Then refresh the project dependencies, to get the binaries downloaded.

<repositories>
   <repository>
      <id>central</id>
      <name>Central</name>
      <url>http://repo1.maven.org/maven2</url>
   </repository>
</repositories>

<dependencies>
  <dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>applicationinsights-web</artifactId>
    <!-- or applicationinsights-core for bare API -->
    <version>[1.0,)</version>
  </dependency>
</dependencies>
  • Build or checksum validation errors? Try using a specific version, such as: <version>1.0.n</version>. You'll find the latest version in the SDK release notes or in our Maven artifacts.
  • To update to a new SDK
    • Refresh your project's dependencies.

If you're using Gradle...

If your project is already set up to use Gradle for build, merge the following snippet of code to your build.gradle file.

Then refresh the project dependencies, to get the binaries downloaded.

repositories {
  mavenCentral()
}

dependencies {
  compile group: 'com.microsoft.azure', name: 'applicationinsights-web', version: '1.+'
  // or applicationinsights-core for bare API
}
  • Build or checksum validation errors? Try using a specific version, such as: version:'1.0.n'. You'll find the latest version in the SDK release notes.
  • To update to a new SDK
    • Refresh your project's dependencies.

Otherwise ...

Manually add the SDK:

  1. Download the Application Insights SDK for Java
  2. Extract the binaries from the zip file, and add them to your project.

Questions...

  • What's the relationship between the -core and -web components in the zip?

    • applicationinsights-core gives you the bare API. You always need this.
    • applicationinsights-web gives you metrics that track HTTP request counts and response times. You can omit this if you don't want this telemetry automatically collected - for example if you want to write your own.
  • To update the SDK

3. Add an Application Insights xml file

Add ApplicationInsights.xml to the resources folder in your project, or otherwise make sure it is added to your project’s deployment class path. Copy into it the following XML.

Substitute the instrumentation key that you got from the Azure portal.

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30">


  <!-- The key from the portal: -->

  <InstrumentationKey>** Your instrumentation key **</InstrumentationKey>


  <!-- HTTP request component (not required for bare API) -->

  <TelemetryModules>
    <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebRequestTrackingTelemetryModule"/>
    <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebSessionTrackingTelemetryModule"/>
    <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebUserTrackingTelemetryModule"/>
  </TelemetryModules>

  <!-- Events correlation (not required for bare API) -->
  <!-- These initializers add context data to each event -->

  <TelemetryInitializers>
    <Add   type="com.microsoft.applicationinsights.web.extensibility.initializers.WebOperationIdTelemetryInitializer"/>
    <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebOperationNameTelemetryInitializer"/>
    <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebSessionTelemetryInitializer"/>
    <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebUserTelemetryInitializer"/>
    <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebUserAgentTelemetryInitializer"/>

  </TelemetryInitializers>
</ApplicationInsights>
  • The instrumentation key is sent along with every item of telemetry and tells Application Insights to display it in your resource.
  • The HTTP Request component is optional. It automatically sends telemetry about requests and response times to the portal.
  • Events correlation is an addition to the HTTP request component. It assigns an identifier to each request received by the server, and adds this as a property to every item of telemetry as the property 'Operation.Id'. It allows you to correlate the telemetry associated with each request by setting a filter in diagnostic search.

4. Add an HTTP filter

The last configuration step allows the HTTP request component to log each web request. (Not required if you just want the bare API.)

Locate and open the web.xml file in your project, and merge the following snippet of code under the web-app node, where your application filters are configured.

To get the most accurate results, the filter should be mapped before all other filters.

<filter>
  <filter-name>ApplicationInsightsWebFilter</filter-name>
  <filter-class>
    com.microsoft.applicationinsights.web.internal.WebRequestTrackingFilter
  </filter-class>
</filter>
<filter-mapping>
   <filter-name>ApplicationInsightsWebFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

If you're using MVC 3.1 or later

Edit these elements to include the Application Insights package:

<context:component-scan base-package=" com.springapp.mvc, com.microsoft.applicationinsights.web.spring"/>

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.microsoft.applicationinsights.web.spring.RequestNameHandlerInterceptorAdapter" />
    </mvc:interceptor>
</mvc:interceptors>

If you're using Struts 2

Add this item to the Struts configuration file (usually named struts.xml or struts-default.xml):

 <interceptors>
   <interceptor name="ApplicationInsightsRequestNameInterceptor" class="com.microsoft.applicationinsights.web.struts.RequestNameInterceptor" />
 </interceptors>
 <default-interceptor-ref name="ApplicationInsightsRequestNameInterceptor" />

(If you have interceptors defined in a default stack, the interceptor can simply be added to that stack.)

5. Install on the server

On Windows servers, install:

(This enables performance counters.)

6. Run your application

Either run it in debug mode on your development machine, or publish to your server.

7. View your telemetry in Application Insights

Return to your Application Insights resource in Microsoft Azure Portal.

HTTP requests data will appear on the overview blade. (If it isn't there, wait a few seconds and then click Refresh.)

sample data

Click through any chart to see more detailed metrics.

Click the server requests chart to see counts of requests by name

And when viewing the properties of a request, you can see the telemetry events associated with it such as requests and exceptions.

Under Related Items, click any item

Learn more about metrics.

Smart address name calculation

Application Insights assumes the format of HTTP requests for MVC applications is: VERB controller/action

For example, GET Home/Product/f9anuh81, GET Home/Product/2dffwrf5 and GET Home/Product/sdf96vws will be grouped into GET Home/Product.

This enables meaningful aggregations of requests, such as number of requests and average execution time for requests.

Exceptions and request failures

Exceptions not handled by your code are collected:

On the Overview blade, click Failures to see details of exceptions

To collect data on other exceptions, you have two options:

Monitor method calls and external dependencies

Install the Java Agent to log specified internal methods and calls made through JDBC, with timing data.

Performance counters

Click the Servers tile, and you'll see a range of performance counters.

On the Overview blade, click Servers to see performance counters from your server

Customizing performance counter collection

To disable collection of the standard set of performance counters, add the following snippet under the root node of the ApplicationInsights.xml file:

<PerformanceCounters>
   <UseBuiltIn>False</UseBuiltIn>
</PerformanceCounters>

Collecting additional performance counters

You can specify additional performance counters to be collected.

JMX counters (exposed by the Java Virtual Machine)

<PerformanceCounters>
  <Jmx>
    <Add objectName="java.lang:type=ClassLoading" attribute="TotalLoadedClassCount" displayName="Loaded Class Count"/>
    <Add objectName="java.lang:type=Memory" attribute="HeapMemoryUsage.used" displayName="Heap Memory Usage-used" type="composite"/>
  </Jmx>
</PerformanceCounters>
  • displayName – The name displayed in the Application Insights portal.
  • objectName – The JMX object name.
  • attribute – The attribute of the JMX object name to fetch
  • type (optional) - The type of JMX object’s attribute:
    • Default: a simple type such as int or long.
    • composite: the perf counter data is in the format of 'Attribute.Data'
    • tabular: the perf counter data is in the format of a table row

Windows performance counters

Each Windows performance counter is a member of a category (in the same way that a field is a member of a class). Categories can either be global, or can have numbered or named instances.

<PerformanceCounters>
  <Windows>
    <Add displayName="Process User Time" categoryName="Process" counterName="%User Time" instanceName="__SELF__" />
    <Add displayName="Bytes Printed per Second" categoryName="Print Queue" counterName="Bytes Printed/sec" instanceName="Fax" />
  </Windows>
</PerformanceCounters>
  • displayName – The name displayed in the Application Insights portal
  • categoryName – The performance counter category (performance object) with which this performance counter is associated
  • counterName – The name of the performance counter
  • instanceName – The name of the performance counter category instance, or an empty string (""), if the category contains a single instance. If the categoryName is Process, and the performance counter you'd like to collect is from the current JVM process on which your app is running, specify "__SELF__".

Your performance counters are visible as custom metrics in Metrics Explorer.

In Metrics Explorer, add or select a chart, then in the chart details blade, scroll down to Custom metrics. Check one or more to display it on the chart.

Unix performance counters

Get user and session data

OK, you're sending telemetry from your web server. Now to get the full 360-degree view of your application, you can add more monitoring:

Capture log traces

You can use Application Insights to slice and dice logs from Log4J, Logback or other logging frameworks. You can correlate the logs with HTTP requests and other telemetry. Learn how.

Send your own telemetry

Now that you've installed the SDK, you can use the API to send your own telemetry.

Questions? Problems?

Troubleshooting Java