Crate opentelemetry_datadog

Source
Expand description

§OpenTelemetry Datadog Exporter

An OpenTelemetry datadog exporter implementation

See the Datadog Docs for information on how to run the datadog-agent

§Quirks

There are currently some incompatibilities between Datadog and OpenTelemetry, and this manifests as minor quirks to this exporter.

Firstly Datadog uses operation_name to describe what OpenTracing would call a component. Or to put it another way, in OpenTracing the operation / span name’s are relatively granular and might be used to identify a specific endpoint. In datadog, however, they are less granular - it is expected in Datadog that a service will have single primary span name that is the root of all traces within that service, with an additional piece of metadata called resource_name providing granularity. See here

The Datadog Golang API takes the approach of using a resource.name OpenTelemetry attribute to set the resource_name. See here

Unfortunately, this breaks compatibility with other OpenTelemetry exporters which expect a more granular operation name - as per the OpenTracing specification.

This exporter therefore takes a different approach of naming the span with the name of the tracing provider, and using the span name to set the resource_name. This should in most cases lead to the behaviour that users expect.

Datadog additionally has a span_type string that alters the rendering of the spans in the web UI. This can be set as the span.type OpenTelemetry span attribute.

For standard values see here.

If the default mapping is not fit for your use case, you may change some of them by providing FieldMappingFns in pipeline.

§Performance

For optimal performance, a batch exporter is recommended as the simple exporter will export each span synchronously on drop. The default batch exporter uses a dedicated thread for exprt, but you can enable the async batch exporter with rt-tokio, rt-tokio-current-thread or rt-async-std features and specify a runtime on the pipeline to have a batch exporter configured for you automatically.

[dependencies]
opentelemetry_sdk = { version = "*", features = ["rt-tokio"] }
opentelemetry-datadog = "*"
let provider = opentelemetry_datadog::new_pipeline()
    .install_batch()?;

§Bring your own http client

Users can choose appropriate http clients to align with their runtime.

Based on the feature enabled. The default http client will be different. If user doesn’t specific features or enabled reqwest-blocking-client feature. The blocking reqwest http client will be used as default client. If reqwest-client feature is enabled. The async reqwest http client will be used. If surf-client feature is enabled. The surf http client will be used.

Note that async http clients may need specific runtime otherwise it will panic. User should make sure the http client is running in appropriate runime.

Users can always use their own http clients by implementing HttpClient trait.

§Kitchen Sink Full Configuration

Example showing how to override all configuration options. See the DatadogPipelineBuilder docs for details of each option.

use opentelemetry::{global, KeyValue, trace::{Tracer, TracerProvider}, InstrumentationScope};
use opentelemetry_sdk::{trace::{self, RandomIdGenerator, Sampler}, Resource};
use opentelemetry_datadog::{new_pipeline, ApiVersion, Error};
use opentelemetry_http::{HttpClient, HttpError};
use opentelemetry_semantic_conventions as semcov;
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::io::AsyncReadExt as _;
use http::{Request, Response, StatusCode};
use std::convert::TryInto as _;
use http_body_util::BodyExt;

// `reqwest` and `surf` are supported through features, if you prefer an
// alternate http client you can add support by implementing `HttpClient` as
// shown here.
#[derive(Debug)]
struct HyperClient(hyper_util::client::legacy::Client<hyperlocal::UnixConnector, http_body_util::Full<hyper::body::Bytes>>);

#[async_trait]
impl HttpClient for HyperClient {
    async fn send(&self, request: Request<Vec<u8>>) -> Result<Response<Bytes>, HttpError> {
        let (parts, body) = request.into_parts();
        let request = hyper::Request::from_parts(parts, body.into());
        let mut response = self.0.request(request).await?;
        let status = response.status();

        let body = response.into_body().collect().await?;
        Ok(Response::builder()
            .status(status)
            .body(body.to_bytes().into())?)
    }
    async fn send_bytes(&self, request: Request<Bytes>) -> Result<Response<Bytes>, HttpError> {
        let (parts, body) = request.into_parts();
        //TODO - Implement a proper client
         Ok(Response::builder()
            .status(StatusCode::OK)
            .body(Bytes::from("Dummy response"))
            .unwrap())
    }
}

    let mut config = trace::Config::default();
    config.sampler = Box::new(Sampler::AlwaysOn);
    config.id_generator = Box::new(RandomIdGenerator::default());

    let provider = new_pipeline()
        .with_service_name("my_app")
        .with_api_version(ApiVersion::Version05)
        .with_agent_endpoint("http://localhost:8126")
        .with_trace_config(config)
        .install_batch().unwrap();
    global::set_tracer_provider(provider.clone());

    let scope = InstrumentationScope::builder("opentelemetry-datadog")
        .with_version(env!("CARGO_PKG_VERSION"))
        .with_schema_url(semcov::SCHEMA_URL)
        .with_attributes(None)
        .build();
    let tracer = provider.tracer_with_scope(scope);

    tracer.in_span("doing_work", |cx| {
        // Traced app logic here...
    });

    let _ = provider.shutdown(); // sending remaining spans before exit

Structs§

DatadogExporter
Datadog span exporter
DatadogPipelineBuilder
Builder for ExporterConfig struct.
DatadogPropagator
Extracts and injects SpanContexts into Extractors or Injectors using Datadog’s header format.
DatadogTraceStateBuilder
ModelConfig
Helper struct to custom the mapping between Opentelemetry spans and datadog spans.

Enums§

ApiVersion
Version of datadog trace ingestion API
Error
Wrap type for errors from opentelemetry datadog exporter

Traits§

DatadogTraceState

Functions§

new_pipeline
Create a new Datadog exporter pipeline builder.

Type Aliases§

FieldMappingFn
Custom mapping between opentelemetry spans and datadog spans.