Add and modify Azure Monitor OpenTelemetry for .NET, Java, Node.js, and Python applications

This guide provides instructions on integrating and customizing OpenTelemetry (OTel) instrumentation within Azure Monitor Application Insights.

To learn more about OpenTelemetry concepts, see the OpenTelemetry overview or OpenTelemetry FAQ.

Automatic data collection

The distros automatically collect data by bundling OpenTelemetry instrumentation libraries.

Included instrumentation libraries

Requests for Spring Boot native applications

  • Spring Web
  • Spring Web MVC (Model-View-Controller)
  • Spring WebFlux

Dependencies for Spring Boot native applications

Metrics

  • Micrometer Metrics

Logs for Spring Boot native applications

  • Logback

To reduce or increase the number of logs that Azure Monitor collects, first set the desired logging level (such as WARNING or ERROR) in the application's logging library.

For Quartz native applications, look at the Quarkus documentation.

Footnotes

  • ¹: Supports automatic reporting of unhandled/uncaught exceptions
  • ²: Supports OpenTelemetry Metrics

Note

The Azure Monitor OpenTelemetry Distros include custom mapping and logic to automatically emit Application Insights standard metrics.

Tip

All OpenTelemetry metrics whether automatically collected from instrumentation libraries or manually collected from custom coding are currently considered Application Insights "custom metrics" for billing purposes. Learn more.

Add a community instrumentation library

You can collect more data automatically when you include instrumentation libraries from the OpenTelemetry community.

Caution

We don't support or guarantee the quality of community instrumentation libraries. To suggest one for our distro, post or up-vote in our feedback community. Be aware, some are based on experimental OpenTelemetry specs and might introduce future breaking changes.

You can't use community instrumentation libraries with GraalVM Java native applications.

Collect custom telemetry

This section explains how to collect custom telemetry from your application.

Depending on your language and signal type, there are different ways to collect custom telemetry, including:

  • OpenTelemetry API
  • Language-specific logging/metrics libraries
  • Application Insights Classic API

The following table represents the currently supported custom telemetry types:

Language Custom Events Custom Metrics Dependencies Exceptions Page Views Requests Traces
ASP.NET Core
   OpenTelemetry API Yes Yes Yes Yes
   ILogger API Yes
   AI Classic API
Java
   OpenTelemetry API Yes Yes Yes Yes
   Logback, Log4j, JUL Yes Yes
   Micrometer Metrics Yes
   AI Classic API Yes Yes Yes Yes Yes Yes Yes
Node.js
   OpenTelemetry API Yes Yes Yes Yes
Python
   OpenTelemetry API Yes Yes Yes Yes
   Python Logging Module Yes
   Events Extension Yes Yes

Note

Application Insights Java 3.x and Application Insights Node.js 3.x collect telemetry from the Application Insights Classic API. This behavior simplifies upgrades and temporarily supports custom telemetry until the OpenTelemetry API includes all custom telemetry types.

Add custom metrics

In this context, the custom metrics term refers to manually instrumenting your code to collect extra metrics beyond what the OpenTelemetry Instrumentation Libraries automatically collect.

The OpenTelemetry API offers six metric "instruments" to cover various metric scenarios and you need to pick the correct "Aggregation Type" when visualizing metrics in Metrics Explorer. This requirement is true when using the OpenTelemetry Metric API to send metrics and when using an instrumentation library.

The following table shows the recommended aggregation types for each of the OpenTelemetry Metric Instruments.

OpenTelemetry Instrument Azure Monitor Aggregation Type
Counter Sum
Asynchronous Counter Sum
Histogram Min, Max, Average, Sum, and Count
Asynchronous Gauge Average
UpDownCounter Sum
Asynchronous UpDownCounter Sum

Caution

Other aggregation types aren't meaningful in most cases.

The OpenTelemetry Specification describes the instruments and provides examples of when you might use each one.

Tip

The histogram is the most versatile and most closely equivalent to the Application Insights GetMetric Classic API. Azure Monitor currently flattens the histogram instrument into our five supported aggregation types, and support for percentiles is underway. Although less versatile, other OpenTelemetry instruments have a lesser effect on your application's performance.

Histogram example

  1. Inject OpenTelemetry:

    • Spring

      import io.opentelemetry.api.OpenTelemetry;
      
      @Autowired
      OpenTelemetry openTelemetry;
      
    • Quarkus

      import io.opentelemetry.api.OpenTelemetry; 
      
      @Inject
      OpenTelemetry openTelemetry;
      
  2. Create a histogram:

    import io.opentelemetry.api.metrics.DoubleHistogram;
    import io.opentelemetry.api.metrics.Meter;
    
    Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
    DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
    histogram.record(1.0);
    histogram.record(100.0);
    histogram.record(30.0);
    

Counter example

  1. Inject OpenTelemetry:

    • Spring

      import io.opentelemetry.api.OpenTelemetry;
      
      @Autowired
      OpenTelemetry openTelemetry;
      
    • Quarkus

      import io.opentelemetry.api.OpenTelemetry; 
      
      @Inject
      OpenTelemetry openTelemetry;
      
  2. Create the counter:

    import io.opentelemetry.api.common.AttributeKey;
    import io.opentelemetry.api.common.Attributes;
    import io.opentelemetry.api.metrics.LongCounter;
    import io.opentelemetry.api.metrics.Meter;
    
    
    Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
    
    LongCounter myFruitCounter = meter.counterBuilder("MyFruitCounter")
                                      .build();
    
    myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
    myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
    myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
    myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
    myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
    myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
    

Gauge example

  1. Inject OpenTelemetry:

    • Spring

      import io.opentelemetry.api.OpenTelemetry;
      
      @Autowired
      OpenTelemetry openTelemetry;
      
    • Quarkus

      import io.opentelemetry.api.OpenTelemetry; 
      
      @Inject
      OpenTelemetry openTelemetry;
      
  2. Create a gauge:

    import io.opentelemetry.api.common.AttributeKey;
    import io.opentelemetry.api.common.Attributes;
    import io.opentelemetry.api.metrics.Meter;
    
    Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
    
    meter.gaugeBuilder("gauge")
         .buildWithCallback(
                observableMeasurement -> {
                    double randomNumber = Math.floor(Math.random() * 100);
                    observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
                });
    

Add custom exceptions

Select instrumentation libraries automatically report exceptions to Application Insights. However, you might want to manually report exceptions beyond what instrumentation libraries report. For instance, exceptions caught by your code aren't ordinarily reported. You might wish to report them to draw attention in relevant experiences including the failures section and end-to-end transaction views.

Set status to error and record an exception in your code:

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;

Span span = Span.current();
span.setStatus(StatusCode.ERROR, "errorMessage");
span.recordException(e);

Add custom spans

You might want to add a custom span in two scenarios. First, when there's a dependency request not already collected by an instrumentation library. Second, when you wish to model an application process as a span on the end-to-end transaction view.

  1. Inject OpenTelemetry:

    • Spring

      import io.opentelemetry.api.OpenTelemetry;
      
      @Autowired
      OpenTelemetry openTelemetry;
      
    • Quarkus

      import io.opentelemetry.api.OpenTelemetry;
      
      @Inject
      OpenTelemetry openTelemetry;
      
  2. Create a Tracer:

    import io.opentelemetry.api.trace.Tracer;
    
    static final Tracer tracer = openTelemetry.getTracer("com.example");
    
  3. Create a span, make it current, and then end it:

    Span span = tracer.spanBuilder("my first span").startSpan();
    try (Scope ignored = span.makeCurrent()) {
        // do stuff within the context of this 
    } catch (Throwable t) {
        span.recordException(t);
    } finally {
        span.end();
    }
    

Send custom events

This section provides guidance on instrumenting your application to capture and send custom events.

It's not possible to send a customEvent using the "microsoft.custom_event.name" attribute in Java native.

Modify telemetry

This section explains how to modify telemetry.

Add span attributes

These attributes might include adding a custom property to your telemetry. You might also use attributes to set optional fields in the Application Insights schema, like Client IP.

Add a custom property to a Span

Any attributes you add to spans are exported as custom properties. They populate the customDimensions field in the requests, dependencies, traces, or exceptions table.

Add custom dimensions in your code:

import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.common.AttributeKey;

AttributeKey attributeKey = AttributeKey.stringKey("mycustomdimension");
Span.current().setAttribute(attributeKey, "myvalue1");

Set the user IP

You can populate the client_IP field for requests by setting an attribute on the span. Application Insights uses the IP address to generate user location attributes and then discards it by default.

This field is automatically populated.

Set the user ID or authenticated user ID

You can populate the user_Id or user_AuthenticatedId field for requests by using the following guidance. User ID is an anonymous user identifier. Authenticated User ID is a known user identifier.

Important

Consult applicable privacy laws before you set the Authenticated User ID.

Populate the user ID field in the requests, dependencies, or exceptions table.

Set user_Id in your code:

import io.opentelemetry.api.trace.Span;

Span.current().setAttribute("enduser.id", "myuser");

Add log attributes

For Spring Boot native applications, Logback is instrumented out of the box.

Get the trace ID or span ID

You can obtain the Trace ID and Span ID of the currently active Span using following steps.

Get the request trace ID and the span ID in your code:

import io.opentelemetry.api.trace.Span;

Span span = Span.current();
String traceId = span.getSpanContext().getTraceId();
String spanId = span.getSpanContext().getSpanId();

Next steps