Azure Monitor OpenTelemetry-based auto-instrumentation for Java applications
This article describes how to enable and configure the OpenTelemetry-based Azure Monitor Java offering. After you finish the instructions in this article, you'll be able to use Azure Monitor Application Insights to monitor your application.
Note
On March 31, 2025, support for instrumentation key ingestion will end. Instrumentation key ingestion will continue to work, but we'll no longer provide updates or support for the feature. Transition to connection strings to take advantage of new capabilities.
Get started
Java auto-instrumentation can be enabled without any code changes.
Prerequisites
- Java application using Java 8+
- Azure subscription: Create an Azure subscription for free
- Application Insights resource: Create an Application Insights resource
Enable Azure Monitor Application Insights
This section shows you how to download the auto-instrumentation jar file.
Download the jar file
Download the applicationinsights-agent-3.2.11.jar file.
Warning
If you're upgrading from 3.2.x to 3.3.0-BETA:
- Starting from 3.3.0-BETA,
LoggingLevelis not captured by default as part of Traces' custom dimension since that data is already captured in theSeverityLevelfield. For details on how to re-enable this if needed, please see the config options
If you're upgrading from 3.1.x:
- Starting from 3.2.0, controller "InProc" dependencies are not captured by default. For details on how to enable this, please see the config options.
- Database dependency names are now more concise with the full (sanitized) query still present in the
datafield. HTTP dependency names are now more descriptive. This change can affect custom dashboards or alerts if they relied on the previous values. For details, see the 3.2.0 release notes.
If you're upgrading from 3.0.x:
- The operation names and request telemetry names are now prefixed by the HTTP method, such as
GETandPOST. This change can affect custom dashboards or alerts if they relied on the previous values. For details, see the 3.1.0 release notes.
Point the JVM to the jar file
Add -javaagent:path/to/applicationinsights-agent-3.2.11.jar to your application's JVM args.
Tip
For help with configuring your application's JVM args, see Tips for updating your JVM args.
Set the Application Insights connection string
There are two ways you can point the jar file to your Application Insights resource:
You can set an environment variable:
APPLICATIONINSIGHTS_CONNECTION_STRING = <Copy connection string from Application Insights Resource Overview>Or you can create a configuration file named
applicationinsights.json. Place it in the same directory asapplicationinsights-agent-3.2.11.jarwith the following content:{ "connectionString": "Copy connection string from Application Insights Resource Overview" }
Find the connection string on your Application Insights resource.
Confirm data is flowing
Run your application and open your Application Insights Resource tab in the Azure portal. It can take a few minutes for data to show up in the portal.
Note
If you can't run the application or you aren't getting data as expected, see the Troubleshooting section.
Important
If you have two or more services that emit telemetry to the same Application Insights resource, you're required to set cloud role names to represent them properly on the application map.
As part of using Application Insights instrumentation, we collect and send diagnostic data to Microsoft. This data helps us run and improve Application Insights. You can disable nonessential data collection. To learn more, see Statsbeat in Azure Application Insights.
Configuration options
In the applicationinsights.json file, you can also configure these settings:
- Cloud role name
- Cloud role instance
- Sampling
- JMX metrics
- Custom dimensions
- Telemetry processors (preview)
- Autocollected logging
- Autocollected Micrometer metrics, which include Spring Boot Actuator metrics
- Heartbeat
- HTTP proxy
- Self-diagnostics
For more information, see Configuration options.
Instrumentation libraries
Java 3.x includes the following instrumentation libraries.
Autocollected requests
- JMS consumers
- Kafka consumers
- Netty/WebFlux
- Servlets
- Spring scheduling
Autocollected dependencies
Autocollected dependencies plus downstream distributed trace propagation:
- Apache HttpClient
- Apache HttpAsyncClient
- AsyncHttpClient
- Google HttpClient
- gRPC
- java.net.HttpURLConnection
- Java 11 HttpClient
- JAX-RS client
- Jetty HttpClient
- JMS
- Kafka
- Netty client
- OkHttp
Autocollected dependencies without downstream distributed trace propagation:
- Cassandra
- JDBC
- MongoDB (async and sync)
- Redis (Lettuce and Jedis)
Autocollected logs
- java.util.logging
- Log4j, which includes MDC properties
- SLF4J/Logback, which includes MDC properties
Autocollected metrics
- Micrometer, which includes Spring Boot Actuator metrics
- JMX Metrics
Azure SDKs
Telemetry emitted by these Azure SDKs is automatically collected by default:
- Azure App Configuration 1.1.10+
- Azure Cognitive Search 11.3.0+
- Azure Communication Chat 1.0.0+
- Azure Communication Common 1.0.0+
- Azure Communication Identity 1.0.0+
- Azure Communication Phone Numbers 1.0.0+
- Azure Communication SMS 1.0.0+
- Azure Cosmos DB 4.13.0+
- Azure Digital Twins - Core 1.1.0+
- Azure Event Grid 4.0.0+
- Azure Event Hubs 5.6.0+
- Azure Event Hubs - Azure Blob Storage Checkpoint Store 1.5.1+
- Azure Form Recognizer 3.0.6+
- Azure Identity 1.2.4+
- Azure Key Vault - Certificates 4.1.6+
- Azure Key Vault - Keys 4.2.6+
- Azure Key Vault - Secrets 4.2.6+
- Azure Service Bus 7.1.0+
- Azure Storage - Blobs 12.11.0+
- Azure Storage - Blobs Batch 12.9.0+
- Azure Storage - Blobs Cryptography 12.11.0+
- Azure Storage - Common 12.11.0+
- Azure Storage - Files Data Lake 12.5.0+
- Azure Storage - Files Shares 12.9.0+
- Azure Storage - Queues 12.9.0+
- Azure Text Analytics 5.0.4+
Modify telemetry
This section explains how to modify telemetry.
Add spans
You can use opentelemetry-api to create tracers and spans. Spans populate the dependencies table in Application Insights. The string passed in for the span's name is saved to the target field within the dependency.
Note
This feature is only in 3.2.0 and later.
Add
opentelemetry-api-1.6.0.jarto your application:<dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-api</artifactId> <version>1.6.0</version> </dependency>Add spans in your code:
import io.opentelemetry.api.trace.Span; Span span = tracer.spanBuilder("mySpan").startSpan();
Add span events
You can use opentelemetry-api to create span events, which populate the traces table in Application Insights. The string passed in to addEvent() is saved to the message field within the trace.
Note
This feature is only in 3.2.0 and later.
Add
opentelemetry-api-1.6.0.jarto your application:<dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-api</artifactId> <version>1.6.0</version> </dependency>Add span events in your code:
import io.opentelemetry.api.trace.Span; span.addEvent("eventName");
Add span attributes
You can use opentelemetry-api to add attributes to spans. These attributes can include adding a custom business dimension to your telemetry. You can also use attributes to set optional fields in the Application Insights schema, such as User ID or Client IP.
Add a custom dimension
Adding one or more custom dimensions populates the customDimensions field in the requests, dependencies, traces, or exceptions table.
Note
This feature is only in 3.2.0 and later.
Add
opentelemetry-api-1.6.0.jarto your application:<dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-api</artifactId> <version>1.6.0</version> </dependency>Add custom dimensions in your code:
import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; Attributes attributes = Attributes.of(AttributeKey.stringKey("mycustomdimension"), "myvalue1"); span.setAllAttributes(attributes); span.addEvent("eventName", attributes);
Update span status and record exceptions
You can use opentelemetry-api to update the status of a span and record exceptions.
Note
This feature is only in 3.2.0 and later.
Add
opentelemetry-api-1.6.0.jarto your application:<dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-api</artifactId> <version>1.6.0</version> </dependency>Set status to error and record an exception in your code:
import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.StatusCode; span.setStatus(StatusCode.ERROR, "errorMessage"); span.recordException(e);
Set the user ID
Populate the user ID field in the requests, dependencies, or exceptions table.
Important
Consult applicable privacy laws before you set Authenticated User ID.
Note
This feature is only in 3.2.0 and later.
Add
opentelemetry-api-1.6.0.jarto your application:<dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-api</artifactId> <version>1.6.0</version> </dependency>Set
user_Idin your code:import io.opentelemetry.api.trace.Span; Span.current().setAttribute("enduser.id", "myuser");
Get the trace ID or span ID
You can use opentelemetry-api to get the trace ID or span ID. This action can be done to add these identifiers to existing logging telemetry to improve correlation when you debug and diagnose issues.
Note
This feature is only in 3.2.0 and later.
Add
opentelemetry-api-1.6.0.jarto your application:<dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-api</artifactId> <version>1.6.0</version> </dependency>Get the request trace ID and the span ID in your code:
import io.opentelemetry.api.trace.Span; String traceId = Span.current().getSpanContext().getTraceId(); String spanId = Span.current().getSpanContext().getSpanId();
Custom telemetry
Our goal in Application Insights Java 3.x is to allow you to send your custom telemetry by using standard APIs.
We currently support Micrometer, popular logging frameworks, and the Application Insights Java 2.x SDK. Application Insights Java 3.x automatically captures the telemetry sent through these APIs and correlates it with autocollected telemetry.
Supported custom telemetry
The following table represents currently supported custom telemetry types that you can enable to supplement the Java 3.x agent. To summarize:
- Custom metrics are supported through micrometer.
- Custom exceptions and traces are supported through logging frameworks.
- Custom requests, dependencies, and exceptions are supported through
opentelemetry-api. - Any type of the custom telemetry is supported through the Application Insights Java 2.x SDK.
| Custom telemetry type | Micrometer | Log4j, logback, JUL | 2.x SDK | opentelemetry-api |
|---|---|---|---|---|
| Custom events | Yes | |||
| Custom metrics | Yes | Yes | ||
| Dependencies | Yes | Yes | ||
| Exceptions | Yes | Yes | Yes | |
| Page views | Yes | |||
| Requests | Yes | Yes | ||
| Traces | Yes | Yes | Yes |
Currently, we're not planning to release an SDK with Application Insights 3.x.
Application Insights Java 3.x is already listening for telemetry that's sent to the Application Insights Java 2.x SDK. This functionality is an important part of the upgrade story for existing 2.x users. And it fills an important gap in our custom telemetry support until the OpenTelemetry API is generally available.
Send custom metrics by using Micrometer
Add Micrometer to your application:
<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-core</artifactId> <version>1.6.1</version> </dependency>Use the Micrometer global registry to create a meter:
static final Counter counter = Metrics.counter("test.counter");Use the counter to record metrics:
counter.increment();The metrics will be ingested into the customMetrics table, with tags captured in the
customDimensionscolumn. You can also view the metrics in the Metrics explorer under the "Log-based metrics" metric namespace.Note
Application Insights Java replaces all non-alphanumeric characters (except dashes) in the Micrometer metric name with underscores, so the
test.countermetric above will show up astest_counter.
Send custom traces and exceptions by using your favorite logging framework
Log4j, Logback, and java.util.logging are auto-instrumented. Logging performed via these logging frameworks is autocollected as trace and exception telemetry.
By default, logging is only collected when that logging is performed at the INFO level or above. To change this level, see the configuration options.
If you want to attach custom dimensions to your logs, use Log4j 1.2 MDC, Log4j 2 MDC, or Logback MDC. Application Insights Java 3.x automatically captures those MDC properties as custom dimensions on your trace and exception telemetry.
Send custom telemetry by using the 2.x SDK
Add
applicationinsights-core-2.6.4.jarto your application. All 2.x versions are supported by Application Insights Java 3.x. If you have a choice, it's worth using the latest version:<dependency> <groupId>com.microsoft.azure</groupId> <artifactId>applicationinsights-core</artifactId> <version>2.6.4</version> </dependency>Create a TelemetryClient:
static final TelemetryClient telemetryClient = new TelemetryClient();Use the client to send custom telemetry:
Events
telemetryClient.trackEvent("WinGame");Metrics
telemetryClient.trackMetric("queueLength", 42.0);Dependencies
boolean success = false; long startTime = System.currentTimeMillis(); try { success = dependency.call(); } finally { long endTime = System.currentTimeMillis(); RemoteDependencyTelemetry telemetry = new RemoteDependencyTelemetry(); telemetry.setSuccess(success); telemetry.setTimestamp(new Date(startTime)); telemetry.setDuration(new Duration(endTime - startTime)); telemetryClient.trackDependency(telemetry); }Logs
telemetryClient.trackTrace(message, SeverityLevel.Warning, properties);Exceptions
try { ... } catch (Exception e) { telemetryClient.trackException(e); }
Troubleshooting
For help with troubleshooting, see Troubleshooting.
Release notes
See the release notes on GitHub.
Support
To get support:
- For help with troubleshooting, review the troubleshooting steps.
- For Azure support issues, open an Azure support ticket.
- For OpenTelemetry issues, contact the OpenTelemetry community directly.
OpenTelemetry feedback
To provide feedback:
- Fill out the OpenTelemetry community's customer feedback survey.
- Tell Microsoft about yourself by joining our OpenTelemetry Early Adopter Community.
- Engage with other Azure Monitor users in the Microsoft Tech Community.
- Make a feature request at the Azure Feedback Forum.
Next steps
- To review the source code, see the Azure Monitor Java auto-instrumentation GitHub repository.
- To learn more about OpenTelemetry and its community, see the OpenTelemetry Java GitHub repository.
- To enable usage experiences, see Enable web or browser user monitoring.
Tilbakemeldinger
Send inn og vis tilbakemelding for