Expand description

An Azure Application Insights exporter implementation for OpenTelemetry Rust.

Disclaimer: This is not an official Microsoft product.

Usage

Configure a OpenTelemetry pipeline using the Application Insights exporter and start creating spans (this example requires the reqwest-client feature):

use opentelemetry::trace::Tracer as _;

fn main() {
    let instrumentation_key = std::env::var("INSTRUMENTATION_KEY").unwrap();
    let tracer = opentelemetry_application_insights::new_pipeline(instrumentation_key)
        .with_client(reqwest::blocking::Client::new())
        .install_simple();

    tracer.in_span("main", |_cx| {});
}

Simple or Batch

The functions build_simple and install_simple build/install a trace pipeline using the simple span processor. This means each span is processed and exported synchronously at the time it ends.

The functions build_batch and install_batch use the batch span processor instead. This means spans are exported periodically in batches, which can be better for performance. This feature requires an async runtime such as Tokio or async-std. If you decide to use a batch span processor, make sure to call opentelemetry::global::shutdown_tracer_provider() before your program exits to ensure all remaining spans are exported properly (this example requires the reqwest-client and opentelemetry/rt-tokio features).

use opentelemetry::trace::Tracer as _;

#[tokio::main]
async fn main() {
    let instrumentation_key = std::env::var("INSTRUMENTATION_KEY").unwrap();
    let tracer = opentelemetry_application_insights::new_pipeline(instrumentation_key)
        .with_client(reqwest::Client::new())
        .install_batch(opentelemetry::runtime::Tokio);

    tracer.in_span("main", |_cx| {});

    opentelemetry::global::shutdown_tracer_provider();
}

Async runtimes and HTTP clients

In order to support different async runtimes, the exporter requires you to specify an HTTP client that works with your chosen runtime. The opentelemetry-http crate comes with support for:

  • surf for async-std: enable the surf-client and opentelemetry/rt-async-std features and configure the exporter with with_client(surf::Client::new()).
  • reqwest for tokio: enable the reqwest-client and opentelemetry/rt-tokio features and configure the exporter with either with_client(reqwest::Client::new()) or with_client(reqwest::blocking::Client::new()).

Alternatively you can bring any other HTTP client by implementing the HttpClient trait.

Metrics

Please note: Metrics are still experimental both in the OpenTelemetry specification as well as Rust implementation.

Please note: The metrics export configuration is still a bit rough in this crate. But once configured it should work as expected.

This requires the metrics feature.

use opentelemetry::{global, sdk};
use std::time::Duration;

#[tokio::main]
async fn main() {
    // Setup exporter
    let instrumentation_key = std::env::var("INSTRUMENTATION_KEY").unwrap();
    let exporter = opentelemetry_application_insights::Exporter::new(instrumentation_key, ());
    let controller = sdk::metrics::controllers::push(
        sdk::metrics::selectors::simple::Selector::Exact,
        sdk::export::metrics::ExportKindSelector::Stateless,
        exporter,
        tokio::spawn,
        opentelemetry::util::tokio_interval_stream,
    )
    .with_period(Duration::from_secs(1))
    .build();
    global::set_meter_provider(controller.provider());

    // Record value
    let meter = global::meter("example");
    let value_recorder = meter.f64_value_recorder("pi").init();
    value_recorder.record(3.14, &[]);

    // Give exporter some time to export values before exiting
    tokio::time::sleep(Duration::from_secs(5)).await;
}

Attribute mapping

OpenTelemetry and Application Insights are using different terminology. This crate tries it’s best to map OpenTelemetry fields to their correct Application Insights pendant.

Spans

The OpenTelemetry SpanKind determines the Application Insights telemetry type:

OpenTelemetry SpanKindApplication Insights telemetry type
CLIENT, PRODUCER, INTERNALDependency
SERVER, CONSUMERRequest

The Span’s status determines the Success field of a Dependency or Request. Success is false if the status Error; otherwise true.

The following of the Span’s attributes map to special fields in Application Insights (the mapping tries to follow the OpenTelemetry semantic conventions for trace and resource).

Note: for INTERNAL Spans the Dependency Type is always "InProc".

OpenTelemetry attribute keyApplication Insights field
service.versionContext: Application version (ai.application.ver)
enduser.idContext: Authenticated user id (ai.user.authUserId)
service.namespace + service.nameContext: Cloud role (ai.cloud.role)
service.instance.idContext: Cloud role instance (ai.cloud.roleInstance)
telemetry.sdk.name + telemetry.sdk.versionContext: Internal SDK version (ai.internal.sdkVersion)
SpanKind::Server + http.method + http.routeContext: Operation Name (ai.operation.name)
ai.*Context: AppInsights Tag (ai.*)
http.urlDependency Data
db.statementDependency Data
http.hostDependency Target
net.peer.name + net.peer.portDependency Target
net.peer.ip + net.peer.portDependency Target
db.nameDependency Target
http.status_codeDependency Result code
db.systemDependency Type
messaging.systemDependency Type
rpc.systemDependency Type
"HTTP" if any http. attribute existsDependency Type
"DB" if any db. attribute existsDependency Type
http.urlRequest Url
http.scheme + http.host + http.targetRequest Url
http.client_ipRequest Source
net.peer.ipRequest Source
http.status_codeRequest Response code

All other attributes are directly converted to custom properties.

For Requests the attributes http.method and http.route override the Name.

Events

Events are converted into Exception telemetry if the event name equals "exception" (see OpenTelemetry semantic conventions for exceptions) with the following mapping:

OpenTelemetry attribute keyApplication Insights field
exception.typeException type
exception.messageException message
exception.stacktraceException call stack

All other events are converted into Trace telemetry.

All other attributes are directly converted to custom properties.

Metrics

Metrics get reported to Application Insights as Metric Data. The Aggregator (chosen through the Selector passed to the controller) determines how the data is represented.

AggregatorData representation
Arraylist of measurements
DDSketchaggregation with value, min, max and count
Histogramaggregation with sum and count (buckets are not exported)
LastValueone measurement
MinMaxSumCountaggregation with value, min, max and count
Sumaggregation with only a value

Modules

Attributes for Application Insights context fields

Structs

Application Insights span exporter

Application Insights exporter pipeline builder

Enums

Errors that occurred during span export.

Traits

A minimal interface necessary for export spans over HTTP.

Functions

Create a new Application Insights exporter pipeline builder