### Create Root and Explicit Child Spans in Rust Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This Rust example demonstrates how to initialize a root `Span` using `Span::root()` and subsequently create child `Span`s using `Span::enter_with_parent()`, establishing a direct parent-child relationship. It also includes the setup for `fastrace`'s `ConsoleReporter`. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fastrace::set_reporter(ConsoleReporter, Config::default()); { let root_span = Span::root("root", SpanContext::random()); { let child_span = Span::enter_with_parent("a child span", &root_span); // ... // child_span ends here. } // root_span ends here. } fastrace::flush(); ``` -------------------------------- ### Using fastrace `#[trace]` Macro for Function Tracing (Rust) Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This example illustrates the use of the `#[trace]` attribute macro to automatically instrument synchronous and asynchronous functions for tracing. It highlights that functions annotated with `#[trace]` must be called within the local context of an active Span for successful tracing. The snippet includes setup for a ConsoleReporter and demonstrates tracing both a regular function and an async function. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; use pollster::block_on; #[trace] fn do_something(i: u64) { std::thread::sleep(std::time::Duration::from_millis(i)); } #[trace] async fn do_something_async(i: u64) { futures_timer::Delay::new(std::time::Duration::from_millis(i)).await; } fastrace::set_reporter(ConsoleReporter, Config::default()); { let root = Span::root("root", SpanContext::random()); let _guard = root.set_local_parent(); do_something(100); block_on( async { do_something_async(100).await; } .in_span(Span::enter_with_local_parent("aync_job")), ); } fastrace::flush(); ``` -------------------------------- ### Optimize Tracing with LocalSpan and Thread-Local Context in Rust Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This Rust example showcases the use of `LocalSpan` for performance optimization in single-threaded scenarios. It demonstrates how `LocalSpan::enter_with_local_parent()` can be used to create spans, provided a local context has been established by `Span::set_local_parent()`. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fastrace::set_reporter(ConsoleReporter, Config::default()); { let root = Span::root("root", SpanContext::random()); let _guard = root.set_local_parent(); { // The parent of this span is `root`. let _span1 = LocalSpan::enter_with_local_parent("a child span"); foo(); } } fn foo() { // The parent of this span is `span1`. let _span2 = LocalSpan::enter_with_local_parent("a child span of child span"); } fastrace::flush(); ``` -------------------------------- ### Example: Create a root Span Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/struct.Span Demonstrates how to create a new root span for a trace using `Span::root()` with a name and a `SpanContext`. ```Rust use fastrace::prelude::*; let root = Span::root("root", SpanContext::random()); ``` -------------------------------- ### Initialize and Flush Fastrace Reporter in Rust Application Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This example demonstrates how to initialize a `Reporter` implementation (e.g., `ConsoleReporter`) early in a Rust application's runtime using `fastrace::set_reporter`. It also shows calling `fastrace::flush()` before termination to ensure all collected span records are reported, as records generated before initialization are ignored. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fn main() { fastrace::set_reporter(ConsoleReporter, Config::default()); loop { let root = Span::root("worker-loop", SpanContext::random()); let _guard = root.set_local_parent(); handle_request(); } fastrace::flush(); } ``` -------------------------------- ### Example: Create a no-op Span Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/struct.Span Demonstrates how to create a placeholder span using `Span::noop()`. ```Rust use fastrace::prelude::*; let root = Span::noop(); ``` -------------------------------- ### Establish New Fastrace Context in Rust Library Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This example demonstrates how a library can establish its own tracing context using `Span::root()` and `Span::set_local_parent()`, independent of the caller's context. The `func_path!()` macro is used to automatically detect the function's full name for the root span. ```Rust use fastrace::prelude::*; pub fn send_request(req: HttpRequest) -> Result<(), Error> { let root = Span::root(func_path!(), SpanContext::random()); let _guard = root.set_local_parent(); // ... } ``` -------------------------------- ### APIDOC: fastrace::set_reporter Function Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace Documents the `set_reporter` function, used to configure the reporter for the current application. ```APIDOC fn fastrace::set_reporter Description: Sets the reporter and its configuration for the current application. ``` -------------------------------- ### Span::noop Method Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/struct.Span Creates a place-holder span that never starts recording. ```APIDOC pub fn noop() -> Self ``` -------------------------------- ### Rust: Convert LocalSpans to SpanRecords Example Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/local/local_collector.rs This Rust example demonstrates how to use `LocalCollector` to collect local spans and then convert them into `SpanRecord`s using the `LocalSpans::to_span_records` method. It shows how to manually handle the collected records, associating them with a new parent context. ```Rust use fastrace::local::LocalCollector; use fastrace::local::LocalSpans; use fastrace::prelude::*; // Collect local spans manually without a parent let collector = LocalCollector::start(); let span = LocalSpan::enter_with_local_parent("a child span"); drop(span); // Collect local spans into a LocalSpans instance let local_spans: LocalSpans = collector.collect(); // Convert LocalSpans to SpanRecords with a given parent context let parent_context = SpanContext::random(); let span_records = local_spans.to_span_records(parent_context); // Now you can manually handle the span records for record in span_records { println!("{:?}", record); } ``` ```Rust pub fn to_span_records(&self, parent: SpanContext) -> Vec { #[cfg(not(feature = "enable"))] { vec![] } #[cfg(feature = "enable")] { self.inner.to_span_records(parent) } } ``` -------------------------------- ### APIDOC: fastrace::trace Attribute Macro Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace Documents the `trace` attribute macro, designed to reduce boilerplate code in tracing implementations. ```APIDOC attr fastrace::trace Description: An attribute macro designed to eliminate boilerplate code. ``` -------------------------------- ### Configuring and Initializing fastrace Reporter Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/lib.rs This example illustrates how to set up a `fastrace` reporter, specifically the `ConsoleReporter`, which prints span records to stderr. It also shows how to configure the reporting interval using `Config` and how to manually trigger a flush of collected spans. ```Rust use std::time::Duration; use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; fastrace::set_reporter( ConsoleReporter, Config::default().report_interval(Duration::from_secs(1)), ); fastrace::flush(); ``` -------------------------------- ### LocalCollector::start() Method (fastrace APIDOC) Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/local/local_collector.rs The `start` method initializes and returns a new `LocalCollector` instance. When the `enable` feature is active, it registers a new span line with the `LOCAL_SPAN_STACK`; otherwise, it returns a default (disabled) collector. ```APIDOC LocalCollector::start() -> Self Description: Initializes and returns a new LocalCollector instance. Return: Self (a new LocalCollector) Behavior: - If 'enable' feature is NOT active: Returns LocalCollector::default(). - If 'enable' feature IS active: Registers a new span line with LOCAL_SPAN_STACK to create the collector. ``` -------------------------------- ### Set Up Manual fastrace Context in Rust Library Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index This Rust code illustrates how a library can establish its own tracing context using `fastrace::Span::root()` and `Span::set_local_parent()`. This allows the library to trace its operations independently of the caller's tracing setup. The `func_path!()` macro is used to automatically name the root span. ```Rust use fastrace::prelude::*; pub fn send_request(req: HttpRequest) -> Result<(), Error> { let root = Span::root(func_path!(), SpanContext::random()); let _guard = root.set_local_parent(); // ... } ``` -------------------------------- ### Configuring fastrace Reporter Interval (Rust) Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This snippet demonstrates how to initialize a fastrace reporter and customize its reporting behavior, specifically by setting a custom report interval. It uses the ConsoleReporter as an example, configuring it to flush span records every 1 second instead of the default 500 milliseconds. ```Rust use std::time::Duration; use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; fastrace::set_reporter( ConsoleReporter, Config::default().report_interval(Duration::from_secs(1)), ); fastrace::flush(); ``` -------------------------------- ### APIDOC: fastrace::file_location Macro Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace Documents the `file_location` macro, which retrieves the source file location where it is invoked. ```APIDOC macro fastrace::file_location Description: Get the source file location where the macro is invoked. Returns: &'static str ``` -------------------------------- ### Rust `#[trace]` Macro Usage Examples Source: https://docs.rs/fastrace/latest/fastrace/-macro/0.7.11/x86_64-unknown-linux-gnu/src/fastrace_macro/lib.rs Illustrates various ways to apply the `#[trace]` attribute macro to Rust functions. Examples include basic function tracing, customizing span names using `short_name` and `name` parameters, controlling async span entry with `enter_on_poll`, and adding custom key-value properties to spans. ```Rust use fastrace::prelude::*; #[trace] fn simple() { // ... } #[trace(short_name = true)] async fn simple_async() { // ... } #[trace(name = "qux", enter_on_poll = true)] async fn baz() { // ... } #[trace(properties = { "k1": "v1", "a": "argument `a` is {a:?}" })] async fn properties(a: u64) { // ... } ``` -------------------------------- ### APIDOC: fastrace::Span Struct Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace Documents the `Span` struct, which provides a thread-safe mechanism for tracing. ```APIDOC struct fastrace::Span Description: A thread-safe span. ``` -------------------------------- ### Example: Set Report Interval for fastrace::collector::Config Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/collector/struct.Config Demonstrates how to create a default `Config` instance and set its report interval to 100 milliseconds, then apply this configuration to a `ConsoleReporter`. ```Rust use fastrace::collector::Config; let config = Config::default().report_interval(std::time::Duration::from_millis(100)); fastrace::set_reporter(fastrace::collector::ConsoleReporter, config); ``` -------------------------------- ### Rust fastrace::file_location Macro Definition and Example Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/macro.file_location This snippet provides the definition and an example usage of the `fastrace::file_location!` macro. This macro is designed to retrieve the static string representation of the source file location (file path, line, and column) where it is invoked. ```Rust macro_rules! file_location! { () => { ... }; } ``` ```Rust use fastrace::file_location; fn foo() { assert_eq!(file_location!(), "fastrace/src/macros.rs:8:15"); } ``` -------------------------------- ### LocalCollector struct and methods API documentation Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/local/struct.LocalCollector Provides the API reference for the `LocalCollector` struct, detailing its core methods: `start()` for initializing a new collector and `collect()` for retrieving the accumulated `LocalSpans`. ```APIDOC LocalCollector struct: pub fn start() -> Self pub fn collect(self) -> LocalSpans ``` -------------------------------- ### Example: Enable Tail Sampling for fastrace::collector::Config Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/collector/struct.Config Demonstrates how to enable tail sampling for the `Config` and then cancel a root span, illustrating the effect of tail sampling where child spans are held until the root span finishes or is cancelled. ```Rust use fastrace::collector::Config; use fastrace::collector::SpanContext; let config = Config::default().tail_sampled(true); fastrace::set_reporter(fastrace::collector::ConsoleReporter, config); let root = fastrace::Span::root("root", SpanContext::random()); root.cancel(); ``` -------------------------------- ### Add Fastrace Dependency to Rust Library Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This snippet shows how to add `fastrace` as a dependency to a Rust library project in `Cargo.toml` without enabling any extra features, ensuring minimal overhead. ```Rust [dependencies] fastrace = "0.7" ``` -------------------------------- ### Collect and Attach Local Spans with LocalCollector (Rust Example) Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/local/local_collector.rs This example demonstrates how to use `LocalCollector::start()` to begin collecting `LocalSpan` instances without an immediate parent. After dropping the local span, `collector.collect()` gathers them into a `LocalSpans` object, which can then be attached to a `Span::root` using `root.push_child_spans()`. ```Rust use fastrace::local::LocalCollector; use fastrace::prelude::*; // Collect local spans manually without a parent let collector = LocalCollector::start(); let span = LocalSpan::enter_with_local_parent("a child span"); drop(span); let local_spans = collector.collect(); // Attach the local spans to a parent let root = Span::root("root", SpanContext::random()); root.push_child_spans(local_spans); ``` -------------------------------- ### APIDOC: fastrace::func_path Macro Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace Documents the `func_path` macro, which retrieves the full path of the function where it is invoked. ```APIDOC macro fastrace::func_path Description: Get the full path of the function where the macro is invoked. Returns: &'static str ``` -------------------------------- ### Fastrace Collector StartCollect Command Processing Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/collector/global_collector.rs This loop processes `StartCollect` commands. For each command, it inserts a new `ActiveCollector` into the `active_collectors` map, keyed by the `collect_id`, indicating the start of a new collection. ```Rust for StartCollect { collect_id } in self.start_collects.drain(..) { self.active_collectors .insert(collect_id, ActiveCollector::default()); } ``` -------------------------------- ### Example: Create a child Span with multiple parents Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/struct.Span Demonstrates how to create a child span associated with an array of parent spans using `Span::enter_with_parents()`. ```Rust use fastrace::prelude::*; let parent1 = Span::root("parent1", SpanContext::random()); let parent2 = Span::root("parent2", SpanContext::random()); let child = Span::enter_with_parents("child", [&parent1, &parent2]); ``` -------------------------------- ### Instrumenting an Async Task with fastrace in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/future/index This Rust example demonstrates how to use the `fastrace` crate to instrument an asynchronous task. It shows how to create a root span, enter a child span, and use `in_span()` and `enter_on_poll()` to ensure tracing context is propagated through `Future`s. ```Rust use fastrace::prelude::*; let root = Span::root("root", SpanContext::random()); // Instrument the a task let task = async { async { // ... } .enter_on_poll("future is polled") .await; } .in_span(Span::enter_with_parent("task", &root)); runtime.spawn(task); ``` -------------------------------- ### Example: Create a child Span with a single parent Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/struct.Span Demonstrates how to create a child span by associating it with an existing parent span using `Span::enter_with_parent()`. ```Rust use fastrace::prelude::*; let root = Span::root("root", SpanContext::random()); let child = Span::enter_with_parent("child", &root); ``` -------------------------------- ### APIDOC: fastrace::Event Struct Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace Documents the `Event` struct, representing a single point in time during the execution of a span. ```APIDOC struct fastrace::Event Description: An event that represents a single point in time during the execution of a span. ``` -------------------------------- ### APIDOC: fastrace::full_name Macro (Deprecated) Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace Documents the deprecated `full_name` macro, which retrieves the full path of the function where it is invoked. ```APIDOC macro fastrace::full_name (Deprecated) Description: Get the full path of the function where the macro is invoked. Returns: &'static str ``` -------------------------------- ### Example Usage of func_name Macro in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/macro.func_name Demonstrates how to use the `func_name!` macro within a Rust function to assert its own function name, illustrating its basic functionality. ```Rust use fastrace::func_name; fn foo() { assert_eq!(func_name!(), "foo"); } ``` -------------------------------- ### Using `#[trace]` Macro for Function Tracing in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/attr.trace Demonstrates various applications of the `#[trace]` macro from the `fastrace` crate. Examples include basic function tracing, asynchronous function tracing with `short_name`, custom span names with `enter_on_poll`, and adding custom properties to spans. ```Rust use fastrace::prelude::*; #[trace] fn simple() { // ... } #[trace(short_name = true)] async fn simple_async() { // ... } #[trace(name = "qux", enter_on_poll = true)] async fn baz() { // ... } #[trace(properties = { "k1": "v1", "a": "argument `a` is {a:?}" })] async fn properties(a: u64) { // ... } ``` -------------------------------- ### Example Usage of func_path Macro in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/macro.func_path Demonstrates how to use the `func_path!` macro within a Rust function to assert its return value, which is the full path of the function where it is called. ```Rust use fastrace::func_path; fn foo() { assert_eq!(func_path!(), "rust_out::main::_doctest_main_fastrace_src_macros_rs_34_0::foo"); } ``` -------------------------------- ### Add Fastrace Dependency to Rust Application with Enable Feature Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This snippet shows how to add `fastrace` as a dependency to a Rust application project in `Cargo.toml`, enabling the `enable` feature for runtime tracing. The feature can be removed to statically disable tracing. ```Rust [dependencies] fastrace = { version ="0.7", features = ["enable"] } ``` -------------------------------- ### Establish Local Tracing Context with Span::root() in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/lib.rs Libraries can set up an independent tracing context using `Span::root()` to start a new trace and `Span::set_local_parent()` to establish a local context for the current thread. The `func_path!()` macro can be used to automatically name the root span. ```Rust use fastrace::prelude::*; # struct HttpRequest; # struct Error; pub fn send_request(req: HttpRequest) -> Result<(), Error> { let root = Span::root(func_path!(), SpanContext::random()); let _guard = root.set_local_parent(); // ... # Ok(()) } ``` -------------------------------- ### Using Fastrace `#[trace]` Macro for Functions (Rust) Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index This example illustrates the usage of the `#[trace]` attribute macro to automatically instrument functions for tracing. It demonstrates tracing both synchronous and asynchronous functions, emphasizing that traced functions must be called within a `Span`'s local context for successful tracing. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; use pollster::block_on; #[trace] fn do_something(i: u64) { std::thread::sleep(std::time::Duration::from_millis(i)); } #[trace] async fn do_something_async(i: u64) { futures_timer::Delay::new(std::time::Duration::from_millis(i)).await; } fastrace::set_reporter(ConsoleReporter, Config::default()); { let root = Span::root("root", SpanContext::random()); let _guard = root.set_local_parent(); do_something(100); block_on( async { do_something_async(100).await; } .in_span(Span::enter_with_local_parent("aync_job")), ); } fastrace::flush(); ``` -------------------------------- ### Get current local parent SpanContext in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/collector/struct.SpanContext Example demonstrating how to retrieve the `SpanContext` of the current local parent span using `SpanContext::current_local_parent`. ```Rust use fastrace::prelude::*; let span = Span::root("root", SpanContext::random()); let _guard = span.set_local_parent(); let span_context = SpanContext::current_local_parent(); ``` -------------------------------- ### Rust: Configure Global Reporter with fastrace::set_reporter Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/fn.set_reporter The `set_reporter` function in `fastrace` allows configuring a global reporter and its associated settings for the application. It accepts any type that implements the `Reporter` trait and a `Config` struct. The provided example demonstrates how to initialize the global reporter using `ConsoleReporter` with default configuration, enabling tracing output to the console. ```Rust pub fn set_reporter(reporter: impl Reporter, config: Config) ``` ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; fastrace::set_reporter(ConsoleReporter, Config::default()); ``` -------------------------------- ### fastrace Core API Reference Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/lib.rs This section provides an overview of key structs, traits, and functions within the `fastrace` library, covering span creation, management, reporting, and utility modules. ```APIDOC Reporter: Trait responsible for reporting span records to a remote agent (e.g., Jaeger). ConsoleReporter: A concrete Reporter implementation that prints span records to stderr. Config: Struct for customizing reporter behavior, e.g., `report_interval(Duration)`. Functions: flush(): Manually triggers the global reporter to send collected spans. set_reporter(reporter: impl Reporter, config: Config): Initializes the global span reporter. Core Tracing Components: Span: Represents a unit of work or operation in a trace. - root(): Creates a new root span. - noop(): Creates a placeholder span with minimal overhead. - cancel(): Dismisses a span to prevent it from being reported. - enter_with_parent(parent_span: Span): Enters a new span with a specified parent. - set_local_parent(parent_span: Span): Sets a local parent for the current span. LocalSpan: A span type for local, non-global tracing contexts. - enter_with_local_parent(name: &str): Enters a new local span with a specified parent. FutureExt: Trait providing tracing capabilities for `std::future::Future`. - in_span(span: Span): Associates an async Future with a given span. Event: Represents a specific event or log point within a span. Macros: trace: Macro for convenient tracing of functions or blocks. Modules: collector: Contains types related to span collection and reporting (e.g., Reporter, Config). future: Contains extensions for `std::future::Future`. local: Contains types for local span management. prelude: A module that re-exports commonly used types for convenience: - SpanContext - SpanId - SpanRecord - TraceId - Event - file_location() - func_name() - func_path() ``` -------------------------------- ### Get Elapsed Time of a fastrace Span Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/struct.Span Demonstrates how to retrieve the duration since a `Span` was created using the `elapsed` method. This method returns an `Option`, which will be `None` if the span is a no-op span. The example shows how to use the elapsed time to conditionally cancel a span. ```APIDOC pub fn elapsed(&self) -> Option ``` ```Rust use fastrace::prelude::*; use std::time::Duration; let root = Span::root("root", SpanContext::random()); // ... if root .elapsed() .map(|elapsed| elapsed < Duration::from_secs(1)) .unwrap_or(false) { root.cancel(); } ``` -------------------------------- ### Create Root and Child Spans with Explicit Parent in Fastrace Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index This Rust code demonstrates how to initialize a root `Span` and then create a child `Span` by explicitly passing the parent `Span` reference. It also shows the setup of a `ConsoleReporter` for trace collection. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fastrace::set_reporter(ConsoleReporter, Config::default()); { let root_span = Span::root("root", SpanContext::random()); { let child_span = Span::enter_with_parent("a child span", &root_span); // ... // child_span ends here. } // root_span ends here. } fastrace::flush(); ``` -------------------------------- ### Rust FutureExt Trait: enter_on_poll method Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/future/struct.EnterOnPoll Starts a `LocalSpan` at every `Future::poll()`. If the future gets polled multiple times, it will create multiple short spans. This method is part of the `fastrace::future::FutureExt` trait, useful for fine-grained tracing of future polling events. ```Rust fn enter_on_poll(self, name: impl Into>) -> EnterOnPoll ``` -------------------------------- ### fastrace::future::FutureExt::enter_on_poll Method Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/future/trait.FutureExt API documentation for the enter_on_poll method, which starts a LocalSpan every time a Future is polled. This is useful for creating multiple short spans to trace fine-grained polling cycles. ```APIDOC fn enter_on_poll(self, name: impl Into>) -> EnterOnPoll Description: Starts a LocalSpan at every Future::poll(). If the future gets polled multiple times, it will create multiple *short* spans. ``` -------------------------------- ### Tracing Asynchronous Task with fastrace::in_span Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/future/trait.FutureExt Demonstrates how to trace an asynchronous task by wrapping it in a span using in_span and associating it with a root span. This example uses tokio::spawn to execute the task, ensuring its operations are recorded within the tracing hierarchy. ```Rust use fastrace::prelude::*; let root = Span::root("Root", SpanContext::random()); let task = async { // ... } .in_span(Span::enter_with_parent("Task", &root)); tokio::spawn(task); ``` -------------------------------- ### LocalSpan API Reference Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/local/struct.LocalSpan Detailed API documentation for the `LocalSpan` struct, including its methods for span management and property assignment. ```APIDOC impl LocalSpan: pub fn enter_with_local_parent(name: impl Into>) -> Self Description: Create a new child span associated with the current local span in the current thread, and then it will become the new local parent. If no local span is active, this function is no-op. Parameters: name: The name of the new child span. Returns: Self (the new LocalSpan instance). pub fn with_property(self, property: F) -> Self Description: Add a single property to the LocalSpan and return the modified LocalSpan. A property is an arbitrary key-value pair associated with a span. Parameters: self: The LocalSpan instance to modify. property: A closure that returns a (K, V) tuple representing the key-value property. Returns: Self (the modified LocalSpan instance). Constraints: K: Into> V: Into> F: FnOnce() -> (K, V) pub fn with_properties(self, properties: F) -> Self Description: Add multiple properties to the LocalSpan and return the modified LocalSpan. Parameters: self: The LocalSpan instance to modify. properties: A closure that returns an iterable of (K, V) tuples representing the key-value properties. Returns: Self (the modified LocalSpan instance). Constraints: K: Into> V: Into> I: IntoIterator F: FnOnce() -> I pub fn add_property(property: F) Description: Add a single property to the current local parent. A property is an arbitrary key-value pair associated with a span. Parameters: property: A closure that returns a (K, V) tuple representing the key-value property. Constraints: K: Into> V: Into> F: FnOnce() -> (K, V) ``` -------------------------------- ### Optimize Tracing with LocalSpan for Single-Threaded Contexts in Fastrace Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index This Rust code demonstrates the use of `LocalSpan` for performance optimization in single-threaded scenarios. It highlights the precondition that `LocalSpan` creation must occur within a local context established by `Span::set_local_parent()`, showing how to create a root `Span`, set it as the local parent, and then create `LocalSpan` instances. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fastrace::set_reporter(ConsoleReporter, Config::default()); { let root = Span::root("root", SpanContext::random()); let _guard = root.set_local_parent(); { // The parent of this span is `root`. let _span1 = LocalSpan::enter_with_local_parent("a child span"); foo(); } } fn foo() { // The parent of this span is `span1`. let _span2 = LocalSpan::enter_with_local_parent("a child span of child span"); } fastrace::flush(); ``` -------------------------------- ### Rust Any Trait: Get TypeId Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/collector/struct.SpanId Gets the `TypeId` of the `self` value. This method is part of the `Any` trait, allowing runtime type identification for dynamic type introspection. ```APIDOC fn type_id(&self) -> TypeId ``` -------------------------------- ### Using FutureExt::enter_on_poll for Per-Poll Tracing in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/future.rs This example demonstrates `enter_on_poll`, which creates a new `LocalSpan` every time the future is polled. This is useful for tracing short, repeated operations within a future. ```Rust # #[tokio::main] # async fn main() { use fastrace::prelude::*; let root = Span::root("Root", SpanContext::random()); let task = async { async { // ... } .enter_on_poll("Sub Task") .await } .in_span(Span::enter_with_parent("Task", &root)); tokio::spawn(task); # } ``` -------------------------------- ### Initialize and Start GlobalCollector Background Thread (Rust) Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/collector/global_collector.rs This associated function initializes the `GlobalCollector` with a provided `Reporter` and `Config`. It sets up the collector's internal state, including empty command vectors and an empty map for active collectors. If not targeting WASM, it spawns a new thread named 'fastrace-global-collector' that continuously calls `handle_commands` at an interval determined by `config.report_interval`, ensuring periodic processing of trace commands. ```Rust impl GlobalCollector { fn start(reporter: impl Reporter, config: Config) { let global_collector = GlobalCollector { config, reporter: Some(Box::new(reporter)), active_collectors: HashMap::new(), start_collects: vec![], drop_collects: vec![], commit_collects: vec![], submit_spans: vec![], stale_spans: vec![], }; *GLOBAL_COLLECTOR.lock() = Some(global_collector); #[cfg(not(target_family = "wasm"))] { std::thread::Builder::new() .name("fastrace-global-collector".to_string()) .spawn(move || { loop { let begin_instant = Instant::now(); GLOBAL_COLLECTOR.lock().as_mut().unwrap().handle_commands(); std::thread::sleep( config .report_interval .saturating_sub(begin_instant.elapsed()), ); } }) .unwrap(); } } } ``` -------------------------------- ### Fastrace Span API Documentation Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index Detailed API reference for the `Span` and `LocalSpan` structs, outlining their properties, methods, parameters, and return types within the `fastrace` library. ```APIDOC Span: Represents an individual unit of work. Properties: name: string start_timestamp: timestamp duration: duration key_value_properties: map parent_reference: Span Methods: root(name: string, context: SpanContext): Span Description: Starts a new root Span, requiring a trace ID and parent span ID from a remote source. If no remote parent, parent span ID is typically zero. Parameters: name: The name of the span. context: The SpanContext, including trace ID and parent span ID. Returns: A new root Span. enter_with_parent(name: string, parent: &Span): Span Description: Creates a child Span, establishing a reference relationship with the parent. Parameters: name: The name of the child span. parent: A reference to the parent Span. Returns: A new child Span. set_local_parent(): Guard Description: Sets a local context of the Span for the current thread. Returns a guard that unsets the context when dropped. Returns: A guard object. enter_with_local_parent(name: string): Span Description: Accesses the parent Span from the local context and creates a child Span with it. Parameters: name: The name of the child span. Returns: A new child Span. LocalSpan: A substitute for Span to reduce overhead and enhance performance in single-thread execution flows where the Span does not cross threads or await points. Precondition: Must be created within a local context of a Span, established by Span::set_local_parent(). Methods: enter_with_local_parent(name: string): LocalSpan Description: Starts a LocalSpan, which then becomes the new local parent. If no local context is set, this method does nothing. Parameters: name: The name of the local span. Returns: A new LocalSpan. ``` -------------------------------- ### Rust Any Trait Implementation: Get TypeId Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/local/struct.LocalCollector Documents the `Any` trait implementation for generic types `T`, allowing runtime introspection to get the `TypeId` of an instance. This is useful for downcasting and dynamic type checking. ```APIDOC impl Any for T where T: 'static + ?Sized fn type_id(&self) -> TypeId ``` -------------------------------- ### Rust Example: Adding an Event to a Local Parent Span Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/struct.Event Illustrates how to use the `Event::add_to_local_parent` method in Rust. The example shows initializing a root span, setting it as the local parent, and then adding an event with custom properties. ```Rust use fastrace::prelude::*; let root = Span::root("root", SpanContext::random()); let _guard = root.set_local_parent(); Event::add_to_local_parent("event in root", || [("key".into(), "value".into())]); ``` -------------------------------- ### fastrace::future Module API Reference Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/future/index API documentation for the `fastrace::future` module, detailing its purpose, key structs, and traits for instrumenting Rust Futures with tracing. ```APIDOC Module: fastrace::future Description: This module provides tools to trace a `Future`. Details: The `FutureExt` trait extends `Future` with two methods: `in_span()` and `enter_on_poll()`. It is crucial that the outermost future uses `in_span()`, otherwise, the traces inside the `Future` will be lost. Structs: EnterOnPoll Description: Adapter for `FutureExt::enter_on_poll()`. InSpan Description: Adapter for `FutureExt::in_span()`. Traits: FutureExt Description: An extension trait for `Futures` that provides tracing instrument adapters. ``` -------------------------------- ### Configuring Fastrace Reporter (Rust) Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index This snippet shows how to initialize and configure a `Reporter` in `fastrace`, specifically using the `ConsoleReporter` to print span records to stderr. It demonstrates setting a custom report interval, highlighting that reporters should be initialized early and can be manually flushed. ```Rust use std::time::Duration; use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; fastrace::set_reporter( ConsoleReporter, Config::default().report_interval(Duration::from_secs(1)), ); fastrace::flush(); ``` -------------------------------- ### Apply fastrace::trace Attribute to Rust Function Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index This example demonstrates applying the `#[fastrace::trace]` attribute to a Rust function. When a tracing context is active, a `SpanRecord` will be automatically collected each time this function is called, enabling automatic tracing. ```Rust #[fastrace::trace] pub fn send_request(req: HttpRequest) -> Result<(), Error> { // ... } ``` -------------------------------- ### Adding Events to Spans in fastrace (Rust) Source: https://docs.rs/fastrace/latest/fastrace/latest/fastrace This snippet demonstrates how to add custom events to both root and child spans using the fastrace library. It initializes a ConsoleReporter and then shows the process of creating a root span, setting it as the local parent, and adding an event. It also illustrates creating a child span and adding an event within its context. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fastrace::set_reporter(ConsoleReporter, Config::default()); { let root = Span::root("root", SpanContext::random()); let _guard = root.set_local_parent(); root.add_event(Event::new("event in root")); { let _span1 = LocalSpan::enter_with_local_parent("a child span"); LocalSpan::add_event(Event::new("event in span1")); } } fastrace::flush(); ``` -------------------------------- ### Encode W3C Traceparent Header in Rust Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/collector/struct.SpanContext This Rust example shows how to create a new `SpanContext` and then encode it into a W3C Trace Context `traceparent` header string using the `encode_w3c_traceparent` method. It includes an assertion to verify the correctness of the generated traceparent string. ```Rust use fastrace::prelude::*; let span_context = SpanContext::new(TraceId(12), SpanId(34)); let traceparent = span_context.encode_w3c_traceparent(); assert_eq!( traceparent, "00-0000000000000000000000000000000c-0000000000000022-01" ); ``` -------------------------------- ### Initialize and Flush fastrace Reporter in Rust Application Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/index This Rust `main` function demonstrates the initialization of a `fastrace::collector::ConsoleReporter` with a default configuration early in the application's runtime. It also shows how to create root spans for operations and ensures all collected span records are reported by calling `fastrace::flush()` before termination. Span records generated before initialization are ignored. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fn main() { fastrace::set_reporter(ConsoleReporter, Config::default()); loop { let root = Span::root("worker-loop", SpanContext::random()); let _guard = root.set_local_parent(); handle_request(); } fastrace::flush(); } ``` -------------------------------- ### Collect Local Spans into LocalSpans Instance (Rust Example) Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/local/local_collector.rs This example illustrates collecting `LocalSpan` instances into a `LocalSpans` object using `LocalCollector`. The `LocalSpans` struct acts as a container for collected spans, which can then be efficiently attached to a parent `Span` using `Span::push_child_spans()`, demonstrating a common pattern for managing detached trace segments. ```Rust use fastrace::local::LocalCollector; use fastrace::local::LocalSpans; use fastrace::prelude::*; // Collect local spans manually without a parent let collector = LocalCollector::start(); let span = LocalSpan::enter_with_local_parent("a child span"); drop(span); // Collect local spans into a LocalSpans instance let local_spans: LocalSpans = collector.collect(); // Attach the local spans to a parent let root = Span::root("root", SpanContext::random()); root.push_child_spans(local_spans); ``` -------------------------------- ### Adding Events to Spans and LocalSpans in Rust fastrace Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/lib.rs This example demonstrates how to attach `Event` objects to both `Span` and `LocalSpan` instances. Events represent specific points in time during program execution and act as log records associated with their parent span. ```Rust use fastrace::collector::Config; use fastrace::collector::ConsoleReporter; use fastrace::prelude::*; fastrace::set_reporter(ConsoleReporter, Config::default()); { let root = Span::root("root", SpanContext::random()); let _guard = root.set_local_parent(); root.add_event(Event::new("event in root")); { let _span1 = LocalSpan::enter_with_local_parent("a child span"); LocalSpan::add_event(Event::new("event in span1")); } } fastrace::flush(); ``` -------------------------------- ### Rust: Creating a Span Tree with Properties and Mock Collection Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/src/fastrace/span.rs This example demonstrates how to create a hierarchical tree of `fastrace` spans, including adding properties to a span. It uses `Span::root` for the top-level span and `Span::enter_with_parent` for child and grandchild spans. The snippet also shows how to use `crossbeam::scope` to concurrently drop spans, simulating their completion. A `MockGlobalCollect` is set up to capture and verify the collected span data, ensuring the tree structure and properties are correctly reported. ```Rust #[test] fn span_tree_with_properties() { crate::set_reporter(ConsoleReporter, crate::collector::Config::default()); let parent_ctx = SpanContext::random(); let routine = || { let root = Span::root("root", parent_ctx); let child1 = Span::enter_with_parent("child1", &root).with_properties(|| [("k1", "v1")]); let grandchild = Span::enter_with_parent("grandchild", &child1); let child2 = Span::enter_with_parent("child2", &root); crossbeam::scope(move |scope| { let mut rng = rng(); let mut spans = [child1, grandchild, child2]; spans.shuffle(&mut rng); for span in spans { scope.spawn(|_| drop(span)); } }) .unwrap(); fastrace::flush(); }; let mut mock = MockGlobalCollect::new(); let mut seq = Sequence::new(); let span_sets = Arc::new(Mutex::new(Vec::new())); mock.expect_start_collect() .times(1) .in_sequence(&mut seq) .return_const(42_usize); mock.expect_submit_spans() .times(4) .in_sequence(&mut seq) .withf(|_, collect_token| collect_token.len() == 1 && collect_token[0].collect_id == 42) .returning({ let span_sets = span_sets.clone(); move |span_set, token| span_sets.lock().unwrap().push((span_set, token)) }); mock.expect_commit_collect() .times(1) .in_sequence(&mut seq) .with(predicate::eq(42_usize)) .return_const(()); mock.expect_drop_collect().times(0); let mock = Arc::new(mock); set_mock_collect(mock); routine(); let span_sets = std::mem::take(&mut *span_sets.lock().unwrap()); assert_eq!( tree_str_from_span_sets(span_sets.as_slice()), "\n#42\nroot []\n child1 [(\"k1\", \"v1\")]\n grandchild []\n child2 []\n" ); } ``` -------------------------------- ### LocalSpans Struct and Method API Reference Source: https://docs.rs/fastrace/latest/fastrace/0.7.11/fastrace/local/struct.LocalSpans API documentation for the `fastrace::local::LocalSpans` struct, including its definition, methods, and trait implementations. ```APIDOC Struct: LocalSpans Description: A collection of LocalSpan instances, typically used to group and associate with a parent span. Implemented as Arc<[LocalSpan]> for low-cost cloning and sharing. Methods: pub fn to_span_records(&self, parent: SpanContext) -> Vec Description: Converts the LocalSpans to SpanRecords. The converted spans will appear as if they were collected within the given parent context. The parent of the top local span is set to the given parent. This function is useful for manual collection without involving the global collector. Parameters: parent: SpanContext - The parent context to associate the converted spans with. Returns: Vec - A vector of SpanRecord instances. Trait Implementations: impl Clone for LocalSpans Methods: fn clone(&self) -> LocalSpans Description: Returns a duplicate of the value. fn clone_from(&mut self, source: &Self) Description: Performs copy-assignment from source. impl Debug for LocalSpans Methods: fn fmt(&self, f: &mut Formatter<'_>) -> Result Description: Formats the value using the given formatter. ```