Instrument your Rust application with OpenTelemetry
This walkthrough shows how to add observability to your Rust application using the OpenTelemetry Rust libraries and tools.
Feature | Supported |
---|---|
Automatic Instrumentation | No |
Automatic OneAgent Ingestion | No |
Prerequisites
- Dynatrace version 1.222+
- For tracing, W3C Trace Context is enabled
- Go to Settings > Preferences > OneAgent features.
- Turn on Send W3C Trace Context HTTP headers.
Get the Dynatrace access details
Determine the API base URL
For details on how to assemble the base OTLP endpoint URL, see Export with OTLP. The URL should end in /api/v2/otlp
.
Get API access token
The access token for ingesting traces, logs, and metrics can be generated under Access Tokens.
Export with OTLP has more details on the format and the necessary access scopes.
Set up OpenTelemetry
-
Add the current version (
[VERSION]
) of the following crates to yourCargo.toml
file.opentelemetry = { version = "[VERSION]", features = ["trace", "metrics"] }opentelemetry_sdk = { version = "[VERSION]" , features = ["rt-tokio"] }opentelemetry-otlp = { version = "[VERSION]", features = ["http-proto", "reqwest-client", "reqwest-rustls"] }opentelemetry-http = { version = "[VERSION]" }opentelemetry-semantic-conventions = { version = "[VERSION]" } -
Add the following
use
declarations.use std::collections::HashMap;use std::io::{BufRead, BufReader, Read};use opentelemetry::{global,trace::{Span, TraceContextExt, TraceError, Tracer},Context, KeyValue,};use opentelemetry_sdk::{runtime, trace as sdktrace, Resource};use opentelemetry_http::{HeaderExtractor, HeaderInjector};use opentelemetry_otlp::WithExportConfig;use opentelemetry_semantic_conventions as semcov; -
Add the following function to your startup file.
fn init_opentelemetry() -> Result<sdktrace::Tracer, TraceError> {// Helper function to read potentially available OneAgent datafn read_dt_metadata() -> Resource {fn read_single(path: &str, metadata: &mut Vec<KeyValue>) -> std::io::Result<()> {let mut file = std::fs::File::open(path)?;if path.starts_with("dt_metadata") {let mut name = String::new();file.read_to_string(&mut name)?;file = std::fs::File::open(name)?;}for line in BufReader::new(file).lines() {if let Some((k, v)) = line?.split_once('=') {metadata.push(KeyValue::new(k.to_string(), v.to_string()))}}Ok(())}let mut metadata = Vec::new();for name in ["dt_metadata_e617c525669e072eebe3d0f08212e8f2.properties","/var/lib/dynatrace/enrichment/dt_metadata.properties","/var/lib/dynatrace/enrichment/dt_host_metadata.properties"] {let _ = read_single(name, &mut metadata);}Resource::new(metadata)}// ===== GENERAL SETUP =====let DT_API_TOKEN = env::var("DT_API_TOKEN").unwrap(); // TODO: changelet DT_API_URL = env::var("DT_API_URL").unwrap();let mut map = HashMap::new();map.insert("Authorization".to_string(), format!("Api-Token {}", DT_API_TOKEN));let mut resource = Resource::new([KeyValue::new(semcov::resource::SERVICE_NAME, "rust-app") //TODO Replace with the name of your application]);resource = resource.merge(&read_dt_metadata());// ===== TRACING SETUP =====global::set_text_map_propagator(TraceContextPropagator::new());opentelemetry_otlp::new_pipeline().tracing().with_exporter(opentelemetry_otlp::new_exporter().http().with_endpoint(DT_API_URL).with_headers(map),).with_trace_config(sdktrace::config().with_resource(resource).with_sampler(sdktrace::Sampler::AlwaysOn),).install_batch(runtime::Tokio)} -
Configure the variables
DT_API_URL
andDT_API_TOKEN
ininit_opentelemetry()
for the Dynatrace URL and access token inotel.h
. -
Call
init_opentelemetry()
as early as possible in your startup code.
Instrument your application
Add tracing
-
First, we need to get a tracer object.
let tracer = global::tracer("my-tracer"); -
With
tracer
, we can now start new spans.let mut span = tracer.start("Call to /myendpoint");span.set_attribute(KeyValue::new("http.method", "GET"));span.set_attribute(KeyValue::new("net.protocol.version", "1.1"));// TODO: Your code goes herespan.end();In the above code, we:
Create a new span and name it "Call to /myendpoint"
- Add two attributes, following the semantic naming convention, specific to the action of this span: information on the HTTP method and version
- Add a
TODO
in place of the eventual business logic - Call the span's
end()
method to complete the span
Collect metrics
No example yet, as OpenTelemetry for Rust does not have stable support for metrics yet.
Connect logs
No example yet, as OpenTelemetry for Rust does not have stable support for logs yet.
Depending on the status of the OpenTelemetry SDK, the pre-release version may nonetheless already allow the ingestion of your logs.
Ensure context propagation optional
Context propagation is particularly important when network calls (for example, REST) are involved.
Extracting the context when receiving a request
For extracting information on an existing context, the following example defines the get_parent_context
function. That function is called when a request is received and gets passed the original HTTP request object.
It then calls the global get_text_map_propagator
function and uses the extract
function of the propagator object to fetch the provided context information from the headers and create a new context based on that.
This context is returned by get_parent_context
and allows us to continue the previous traces with our new spans.
//Method to extract the parent context from the requestfn get_parent_context(req: Request<Body>) -> Context {global::get_text_map_propagator(|propagator| {propagator.extract(&HeaderExtractor(req.headers()))})}async fn incoming_request(req: Request<Body>) -> Result<Response<Body>, Infallible> {let parent_cx = get_parent_context(req);let mut span = global::tracer("manual-server").start_with_context("my-server-span", &parent_cx); //TODO Replace with the name of your spanspan.set_attribute(KeyValue::new("my-server-key-1", "my-server-value-1")); //TODO Add attributes// TODO Your incoming_request code goes here}
Injecting the context when sending requests
The following example uses hyper to send an HTTP request. To inject the required propagation headers of our current context, the code instantiates a new hyper request and passes its headers to the inject_context
function.
Once the headers are added to our request, we can perform the HTTP call and the receiving endpoint will be able to continue the trace with the provided information.
async fn outgoing_request(context: Context,) -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {let client = Client::new();let span = global::tracer("manual-client").start_with_context("my-client-span", &context); //TODO Replace with the name of your spanlet cx = Context::current_with_span(span);let mut req = hyper::Request::builder().uri("<HTTP_URL>");//Method to inject the current context in the requestglobal::get_text_map_propagator(|propagator| {propagator.inject_context(&cx, &mut HeaderInjector(&mut req.headers_mut().unwrap()))});cx.span().set_attribute(KeyValue::new("my-client-key-1", "my-client-value-1")); //TODO Add attributes// TODO Your outgoing_request code goes here}
Configure data capture to meet privacy requirements optional
While Dynatrace automatically captures all OpenTelemetry attributes, only attribute values specified in the allowlist are stored and displayed in the Dynatrace web UI. This prevents accidental storage of personal data, so you can meet your privacy requirements and control the amount of monitoring data stored.
To view your custom attributes, you need to allow them in the Dynatrace web UI first. To learn how to configure attribute storage and masking, see Attribute redaction.
Verify data ingestion into Dynatrace
Once you have finished the instrumentation of your application, perform a couple of test actions to create and send demo traces, metrics, and logs and verify that they were correctly ingested into Dynatrace.
To do that for traces, go to Distributed Traces and select the Ingested traces tab. If you use OneAgent, select PurePaths instead.
For metrics and logs, go to Metrics or Logs or Logs & Events (latest Dynatrace).