### Getting Started with Traces in Rust Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/lib.rs.html Demonstrates how to get a tracer, start a new span, set attributes, and end the span to export trace data. Ensure the 'trace' feature is enabled. ```rust # #[cfg(feature = "trace")] # { use opentelemetry::{global, trace::{Span, Tracer}, KeyValue}; // get a tracer from a provider let tracer = global::tracer("my_service"); // start a new span let mut span = tracer.start("my_span"); // set some attributes span.set_attribute(KeyValue::new("http.client_ip", "83.164.160.102")); // perform some more work... // end or drop the span to export span.end(); # } ``` -------------------------------- ### Application Code Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/mod.rs.html Demonstrates how to initialize a TracerProvider and get a named tracer instance in application code. ```APIDOC ## Application Code Example ### Description In application code, you typically initialize a `TracerProvider` once at application startup and then retrieve named `Tracer` instances as needed. ### Code ```rust use opentelemetry::trace::{Tracer, noop::NoopTracerProvider}; use opentelemetry::global; fn init_tracer() { // Swap this no-op provider for your tracing service of choice (jaeger, zipkin, etc) let provider = NoopTracerProvider::new(); // Configure the global `TracerProvider` singleton when your app starts // (there is a no-op default if this is not set by your application) let _ = global::set_tracer_provider(provider); } fn do_something_tracked() { // Then you can get a named tracer instance anywhere in your codebase. let tracer = global::tracer("my-component"); tracer.in_span("doing_work", |cx| { // Traced app logic here... }); } // in main or other app start init_tracer(); do_something_tracked(); ``` ``` -------------------------------- ### Library Code Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/mod.rs.html Shows how a library can use the global TracerProvider to get a tracer and create spans. ```APIDOC ## Library Code Example ### Description In library code, you access the globally configured `TracerProvider` to obtain a `Tracer` specific to your library's instrumentation scope. ### Code ```rust use opentelemetry::{global, trace::{Span, Tracer, TracerProvider}}; use opentelemetry::InstrumentationScope; use std::sync::Arc; fn my_library_function() { // Use the global tracer provider to get access to the user-specified // tracer configuration let tracer_provider = global::tracer_provider(); // Get a tracer for this library let scope = InstrumentationScope::builder("my_name") .with_version(env!("CARGO_PKG_VERSION")) .with_schema_url("https://opentelemetry.io/schemas/1.17.0") .build(); let tracer = tracer_provider.tracer_with_scope(scope); // Create spans let mut span = tracer.start("doing_work"); // Do work... // End the span span.end(); } ``` ``` -------------------------------- ### Initialize Global Tracer Provider (Application) Source: https://docs.rs/opentelemetry/latest/opentelemetry/global/index.html Applications configure their tracer by installing a trace pipeline or calling `set_tracer_provider`. This example shows how to set a custom provider, defaulting to a no-op provider if not explicitly set. ```rust use opentelemetry::trace::{Tracer, noop::NoopTracerProvider}; use opentelemetry::global; fn init_tracer() { // Swap this no-op provider for your tracing service of choice (jaeger, zipkin, etc) let provider = NoopTracerProvider::new(); // Configure the global `TracerProvider` singleton when your app starts // (there is a no-op default if this is not set by your application) let _ = global::set_tracer_provider(provider); } fn do_something_tracked() { // Then you can get a named tracer instance anywhere in your codebase. let tracer = global::tracer("my-component"); tracer.in_span("doing_work", |cx| { // Traced app logic here... }); } // in main or other app start init_tracer(); do_something_tracked(); ``` -------------------------------- ### Get Tracer and Create Spans (Library Code) Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/index.html In library code, use the global tracer provider to get a tracer for your library. Create spans using `start` and end them with `span.end()`. ```rust use opentelemetry::{global, trace::{Span, Tracer, TracerProvider}}; use opentelemetry::InstrumentationScope; use std::sync::Arc; fn my_library_function() { // Use the global tracer provider to get access to the user-specified // tracer configuration let tracer_provider = global::tracer_provider(); // Get a tracer for this library let scope = InstrumentationScope::builder("my_name") .with_version(env!("CARGO_PKG_VERSION")) .with_schema_url("https://opentelemetry.io/schemas/1.17.0") .build(); let tracer = tracer_provider.tracer_with_scope(scope); // Create spans let mut span = tracer.start("doing_work"); // Do work... // End the span span.end(); } ``` -------------------------------- ### Example Usage of OpenTelemetry Metrics API in Rust Source: https://docs.rs/opentelemetry/latest/index.html Demonstrates how to get a meter, create a counter and an observable counter, and record measurements with attributes. Ensure the 'metrics' feature flag is enabled. ```rust use opentelemetry::{global, KeyValue}; // Get a meter from a provider. let meter = global::meter("my_service"); // Create an instrument (in this case, a Counter). let counter = meter.u64_counter("request.count").build(); // Record a measurement by passing the value and a set of attributes. counter.add(1, &[KeyValue::new("http.client_ip", "83.164.160.102")]); // Create an ObservableCounter and register a callback that reports the measurement. let _observable_counter = meter .u64_observable_counter("bytes_received") .with_callback(|observer| { observer.observe( 100, &[ KeyValue::new("protocol", "udp"), ], ) }) .build(); ``` -------------------------------- ### Get Tracer Instance in Library Source: https://docs.rs/opentelemetry/latest/opentelemetry/global/index.html Libraries can use the global tracer without explicit setup, as end-users are responsible for configuring the global tracer provider. This example demonstrates obtaining a named tracer with version and schema URL. ```rust use std::sync::Arc; use opentelemetry::trace::Tracer; use opentelemetry::global; use opentelemetry::InstrumentationScope; pub fn my_traced_library_function() { // End users of your library will configure their global tracer provider // so you can use the global tracer without any setup let scope = InstrumentationScope::builder("my_library-name") .with_version(env!("CARGO_PKG_VERSION")) .with_schema_url("https://opentelemetry.io/schemas/1.17.0") .build(); let tracer = global::tracer_with_scope(scope); tracer.in_span("doing_library_work", |cx| { // Traced library logic here... }); } ``` -------------------------------- ### Creating and Managing Spans with Tracer Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.Tracer.html Demonstrates how to create a tracer, start a parent span, and then start a child span with explicit context and attributes. The child span is configured with a specific kind and attributes. ```rust use opentelemetry::{global, trace::{Span, SpanKind, Tracer, TraceContextExt}, Context, KeyValue}; fn my_function() { let tracer = global::tracer("my-component"); // Create a parent context let parent = tracer.start("parent-span"); let parent_cx = Context::current_with_span(parent); // start an active span with explicit parent context and span configuration tracer.in_span_with_builder_and_context( tracer.span_builder("child-span") .with_kind(SpanKind::Client) .with_attributes(vec![KeyValue::new("key", "value")]), &parent_cx, |_cx| { // child span is active here with configured attributes } ) } ``` -------------------------------- ### Start Span with Tracer Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Builds and starts a span using the provided tracer and the current context. This is a convenience method for starting a span with implicit parent context. ```rust pub fn start(self, tracer: &T) -> T::Span { Context::map_current(|cx| tracer.build_with_context(self, cx)) } ``` -------------------------------- ### i64 Gauge Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Demonstrates recording a value for an i64 Gauge with attributes. ```rust let gauge = meter.i64_gauge("my_gauge").build(); gauge.record( -10, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### f64 Gauge Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Demonstrates recording a value for an f64 Gauge with attributes. ```rust let gauge = meter.f64_gauge("my_gauge").build(); gauge.record( 12.5, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### u64 Gauge Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Demonstrates recording a value for a u64 Gauge with attributes. ```rust let gauge = meter.u64_gauge("my_gauge").build(); gauge.record( 101, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### Start and End a Span in Rust Source: https://docs.rs/opentelemetry/latest/index.html Demonstrates how to obtain a tracer, start a new span, set attributes, and end the span. Ensure the 'opentelemetry' crate is added as a dependency. ```rust use opentelemetry::{global, trace::{Span, Tracer}, KeyValue}; // get a tracer from a provider let tracer = global::tracer("my_service"); // start a new span let mut span = tracer.start("my_span"); // set some attributes span.set_attribute(KeyValue::new("http.client_ip", "83.164.160.102")); // perform some more work... // end or drop the span to export span.end(); ``` -------------------------------- ### Start Span with Default Context Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Starts a new span using the tracer's `start` method. This method implicitly uses the current thread's context to determine the parent span. If no active span is found in the current context, the new span becomes a root span. ```rust fn start(&self, name: T) -> Self::Span where T: Into>, { Context::map_current(|cx| self.start_with_context(name, cx)) } ``` -------------------------------- ### i64 UpDownCounter Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Demonstrates how to create and add values to an i64 UpDownCounter with attributes. ```rust let updown_i64_counter = meter.i64_up_down_counter("my_updown_i64_counter").build(); updown_i64_counter.add( -10, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### f64 Histogram Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Demonstrates recording a value for an f64 Histogram with attributes. ```rust let f64_histogram = meter.f64_histogram("my_f64_histogram").build(); f64_histogram.record( 10.5, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### Initialize Tracer Provider in Application Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/mod.rs.html Configure the global `TracerProvider` singleton when your application starts. Swap the `NoopTracerProvider` for your desired tracing service implementation. ```rust use opentelemetry::trace::{Tracer, noop::NoopTracerProvider}; use opentelemetry::global; fn init_tracer() { // Swap this no-op provider for your tracing service of choice (jaeger, zipkin, etc) let provider = NoopTracerProvider::new(); // Configure the global `TracerProvider` singleton when your app starts // (there is a no-op default if this is not set by your application) let _ = global::set_tracer_provider(provider); } fn do_something_tracked() { // Then you can get a named tracer instance anywhere in your codebase. let tracer = global::tracer("my-component"); tracer.in_span("doing_work", |cx| { // Traced app logic here... }); } // in main or other app start init_tracer(); do_something_tracked(); ``` -------------------------------- ### u64 Histogram Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Demonstrates recording a value for a u64 Histogram with attributes. ```rust let u64_histogram = meter.u64_histogram("my_u64_histogram").build(); u64_histogram.record( 12, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### Setup Function for Tests Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/propagation/composite.rs.html Initializes a default context and enriches it with a test span and baggage for use in propagator tests. ```rust fn setup() -> Context { let mut cx = Context::default(); cx = cx.with_span(TestSpan(SpanContext::new( TraceId::from(1), SpanId::from(11), TraceFlags::default(), true, TraceState::default(), ))); // setup for baggage propagator cx.with_baggage(vec![KeyValue::new("baggagekey", "value")]) } ``` -------------------------------- ### i64 Observable Gauge Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Shows how to create an observable i64 Gauge with a callback to observe values and attributes. ```rust let _observable_i64_gauge = meter .i64_observable_gauge("my_i64_gauge") .with_description("An observable gauge set to 1") .with_unit("myunit") .with_callback(|observer| { observer.observe( 1, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ) }) .build(); ``` -------------------------------- ### SpanBuilder Usage Examples Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/struct.SpanBuilder.html Demonstrates how to use SpanBuilder to create and configure spans, either directly or using the builder pattern. ```APIDOC ## SpanBuilder `SpanBuilder` allows span attributes to be configured before the span has started. ```rust use opentelemetry::{ global, trace::{TracerProvider, SpanBuilder, SpanKind, Tracer}, }; let tracer = global::tracer("example-tracer"); // The builder can be used to create a span directly with the tracer let _span = tracer.build(SpanBuilder { name: "example-span-name".into(), span_kind: Some(SpanKind::Server), ..Default::default() }); // Or used with builder pattern let _span = tracer .span_builder("example-span-name") .with_kind(SpanKind::Server) .start(&tracer); ``` ``` -------------------------------- ### f64 UpDownCounter Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Demonstrates how to create and add values to an f64 UpDownCounter with attributes. ```rust let updown_f64_counter = meter.f64_up_down_counter("my_updown_f64_counter").build(); updown_f64_counter.add( -10.67, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### f64 Observable Gauge Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Shows how to create an observable f64 Gauge with a callback to observe values and attributes. ```rust let _observable_f64_gauge = meter .f64_observable_gauge("my_f64_gauge") .with_description("An observable gauge set to 1.0") .with_unit("myunit") .with_callback(|observer| { observer.observe( 1.0, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ) }) .build(); ``` -------------------------------- ### Example: in_span_with_builder_and_context Usage Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Demonstrates how to create a child span with explicit parent context and span configuration using `in_span_with_builder_and_context`. ```rust fn my_function() { let tracer = global::tracer("my-component"); // Create a parent context let parent = tracer.start("parent-span"); let parent_cx = Context::current_with_span(parent); // start an active span with explicit parent context and span configuration tracer.in_span_with_builder_and_context( tracer.span_builder("child-span") .with_kind(SpanKind::Client) .with_attributes(vec![KeyValue::new("key", "value")]), &parent_cx, |_cx| { // child span is active here with configured attributes } ) } ``` -------------------------------- ### Start Span with SpanBuilder and Context Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Starts a new span as a child of a provided parent context, configuring it with a SpanBuilder and executing a closure within its active context. ```rust fn in_span_with_builder_and_context( &self, builder: SpanBuilder, parent_cx: &Context, f: F, ) -> T where F: FnOnce(Context) -> T, Self::Span: Send + Sync + 'static, { let span = self.build_with_context(builder, parent_cx); let cx = parent_cx.with_span(span); let _guard = cx.clone().attach(); f(cx) } ``` -------------------------------- ### u64 Observable Gauge Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Shows how to create an observable u64 Gauge with a callback to observe values and attributes. ```rust let _observable_u64_gauge = meter .u64_observable_gauge("my_u64_gauge") .with_description("An observable gauge set to 1") .with_unit("myunit") .with_callback(|observer| { observer.observe( 1, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ) }) .build(); ``` -------------------------------- ### Start Span with Tracer and Explicit Context Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Builds and starts a span using the provided tracer and an explicit parent context. Use this when you need to control the parent span explicitly. ```rust pub fn start_with_context(self, tracer: &T, parent_cx: &Context) -> T::Span { tracer.build_with_context(self, parent_cx) } ``` -------------------------------- ### Build Span from Builder Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Starts a span using a pre-configured SpanBuilder and the current context. This method is a convenient way to start a span with custom attributes. ```rust fn build(&self, builder: SpanBuilder) -> Self::Span { Context::map_current(|cx| self.build_with_context(builder, cx)) } ``` -------------------------------- ### Start and Use an Active Span Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/context.rs.html Demonstrates how to start an active span within a component and access it in nested function calls. Ensure the global tracer is initialized before use. ```rust /// fn my_function() { /// // start an active span in one function /// global::tracer("my-component").in_span("span-name", |_cx| { /// // anything happening in functions we call can still access the active span... /// my_other_function(); /// }) /// } /// /// fn my_other_function() { /// // call methods on the current span from /// get_active_span(|span| { /// span.add_event("An event!", vec![KeyValue::new("happened", true)]); /// }) /// } ``` -------------------------------- ### build_with_context Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.Tracer.html Starts a span from a SpanBuilder with a parent context. ```APIDOC ## build_with_context ### Description Start a span from a `SpanBuilder` with a parent context. ### Method ```rust fn build_with_context( &self, builder: SpanBuilder, parent_cx: &Context, ) -> Self::Span; ``` ``` -------------------------------- ### Build Span Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Starts a new span using a configured SpanBuilder and the current context. ```APIDOC ## build ### Description Starts a [`Span`] from a [`SpanBuilder`] using the current context. ### Method Signature `fn build(&self, builder: SpanBuilder) -> Self::Span` ### Parameters - `builder` (SpanBuilder): The configured SpanBuilder to create the span from. ``` -------------------------------- ### Build a Span from a SpanBuilder Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.Tracer.html Starts a `Span` using a pre-configured `SpanBuilder`. This method is useful when you need to set various attributes like span kind, events, or attributes before starting the span. ```APIDOC ## fn build(&self, builder: SpanBuilder) -> Self::Span ### Description Creates and starts a new `Span` based on the configuration provided in the `SpanBuilder`. ### Parameters - **builder** (SpanBuilder): The `SpanBuilder` containing the desired configuration for the span. ``` -------------------------------- ### i64 Observable UpDownCounter Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Shows how to create an observable i64 UpDownCounter with a callback to observe values and attributes. ```rust let _observable_updown_i64_counter = meter .i64_observable_up_down_counter("my_observable_i64_updown_counter") .with_description("My observable updown counter example") .with_unit("myunit") .with_callback(|observer| { observer.observe( 100, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ) }) .build(); ``` -------------------------------- ### f64 Observable UpDownCounter Example Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/meter.rs.html Shows how to create an observable f64 UpDownCounter with a callback to observe values and attributes. ```rust let _observable_updown_f64_counter = meter .f64_observable_up_down_counter("my_observable_f64_updown_counter") .with_description("My observable updown counter example") .with_unit("myunit") .with_callback(|observer| { observer.observe( 100.0, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ) }) .build(); ``` -------------------------------- ### Box Conversion Example Source: https://docs.rs/opentelemetry/latest/opentelemetry/metrics/type.Callback.html Demonstrates converting a value into a Box using the From trait. This conversion allocates on the heap. ```rust let x = 5; let boxed = Box::new(5); assert_eq!(Box::from(x), boxed); ``` -------------------------------- ### Create and Use a Counter Instrument (Metrics) Source: https://docs.rs/opentelemetry/latest/opentelemetry/global/index.html Applications and libraries can obtain a meter from the global meter provider to create instruments. This example shows creating and using a `u64_counter` and recording measurements with attributes. ```rust use opentelemetry::metrics::{Meter}; use opentelemetry::{global, KeyValue}; fn do_something_instrumented() { let meter = global::meter("my-component"); // It is recommended to reuse the same counter instance for the // lifetime of the application let counter = meter.u64_counter("my_counter").build(); // record measurements counter.add(1, &[KeyValue::new("mykey", "myvalue")]); } } ``` -------------------------------- ### TraceId Examples Source: https://docs.rs/opentelemetry/latest/opentelemetry/struct.TraceId.html Demonstrates the usage of `TraceId::from_hex` for valid and invalid hexadecimal string inputs. ```rust use opentelemetry::trace::TraceId; assert!(TraceId::from_hex("42").is_ok()); assert!(TraceId::from_hex("58406520a006649127e371903a2de979").is_ok()); assert!(TraceId::from_hex("not_hex").is_err()); ``` -------------------------------- ### Context Creation and Value Management Source: https://docs.rs/opentelemetry/latest/opentelemetry/context/struct.Context.html Demonstrates how to create a new context, add values to it, and retrieve values by type. It also shows how to create a new context based on an existing one with additional values. ```APIDOC ## Context Creation and Value Management ### Description Demonstrates how to create a new context, add values to it, and retrieve values by type. It also shows how to create a new context based on an existing one with additional values. ### Method - `Context::new()`: Creates a new empty context. - `with_value(&self, value: T) -> Self`: Returns a copy of the context with the new value included. - `get(&self) -> Option<&T>`: Returns a reference to the entry for the corresponding value type. ### Example ```rust use opentelemetry::Context; // Given some value types defined in your application #[derive(Debug, PartialEq)] struct ValueA(&'static str); #[derive(Debug, PartialEq)] struct ValueB(u64); // You can create and attach context with the first value set to "a" let _guard = Context::new().with_value(ValueA("a")).attach(); // And create another context based on the fist with a new value let all_current_and_b = Context::current_with_value(ValueB(42)); // The second context now contains all the current values and the addition assert_eq!(all_current_and_b.get::(), Some(&ValueA("a"))); assert_eq!(all_current_and_b.get::(), Some(&ValueB(42))); ``` ### Example: Retrieving Values ```rust use opentelemetry::Context; // Given some value types defined in your application #[derive(Debug, PartialEq)] struct ValueA(&'static str); #[derive(Debug, PartialEq)] struct MyUser(); let cx = Context::new().with_value(ValueA("a")); // Values can be queried by type assert_eq!(cx.get::(), Some(&ValueA("a"))); // And return none if not yet set assert_eq!(cx.get::(), None); ``` ### Example: Creating a New Context with Additional Values ```rust use opentelemetry::Context; // Given some value types defined in your application #[derive(Debug, PartialEq)] struct ValueA(&'static str); #[derive(Debug, PartialEq)] struct ValueB(u64); // You can create a context with the first value set to "a" let cx_with_a = Context::new().with_value(ValueA("a")); // And create another context based on the fist with a new value let cx_with_a_and_b = cx_with_a.with_value(ValueB(42)); // The first context is still available and unmodified assert_eq!(cx_with_a.get::(), Some(&ValueA("a"))); assert_eq!(cx_with_a.get::(), None); // The second context now contains both values assert_eq!(cx_with_a_and_b.get::(), Some(&ValueA("a"))); assert_eq!(cx_with_a_and_b.get::(), Some(&ValueB(42))); ``` ``` -------------------------------- ### start Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.Tracer.html Starts a new span with the given name. The span will be automatically ended when it goes out of scope. ```APIDOC ## start ### Description Starts a new span with the given name. The span will be automatically ended when it goes out of scope. ### Method ```rust fn start(&self, name: T) -> Self::Span where T: Into>; ``` ### Example ```rust use opentelemetry::{global, trace::Tracer}; let tracer = global::tracer("my-component"); let span = tracer.start("foo"); // ... work ... // span is automatically ended when it goes out of scope ``` ``` -------------------------------- ### Creating Loggers with LoggerProvider Source: https://docs.rs/opentelemetry/latest/opentelemetry/logs/trait.LoggerProvider.html Demonstrates how to obtain Logger instances from a LoggerProvider. Use `logger` for application-level loggers and `logger_with_scope` for library-level loggers with detailed metadata. ```rust use opentelemetry::InstrumentationScope; use opentelemetry::logs::LoggerProvider; use opentelemetry_sdk::logs::SdkLoggerProvider; let provider = SdkLoggerProvider::builder().build(); // logger used in applications/binaries let logger = provider.logger("my_app"); // logger used in libraries/crates that optionally includes version and schema url let scope = InstrumentationScope::builder(env!("CARGO_PKG_NAME")) .with_version(env!("CARGO_PKG_VERSION")) .with_schema_url("https://opentelemetry.io/schemas/1.0.0") .build(); let logger = provider.logger_with_scope(scope); ``` -------------------------------- ### Start Span with Name for NoopTracer Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/noop/struct.NoopTracer.html Starts a new `Span` with a given name. This is a no-op operation. ```rust fn start(&self, name: T) -> Self::Span where T: Into> ``` -------------------------------- ### Start a new span with context Source: https://docs.rs/opentelemetry/latest/opentelemetry/global/struct.BoxedTracer.html Starts a new span with the given name and a specific parent context. ```rust fn start_with_context(&self, name: T, parent_cx: &Context) -> Self::Span where T: Into>, ``` -------------------------------- ### Context Management and Usage Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/context.rs.html Demonstrates how to create, manage, and retrieve values from the execution-scoped context. ```APIDOC ## Context API ### Description The `Context` type represents an immutable, execution-scoped collection of values. It is used to propagate execution-scoped values across API boundaries and between logically associated execution units. ### Methods - `Context::new()`: Creates an empty `Context`. - `Context::current()`: Returns an immutable snapshot of the current thread's context. - `Context::with_value(value)`: Creates a new context with the given value added. - `Context::attach()`: Attaches the current context to the thread, returning a `ContextGuard`. ### Examples ```rust use opentelemetry::Context; // Application-specific `a` and `b` values #[derive(Debug, PartialEq)] struct ValueA(&'static str); #[derive(Debug, PartialEq)] struct ValueB(u64); // Create a new context and add a value let ctx_with_a = Context::new().with_value(ValueA("a")); // Attach the context to the current thread let _guard = ctx_with_a.attach(); // Get the current context and retrieve values let current = Context::current(); assert_eq!(current.get::(), Some(&ValueA("a"))); assert_eq!(current.get::(), None); // Create a new context based on the current one and add another value let ctx_with_b = Context::current_with_value(ValueB(42)); let _inner_guard = ctx_with_b.attach(); // Both values are now available let inner_current = Context::current(); assert_eq!(inner_current.get::(), Some(&ValueA("a"))); assert_eq!(inner_current.get::(), Some(&ValueB(42))); // When the inner guard is dropped, the context reverts to the outer one // (This happens automatically when `_inner_guard` goes out of scope) let outer_current = Context::current(); assert_eq!(outer_current.get::(), Some(&ValueA("a"))); assert_eq!(outer_current.get::(), None); ``` ### Behavior During Context Drop When `Context::current()` is called from within a `Drop` implementation that is triggered by a `ContextGuard` being dropped (e.g., when a `Span` is dropped as part of context cleanup), this function returns whatever context happens to be current after the guard is popped, not the context being dropped. This is important because contexts can be activated in any order and are detached in LIFO order. ``` -------------------------------- ### Start a new span Source: https://docs.rs/opentelemetry/latest/opentelemetry/global/struct.BoxedTracer.html Starts a new span with the given name. The span will be created with the current context. ```rust fn start(&self, name: T) -> Self::Span where T: Into>, ``` -------------------------------- ### Get TypeId of KeyValueMetadata Source: https://docs.rs/opentelemetry/latest/opentelemetry/baggage/struct.KeyValueMetadata.html Gets the TypeId of the KeyValueMetadata. This is part of the Any trait implementation, used for dynamic type checking. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Start Span with Name and Context for NoopTracer Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/noop/struct.NoopTracer.html Starts a new `Span` with a given name and a specific `Context`. This is a no-op operation. ```rust fn start_with_context(&self, name: T, parent_cx: &Context) -> Self::Span where T: Into> ``` -------------------------------- ### Get Global Tracer Provider Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/global/trace.rs.html Get a reference to the globally configured `TracerProvider` instance. This function ensures thread-safe access to the singleton. ```rust static GLOBAL_TRACER_PROVIDER: OnceLock> = OnceLock::new(); #[inline] fn global_tracer_provider() -> &'static RwLock { GLOBAL_TRACER_PROVIDER } ``` -------------------------------- ### start_with_context Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.Tracer.html Starts a new span with the given name and associates it with the provided parent context. The span will be automatically ended when it goes out of scope. ```APIDOC ## start_with_context ### Description Starts a new span with the given name and associates it with the provided parent context. The span will be automatically ended when it goes out of scope. ### Method ```rust fn start_with_context(&self, name: T, parent_cx: &Context) -> Self::Span where T: Into>; ``` ### Example ```rust use opentelemetry::{global, trace::Tracer, Context}; let tracer = global::tracer("my-component"); let parent_cx = Context::current(); let span = tracer.start_with_context("bar", &parent_cx); // ... work ... // span is automatically ended when it goes out of scope ``` ``` -------------------------------- ### Test HashMap Extractor Get Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/propagation/mod.rs.html Verifies the case-insensitive extraction of a value from a HashMap using the Extractor trait's get method. ```rust #[test] fn hash_map_get() { let mut carrier = HashMap::new(); carrier.set("headerName", "value".to_string()); assert_eq!( Extractor::get(&carrier, "HEADERNAME"), Some("value"), "case insensitive extraction" ); } ``` -------------------------------- ### Building Async Instruments with Macros Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/metrics/instruments/mod.rs.html The `build_async_instrument!` macro simplifies the creation of specific async instrument types. Call the `build()` method on the configured builder to finalize instrument creation. Invalid configurations result in a no-op instrument and logged errors. ```rust macro_rules! build_async_instrument { ($name:ident, $inst:ty, $measurement:ty) => { impl<'a> AsyncInstrumentBuilder<'a, $inst, $measurement> { #[doc = concat!("Validates the instrument configuration and creates a new `", stringify!($inst), "`.")] /// In case of invalid configuration, a no-op instrument is returned /// and an error is logged using internal logging. pub fn build(self) -> $inst { self.instrument_provider.$name(self) } } }; } build_async_instrument!(u64_observable_counter, ObservableCounter, u64); build_async_instrument!(f64_observable_counter, ObservableCounter, f64); build_async_instrument!(u64_observable_gauge, ObservableGauge, u64); build_async_instrument!(f64_observable_gauge, ObservableGauge, f64); build_async_instrument!(i64_observable_gauge, ObservableGauge, i64); build_async_instrument!( i64_observable_up_down_counter, ObservableUpDownCounter, i64 ); build_async_instrument!( f64_observable_up_down_counter, ObservableUpDownCounter, f64 ); ``` -------------------------------- ### Get a Meter by Name Source: https://docs.rs/opentelemetry/latest/opentelemetry/metrics/trait.MeterProvider.html Use `meter` to get a Meter with a given name. This is suitable for applications or crates where a simple name is sufficient. ```rust use opentelemetry::{global, metrics::MeterProvider}; use opentelemetry::KeyValue; let provider = global::meter_provider(); // meter used in applications let meter = provider.meter("my_app"); ``` -------------------------------- ### Start Span with Context Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Starts a new span with a given name and parent context. This is useful when you need to explicitly define the parent of a new span. ```rust fn start_with_context(&self, name: T, parent_cx: &Context) -> Self::Span where T: Into>, { self.build_with_context(SpanBuilder::from_name(name), parent_cx) } ``` -------------------------------- ### Start Span with Context Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Starts a new span with a given name and parent context. This is useful for creating child spans explicitly linked to a parent trace. ```APIDOC ## start_with_context ### Description Starts a new span with a given name and parent context. ### Method Signature `fn start_with_context(&self, name: T, parent_cx: &Context) -> Self::Span` ### Parameters - `name` (T): The name of the span. Can be any type that can be converted into a static string. - `parent_cx` (&Context): The parent context to which this span will be linked. ``` -------------------------------- ### CloneToUninit (Nightly Experimental) Source: https://docs.rs/opentelemetry/latest/opentelemetry/logs/enum.AnyValue.html Provides experimental functionality to clone data into uninitialized memory. ```APIDOC ### impl CloneToUninit for T #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ``` -------------------------------- ### Get Tracer by Name Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.TracerProvider.html Retrieve a Tracer instance using a simple name, typically the application or library name. This is the most common way to get a tracer for general use. ```rust use opentelemetry::{global, trace::TracerProvider}; use opentelemetry::KeyValue; let provider = global::tracer_provider(); // tracer used in applications/binaries let tracer = provider.tracer("my_app"); ``` -------------------------------- ### Box::new_uninit Source: https://docs.rs/opentelemetry/latest/opentelemetry/metrics/type.Callback.html Constructs a new box with uninitialized contents. ```APIDOC ## Box::new_uninit ### Description Constructs a new box with uninitialized contents. ### Method `Box::new_uninit() -> Box>` ### Request Example ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### Get a named Meter Source: https://docs.rs/opentelemetry/latest/opentelemetry/global/fn.meter.html Use this function to get a `Meter` instance from the global `MeterProvider`. This is a shortcut for `global::meter_provider().meter(name)`. Ensure the `metrics` feature is enabled. ```rust pub fn meter(name: &'static str) -> Meter ``` -------------------------------- ### SpanBuilder Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html A struct used to configure and build spans before they are started. It allows setting various span properties like name, kind, start time, attributes, events, and links. ```APIDOC ## SpanBuilder ### Description Allows span attributes to be configured before the span has started. ### Fields * `span_kind`: `Option` - The kind of the span (e.g., Server, Client). * `name`: `Cow<'static, str>` - The name of the span. * `start_time`: `Option` - The start time of the span. * `attributes`: `Option>` - A vector of key-value attributes for the span. Duplicate keys are allowed. * `events`: `Option>` - A vector of events to be recorded on the span. * `links`: `Option>` - A vector of links to other spans. ``` ```APIDOC ## SpanBuilder Methods ### from_name>>(name: T) -> Self Creates a new `SpanBuilder` initialized with the given span name. ### with_kind(self, span_kind: SpanKind) -> Self Assigns a `SpanKind` to the `SpanBuilder`. ### with_start_time>(self, start_time: T) -> Self Assigns a start time to the `SpanBuilder`. ### with_attributes(self, attributes: Vec) -> Self Assigns span attributes from an iterable. Providing duplicate keys will result in multiple attributes with the same key, as there is no de-duplication performed. ``` -------------------------------- ### Create a new Key Source: https://docs.rs/opentelemetry/latest/opentelemetry/struct.Key.html Demonstrates creating a Key from a static string, an owned String, and a reference-counted string (Arc). ```rust use opentelemetry::Key; use std::sync::Arc; let key1 = Key::new("my_static_str"); let key2 = Key::new(String::from("my_owned_string")); let key3 = Key::new(Arc::from("my_ref_counted_str")); ``` -------------------------------- ### Start a new Span Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.Tracer.html Starts a new span. By default, the currently active span is set as the new span's parent. A span represents a single operation within a trace. -------------------------------- ### Build ObservableCounter Source: https://docs.rs/opentelemetry/latest/opentelemetry/metrics/struct.AsyncInstrumentBuilder.html Creates a new `ObservableCounter` instrument. Invalid configurations result in a no-op instrument and logged errors. ```rust pub fn build(self) -> ObservableCounter ``` -------------------------------- ### Get Tracer and Create Spans in Library Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/mod.rs.html In library code, use the global tracer provider to get a tracer with specific instrumentation scope details. Create and end spans manually. ```rust use opentelemetry::{global, trace::{Span, Tracer, TracerProvider}}; use opentelemetry::InstrumentationScope; use std::sync::Arc; fn my_library_function() { // Use the global tracer provider to get access to the user-specified // tracer configuration let tracer_provider = global::tracer_provider(); // Get a tracer for this library let scope = InstrumentationScope::builder("my_name") .with_version(env!("CARGO_PKG_VERSION")) .with_schema_url("https://opentelemetry.io/schemas/1.17.0") .build(); let tracer = tracer_provider.tracer_with_scope(scope); // Create spans let mut span = tracer.start("doing_work"); // Do work... // End the span span.end(); } ``` -------------------------------- ### Create and Use f64 Gauge Source: https://docs.rs/opentelemetry/latest/opentelemetry/metrics/struct.Meter.html Illustrates creating and recording a 64-bit floating-point gauge. This allows for tracking fractional values that represent a current state. ```rust // f64 Gauge let gauge = meter.f64_gauge("my_gauge").build(); gauge.record( 12.5, &[ KeyValue::new("mykey1", "myvalue1"), KeyValue::new("mykey2", "myvalue2"), ], ); ``` -------------------------------- ### Start a new Span with a specific context Source: https://docs.rs/opentelemetry/latest/opentelemetry/trace/trait.Tracer.html Starts a new `Span` with a given context. If this context contains a span, the newly created span will be a child of that span. This allows for explicit control over span parenting. ```APIDOC ## fn start_with_context(&self, name: T, parent_cx: &Context) -> Self::Span where T: Into>, ### Description Starts a new `Span` with the given name and explicitly sets its parent using the provided `Context`. ### Parameters - **name** (T): The name of the span. Must be convertible into `Cow<'static, str>`. - **parent_cx** (&Context): The context to use for determining the parent span. ``` -------------------------------- ### SpanBuilder Initialization and Usage Source: https://docs.rs/opentelemetry/latest/src/opentelemetry/trace/tracer.rs.html Shows how to initialize a `SpanBuilder` directly or using a builder pattern to configure span properties like name, kind, and attributes before starting a span. ```rust let tracer = global::tracer("example-tracer"); // The builder can be used to create a span directly with the tracer let _span = tracer.build(SpanBuilder { name: "example-span-name".into(), span_kind: Some(SpanKind::Server), ..Default::default() }); // Or used with builder pattern let _span = tracer .span_builder("example-span-name") .with_kind(SpanKind::Server) .start(&tracer); ``` -------------------------------- ### Build ObservableGauge Source: https://docs.rs/opentelemetry/latest/opentelemetry/metrics/struct.AsyncInstrumentBuilder.html Builds an `ObservableGauge` instrument. Invalid configurations lead to a no-op instrument and logged errors. ```rust pub fn build(self) -> ObservableGauge ``` -------------------------------- ### Get raw pointer to Box contents (nightly) Source: https://docs.rs/opentelemetry/latest/opentelemetry/metrics/type.Callback.html Use `Box::as_ptr` to get a raw pointer to the `Box`'s contents. The `Box` must outlive the pointer, and the memory should not be written to via this pointer. This API is experimental and requires the `box_as_ptr` feature. ```rust #![feature(box_as_ptr)] unsafe { let mut v = Box::new(0); let ptr1 = Box::as_ptr(&v); let ptr2 = Box::as_mut_ptr(&mut v); let _val = ptr2.read(); // No write to this memory has happened yet, so `ptr1` is still valid. let _val = ptr1.read(); // However, once we do a write... ptr2.write(1); // ... `ptr1` is no longer valid. // This would be UB: let _val = ptr1.read(); } ```