Expand description
§grow-datadog-apm
Rust SDK for Datadog APM by Grow Codes.
Two halves:
- Tracing to the local Datadog Agent:
init_tracing(OpenTelemetry, OTLP to the Agent, unified service tagging,DatadogPropagator, Datadog error attributes), the id helpers (to_datadog_trace_id, …) and log correlation (datadog_log_fields). The client’shealth,pingandserver_versionuse the Agent’sGET /info. - Query via the Datadog SaaS API:
DatadogSpansQuery(spans search, aggregate,get_trace,list_services, …; needsDD_API_KEY+DD_APP_KEY).
use grow_datadog_apm::{datadog_log_fields, tracing::{traced, TracingConfig}, DatadogApmClient};
let client = DatadogApmClient::from_env()?;
let health = client.health().await?;
println!("healthy: {}", health.healthy);
let tracing = client.init_tracing(TracingConfig::new("checkout"))?;
traced("charge-card", async {
println!("{:?}", datadog_log_fields(Default::default()));
Ok::<_, std::io::Error>(())
})
.await
.ok();
client.close().await; // flushes the spansFeatures: blocking (a blocking client), testing (in-memory fakes and the conformance
runner)
, tower and reqwest-middleware (tracing instrumentation)
.
Re-exports§
pub use crate::core::Error;pub use crate::core::ErrorCode;pub use crate::core::HealthStatus;pub use crate::core::Result;pub use crate::core::RetryPolicy;pub use crate::core::Secret;
Modules§
- aggregation
- Aggregation functions of the spans aggregate API.
- blocking
blocking - Blocking wrapper (feature
blocking). Each client owns a tokio runtime with one worker thread, so background work (exports, retries’ timers) keeps running between blocking calls. - core
- Shared core: errors, configuration, secrets in config, redaction, retries and transport.
- testing
testing - Test support (feature
testing): in-memory fakes and the conformance runner (SPEC §6). - tracing
- Tracing category (SPEC §5), built on the OpenTelemetry SDK: setup, span helpers, propagation, framework adapters and the trace query model.
Structs§
- Agent
Info - The Agent’s
GET /infodocument (fields this package reads). - Aggregate
Spans Options - Filter of
DatadogSpansQuery::aggregate_spans. - Datadog
ApmClient - Async client for Datadog APM. Cheap to clone (clones share one connection pool).
- Datadog
ApmConfig - Immutable client configuration; build it with
DatadogApmConfig::builderorDatadogApmConfig::from_env.Debugoutput redacts every credential. - Datadog
ApmConfig Builder - Builder for
DatadogApmConfig. Values set here win over the environment. - Datadog
LogFields - Datadog log correlation fields; serializes with the
dd.*keys (absent fields omitted). - Datadog
LogFields Options - Explicit unified-service-tagging values for
datadog_log_fields(None= not given). - Datadog
Propagator - Datadog propagator: injects and extracts
x-datadog-trace-id(low 64 bits, decimal),x-datadog-parent-id(decimal),x-datadog-sampling-priority(1/0) and, for 128-bit ids,x-datadog-tags: _dd.p.tid=<high 64 bits hex>. - Datadog
Query Warning - A warning attached to a partial query result.
- Datadog
Span - One span returned by the spans search API.
- Datadog
Span Exporter - Span exporter wrapper installed by
init_tracing: fills the Datadog error attributes (with_datadog_error_attributes) and adds the terminated-context links (with_terminated_context_link) before handing the spans to the wrapped exporter. It coverswith_span,traced, the HTTP adapters and plain OpenTelemetry calls (the Rust SDK has no span processor hook that may still change an ending span). - Datadog
Spans Page - One page of
DatadogSpansQuery::search_spans_page. - Datadog
Spans Query - The Datadog spans query client (SaaS API at
https://api.<site>, headersDD-API-KEYandDD-APPLICATION-KEY). It implementsTraceQueryClienton top of the spans search and aggregate APIs, plus the Datadog-specificsearch_spans,aggregate_spansandping. Cheap to clone. - Datadog
Trace Id - A trace id split the way Datadog stores it.
- Datadog
Tracing Handle - A running Datadog tracing setup. Dereferences to the generic
TracingHandle(tracer,tracer_provider,force_flush,shutdown, …). Cheap to clone. - GetTrace
Options - Options of
DatadogSpansQuery::get_trace_with_options. - Init
Tracing Options - Extra options of
init_tracing_with_options. - List
Services Options - Options of
DatadogSpansQuery::list_services_with_options. - Search
Spans Options - Options of
DatadogSpansQuery::search_spansandsearch_spans_page. - Span
Aggregate Bucket - One bucket of an aggregation.
- Span
Aggregate Result - Result of
DatadogSpansQuery::aggregate_spans. - Span
Compute - One computation of
DatadogSpansQuery::aggregate_spans. - Span
Group By - One group-by facet of
DatadogSpansQuery::aggregate_spans. - Span
Group BySort - Order of the groups of a
SpanGroupBy. - Span
Histogram - Buckets a numeric facet.
- Span
Timeseries Point - A point of a timeseries compute.
- Terminated
Context - A W3C context that lost against Datadog headers in
DatadogPropagator’s extract.
Enums§
- Datadog
Time - A point in time for a query: an absolute time or a Datadog date expression (
now-15m, ISO-8601, epoch milliseconds). - Span
Compute Value - One compute result of a bucket.
Constants§
- AGENT_
TRACE_ PORT - Default Agent trace intake port (
GET /info). - ATTR_
ERROR_ MESSAGE - The
error.messagespan attribute. - ATTR_
ERROR_ STACK - The
error.stackspan attribute. - ATTR_
ERROR_ TYPE - The
error.typespan attribute (error type name). - DATADOG_
DEFAULT_ PROPAGATORS - The default propagators of this package: Datadog headers, W3C trace context and baggage.
- DATADOG_
ORIGIN_ HEADER - Origin of the trace (synthetics, rum, …).
- DATADOG_
PARENT_ ID_ HEADER - Carries the span id, unsigned decimal.
- DATADOG_
SAMPLING_ PRIORITY_ HEADER 1(sampled) or0(not sampled).- DATADOG_
SITES - The Datadog sites of the official OpenAPI spec (servers enum). Other host names are accepted too (the spec’s “any Datadog deployment” server), but never a scheme, port or path.
- DATADOG_
TAGS_ HEADER - Propagated tags, e.g.
_dd.p.tid=<high 64 bits hex>. - DATADOG_
TRACE_ ID_ HEADER - Carries the low 64 bits of the trace id, unsigned decimal.
- DATADOG_
WAIT_ INTERVAL - Default polling interval of
DatadogSpansQuery’swait_for_trace(Datadog allows 50 searches per minute). - DEFAULT_
PROTOCOL - Default OTLP protocol of this package.
- DEFAULT_
SITE - Default Datadog site (US1).
- DEFAULT_
URL - Default Datadog Agent trace intake URL (
health,pingandserver_versionuse itsGET /info). - LOG_
FIELD_ ENV - Key of
DatadogLogFields::env. - LOG_
FIELD_ SERVICE - Key of
DatadogLogFields::service. - LOG_
FIELD_ SPAN_ ID - Key of
DatadogLogFields::span_id. - LOG_
FIELD_ TRACE_ ID - Key of
DatadogLogFields::trace_id. - LOG_
FIELD_ VERSION - Key of
DatadogLogFields::version. - OTLP_
GRPC_ PORT - Default Agent OTLP/gRPC port.
- OTLP_
HTTP_ PORT - Default Agent OTLP/HTTP port.
- PROPAGATOR_
DATADOG - Propagator name of
DatadogPropagatorinTracingConfig::propagators(PropagatorKind::Other("datadog")).
Functions§
- api_
url_ for_ site - The API base URL of a site:
https://api.<site>. An empty site meansDEFAULT_SITE. - datadog_
error_ attributes - The Datadog error attributes for
err:error.type(the Rust type name ofE),error.message(err.to_string()) anderror.stack(a backtrace of the caller; Rust errors carry no stack). - datadog_
exporter_ factory - The exporter factory of this package: OTLP
http/protobuforgrpctoconfig.endpoint(default: the local Agent), wrapped in aDatadogSpanExporter.nativeis aCONFIGerror (the package exports OTLP only). - datadog_
kind - Converts a Datadog
span.kind(or OpenTelemetry kind name) to aSpanKind; unknown values areUnspecified. - datadog_
log_ fields - The Datadog log correlation fields for the active span, ready to merge into any structured
log record:
dd.trace_id,dd.span_id,dd.service,dd.env,dd.version. Service, env and version come fromoptions, else the lastinit_tracingconfig (orset_datadog_log_defaults). Without a valid span only the service fields are set; unknown fields areNone. - datadog_
search_ span_ to_ span - Maps one span of the spans search API (
data[i]ofPOST /api/v2/spans/events/search, or itsattributes) to a SPECSpan. Nested span attributes (attributes,custom) are flattened to dotted keys;tags(key:value) are added as attributes. Name =resource_name, kind fromspan.kind, status error whenstatusiserrororerroris set; duration from thedurationattribute (nanoseconds) when present, else end − start. - datadog_
trace_ id_ string - The trace id in the format Datadog’s log correlation (
dd.trace_id) and its search API use: 32 lower-case hex characters for a 128-bit id, the low 64 bits in decimal for a 64-bit id. - datadog_
trace_ span_ to_ span - Maps a Datadog trace span — the Agent’s format (
trace_id,span_id,parent_id,start,duration,meta,metrics) or the trace-by-id API format (traceID,traceIDFull,spanID,parentID,startTime,endTime,duration) — to a SPECSpan. - extract_
datadog_ context - Reads the Datadog headers of a carrier into a remote span context;
Nonewhen they are missing or invalid. A missing sampling priority counts as sampled. - from_
datadog_ span_ id - Converts a Datadog unsigned decimal span id to 16 lower-case hex characters.
- from_
datadog_ trace_ id - Joins a Datadog trace id (low 64 bits in decimal, optional
_dd.p.tidhigh half in hex) into a 32-character OpenTelemetry trace id.None(or an empty string) means a zero high half. - init_
tracing - Sets up OpenTelemetry tracing that exports to the Datadog Agent (SPEC §5):
- init_
tracing_ with_ options init_tracingwith an explicitDatadogApmConfigor environment.- is_
datadog_ site - Whether
siteis one ofDATADOG_SITES. - normalize_
datadog_ span_ id - Normalizes a Datadog decimal span id to 16 hex characters;
Nonefor an empty or zero id. - normalize_
datadog_ trace_ id - Normalizes any trace id Datadog returns to 32 lower-case hex characters: a 32-character value is hex, a shorter all-digit value (at most 20 digits) is the 64-bit decimal form, anything else is hex.
- normalize_
site - Lower-cases and trims a site name.
- order_
propagators - Puts
tracecontextbeforedatadogso the Datadog propagator sees the W3C result and applies the conflict rules (Datadog wins); every other propagator keeps its position. - otlp_
traces_ url - The exporter URL for a protocol and an OTLP endpoint: for
http/protobufan endpoint without a path gets/v1/traces; gRPC endpoints are used as they are. - parse_
datadog_ tags - Parses Datadog tags (
DD_TAGS):key:valuepairs separated by commas and/or spaces. Entries without a:or with an empty key are ignored. - quote_
query_ value - Quotes a value for the Datadog query syntax when it contains spaces or special characters.
- record_
datadog_ exception - Alias of
record_exception(Go nameRecordDatadogException). - record_
exception - Records
erras anexceptionevent on the active span (liketracing::record_exception) and also sets the Datadog error attributes. The span status is unchanged. - set_
datadog_ error - Alias of
set_error(Go nameSetDatadogError). - set_
datadog_ log_ defaults - Sets the service/env/version
datadog_log_fieldsuses when none are given (init_tracingcalls it with its effective config). - set_
error - Sets
ERRORstatus (with the error message) on the active span, records the exception event (liketracing::set_error) and sets the Datadog error attributes. - set_
error_ attributes - Sets the Datadog error attributes (
error.type,error.message,error.stack) forerron the active span. No-op without a recording span. - terminated_
context - The W3C context that lost against Datadog headers during extract, if any.
- terminated_
context_ links - Span links for a span started from an extracted context: one link to the terminated W3C
context (
reason=terminated_context,context_headers=tracecontext), or none. Pass them toSpanOptions::linkwhen you export spans withoutinit_tracing’s exporter. - to_
datadog_ span_ id - Converts an OpenTelemetry span id (up to 16 hex characters) to Datadog’s unsigned decimal.
- to_
datadog_ trace_ id - Splits an OpenTelemetry trace id (up to 32 hex characters, left-padded) into Datadog’s form.
Invalid or all-zero ids are
VALIDATIONerrors. - trace_
id_ for_ path - The id to put in a
GET /api/v2/trace/{id}path. Datadog reads an all-digit id as decimal, so a hex id without a letter is sent as its full decimal value; otherwise lower-case hex. - trace_
search_ query_ string - The Datadog query string for a SPEC
TraceSearchQuery:service:,resource_name:,@<tag>:and@duration:>=/<=(nanoseconds). An empty query is*. - validate_
site - Validates a site name and returns it normalized. A value with a scheme, port, path or other
non-host characters (for example
https://app.datadoghq.com) is aCONFIGerror. - with_
datadog_ error_ attributes - Adds the Datadog error attributes to
spanwhen it has none yet: from its lastexceptionevent (exception.type,exception.message,exception.stacktrace) or, for anERRORstatus without an event,error.messagefrom the status description. - with_
terminated_ context_ link - Adds the terminated-context link (see
terminated_context_links) to a span whose remote parent is a Datadog context that won against a conflicting W3C context.
Type Aliases§
- Datadog
ApmError - Service-prefixed alias of
Error. - RawDatadog
Span - A raw Datadog span object (any Datadog span shape) decoded from JSON.