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
- From the Dynatrace menu, 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 in your Dynatrace menu 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 = ["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, sdk::{propagation::TraceContextPropagator, trace as sdktrace, Resource}, trace::{Span, TraceContextExt, TraceError, Tracer}, metrics, Context, KeyValue, }; 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() { // Helper function to read potentially available OneAgent data fn 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", ] { let _ = read_single(name, &mut metadata); } Resource::new(metadata) } // ===== GENERAL SETUP ===== let DT_API_URL = ""; let DT_API_TOKEN = ""; resource = resource.merge(&read_dt_metadata()); let mut map = HashMap::new(); map.insert("Authorization".to_string(), ("Api-Token " + DT_API_TOKEN).to_string()); let mut resource = Resource::new(vec![ semcov::resource::SERVICE_NAME.string("rust-quickstart"), //TODO Replace with the name of your application semcov::resource::SERVICE_VERSION.string("1.0.1"), //TODO Replace with the version of your application ]); // ===== 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 + "/v1/traces") .with_headers(map), ) .with_trace_config( sdktrace::config() .with_resource(resource) .with_sampler(sdktrace::Sampler::AlwaysOn), ) .install_batch(opentelemetry::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 here span.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
OpenTelemetry metrics do not support export via HTTP yet.
Connect logs
OpenTelemetry logging is currently not yet available for Rust and is still under development.
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 request
fn 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 span
span.set_attribute(KeyValue::new("my-server-key-1", "my-server-value-1")); //TODO Add attributes
//Your 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 span
let cx = Context::current_with_span(span);
let mut req = hyper::Request::builder().uri("<HTTP_URL>");
//Method to inject the current context in the request
global::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
//Your code goes here
}
Configure data capture to meet privacy requirements optional
While Dynatrace automatically captures all OpenTelemetry resource and span 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 span attributes, you need to allow them in the Dynatrace web UI first.
- Span attributes: In the Dynatrace menu, go to Settings and select Server-side service monitoring > Span attributes.
- Resource attributes: In the Dynatrace menu, go to Settings and select Server-side service monitoring > Resource attributes.
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, in the Dynatrace menu, go to Distributed traces and select the Ingested traces tab. If you use OneAgent, select PurePaths instead.
Metrics and logs can be found under their respective entries at Observe and explore.