### SumVisitor Example Source: https://docs.rs/tracing/latest/tracing/field/trait.Visit.html An example implementation of the Visit trait that sums up all recorded i64 and u64 values. ```APIDOC ## Example: SumVisitor ### Description A visitor which only records numeric data might look like this: ### Code ```rust use tracing::field::{Visit, Field}; pub struct SumVisitor { sum: i64, } impl Visit for SumVisitor { fn record_i64(&mut self, _field: &Field, value: i64) { self.sum += value; } fn record_u64(&mut self, _field: &Field, value: u64) { self.sum += value as i64; } fn record_debug(&mut self, _field: &Field, _value: &dyn std::fmt::Debug) { // Do nothing } } ``` ### Usage This visitor keeps a running sum of all the numeric values it records, and ignores all other values. A more practical example of recording typed values is presented in `examples/counters.rs`, which demonstrates a very simple metrics system implemented using `tracing`. ``` -------------------------------- ### Info Macro Usage Examples Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Demonstrates how to use the `info!` macro for emitting log events at the info level. Includes examples with simple messages and structured fields. ```rust use tracing::info; # // this is so the test will still work in no-std mode # #[derive(Debug)] # pub struct Ipv4Addr; # impl Ipv4Addr { fn new(o1: u8, o2: u8, o3: u8, o4: u8) -> Self { Self } } # fn main() { # struct Connection { port: u32, speed: f32 } use tracing::field; let addr = Ipv4Addr::new(127, 0, 0, 1); let conn = Connection { port: 40, speed: 3.20 }; info!(conn.port, "connected to {:?}", addr); info!( target: "connection_events", ip = ?addr, conn.port, ?conn.speed, ); # } ``` -------------------------------- ### StringVisitor Example Source: https://docs.rs/tracing/latest/tracing/field/trait.Visit.html An example implementation of the Visit trait that writes formatted values to a mutable String. ```APIDOC ## Example: StringVisitor ### Description A simple visitor that writes to a string might be implemented like so: ### Code ```rust use std::fmt::{self, Write}; use tracing::field::{Value, Visit, Field}; pub struct StringVisitor<'a> { string: &'a mut String, } impl<'a> Visit for StringVisitor<'a> { fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { write!(self.string, "{} = {:?}; ", field.name(), value).unwrap(); } } ``` ### Usage This visitor will format each recorded value using `fmt::Debug`, and append the field name and formatted value to the provided string, regardless of the type of the recorded value. When all the values have been recorded, the `StringVisitor` may be dropped, allowing the string to be printed or stored in some other data structure. ``` -------------------------------- ### Debug Macro Examples Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Examples demonstrating the usage of the `debug!` macro for emitting events at the debug level. These examples show different ways to include fields and targets. ```rust use tracing::debug; # fn main() { # #[derive(Debug)] struct Position { x: f32, y: f32 } let pos = Position { x: 3.234, y: -1.223 }; debug!(?pos.x, ?pos.y); debug!(target: "app_events", position = ?pos, "New position"); debug!(name: "completed", position = ?pos); ``` -------------------------------- ### Trace Macro Examples Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Demonstrates various ways to construct trace events using the `trace!` macro. Includes examples with custom targets, names, and structured fields. ```rust use tracing::trace; # #[derive(Debug, Copy, Clone)] struct Position { x: f32, y: f32 } # impl Position { const ORIGIN: Self = Self { x: 0.0, y: 0.0 }; fn dist(&self, other: Position) -> f32 { let x = (other.x - self.x).exp2(); let y = (self.y - other.y).exp2(); (x + y).sqrt() } } # fn main() { let pos = Position { x: 3.234, y: -1.223 }; let origin_dist = pos.dist(Position::ORIGIN); trace!(position = ?pos, ?origin_dist); trace!( target: "app_events", position = ?pos, "x is {} and y is {}", if pos.x >= 0.0 { "positive" } else { "negative" }, if pos.y >= 0.0 { "positive" } else { "negative" } ); trace!(name: "completed", position = ?pos); # } ``` -------------------------------- ### Dependency Setup Source: https://docs.rs/tracing/latest/tracing Instructions on how to add the tracing crate as a dependency to a Rust project. ```APIDOC ## Dependency Setup ### Description To use the `tracing` crate, add it to your project's `Cargo.toml` file. ### Method Add to `Cargo.toml` ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```toml [dependencies] tracing = "0.1" ``` ### Response N/A ``` -------------------------------- ### Constructing an info_span! Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Examples demonstrating the creation of an info_span! and its usage within a scope. ```rust # use tracing::{span, info_span, Level}; # fn main() { info_span!("my_span"); // is equivalent to: span!(Level::INFO, "my_span"); # } ``` ```rust # use tracing::info_span; # fn main() { let span = info_span!("my span"); span.in_scope(|| { // do work inside the span... }); # } ``` -------------------------------- ### Usage examples for warn! Source: https://docs.rs/tracing/latest/tracing/macro.warn.html Demonstrates how to use the warn! macro with various field types and target specifications. ```rust use tracing::warn; let warn_description = "Invalid Input"; let input = &[0x27, 0x45]; warn!(?input, warning = warn_description); warn!( target: "input_events", warning = warn_description, "Received warning for input: {:?}", input, ); warn!(name: "invalid", ?input); ``` -------------------------------- ### Creating events with fields Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Examples showing how to record events with various field types and targets. ```rust use tracing::{event, Level}; # fn main() { let data = (42, "forty-two"); let private_data = "private"; let error = "a bad error"; event!(Level::ERROR, %error, "Received error"); event!( target: "app_events", Level::WARN, private_data, ?data, "App warning: {}", error ); event!(name: "answer", Level::INFO, the_answer = data.0); event!(Level::INFO, the_answer = data.0); # } ``` -------------------------------- ### Rust `error!` Macro Examples Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Demonstrates various ways to use the `error!` macro for logging events at the error level. Includes examples with custom targets, names, and structured fields. ```rust error!(port, error = %err_info); error!(target: "app_events", "App Error: {}", err_info); error!({ info = err_info }, "error on port: {}", port); error!(name: "invalid_input", "Invalid input: {}", err_info); ``` -------------------------------- ### Constructing a warn_span! Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Examples demonstrating the creation of a warn_span! and its usage within a scope. ```rust # use tracing::{warn_span, span, Level}; # fn main() { warn_span!("my_span"); // is equivalent to: span!(Level::WARN, "my_span"); # } ``` ```rust use tracing::warn_span; # fn main() { let span = warn_span!("my span"); span.in_scope(|| { // do work inside the span... }); # } ``` -------------------------------- ### Warn Macro Examples Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Demonstrates how to use the warn! macro for emitting warning-level events with different argument configurations. ```rust use tracing::warn; # fn main() { let warn_description = "Invalid Input"; let input = &[0x27, 0x45]; warn!(?input, warning = warn_description); warn!( target: "input_events", warning = warn_description, "Received warning for input: {:?}", input, ); warn!(name: "invalid", ?input); # } ``` -------------------------------- ### Subscriber Filtering Example Source: https://docs.rs/tracing/latest/tracing/struct.Level.html Provides a practical example of how a custom Subscriber can implement filtering using LevelFilter to control which spans and events are recorded. ```APIDOC ### §Examples Below is a simple example of how a `Subscriber` could implement filtering through a `LevelFilter`. When a span or event is recorded, the `Subscriber::enabled` method compares the span or event’s `Level` against the configured `LevelFilter`. The optional `Subscriber::max_level_hint` method can also be implemented to allow spans and events above a maximum verbosity level to be skipped more efficiently, often improving performance in short-lived programs. ```rust use tracing_core::{span, Event, Level, LevelFilter, Subscriber, Metadata}; #[derive(Debug)] pub struct MySubscriber { /// The most verbose level that this subscriber will enable. max_level: LevelFilter, // ... } impl MySubscriber { /// Returns a new `MySubscriber` which will record spans and events up to /// `max_level`. pub fn with_max_level(max_level: LevelFilter) -> Self { Self { max_level, // ... } } } impl Subscriber for MySubscriber { fn enabled(&self, meta: &Metadata<'_>) -> bool { // A span or event is enabled if it is at or below the configured // maximum level. meta.level() <= &self.max_level } // This optional method returns the most verbose level that this // subscriber will enable. Although implementing this method is not // *required*, it permits additional optimizations when it is provided, // allowing spans and events above the max level to be skipped // more efficiently. fn max_level_hint(&self) -> Option { Some(self.max_level) } // Implement the rest of the subscriber... fn new_span(&self, span: &span::Attributes<'_>) -> span::Id { // ... } fn event(&self, event: &Event<'_>) { // ... } // ... } ``` It is worth noting that the `tracing-subscriber` crate provides additional APIs for performing more sophisticated filtering, such as enabling different levels based on which module or crate a span or event is recorded in. ``` -------------------------------- ### Usage examples for event macro Source: https://docs.rs/tracing/latest/tracing/macro.event.html Demonstrates various ways to invoke the event macro with different levels, targets, and field formats. ```rust use tracing::{event, Level}; let data = (42, "forty-two"); let private_data = "private"; let error = "a bad error"; event!(Level::ERROR, %error, "Received error"); event!( target: "app_events", Level::WARN, private_data, ?data, "App warning: {}", error ); event!(name: "answer", Level::INFO, the_answer = data.0); event!(Level::INFO, the_answer = data.0); ``` -------------------------------- ### info! Macro Usage Examples Source: https://docs.rs/tracing/latest/tracing/macro.info.html Demonstrates various ways to use the info! macro, including field shorthand, target specification, and custom event names. ```rust use tracing::info; use tracing::field; let addr = Ipv4Addr::new(127, 0, 0, 1); let conn = Connection { port: 40, speed: 3.20 }; info!(conn.port, "connected to {:?}", addr); info!( target: "connection_events", ip = ?addr, conn.port, ?conn.speed, ); info!(name: "completed", "completed connection to {:?}", addr); ``` -------------------------------- ### Constructing an error span Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Examples demonstrating how to create an error span and execute code within its scope. ```rust # use tracing::{span, error_span, Level}; # fn main() { error_span!("my_span"); // is equivalent to: span!(Level::ERROR, "my_span"); # } ``` ```rust # use tracing::error_span; # fn main() { let span = error_span!("my span"); span.in_scope(|| { // do work inside the span... }); # } ``` -------------------------------- ### Span Lifecycle Management Source: https://docs.rs/tracing/latest/tracing/span/struct.EnteredSpan.html Examples of entering and exiting spans using guards and scopes. ```APIDOC ## Span Lifecycle Management ### Description Demonstrates how to manage the lifecycle of a span, including entering and exiting it using guards and explicit scope management. ### Method N/A (Illustrative examples) ### Endpoint N/A ### Parameters N/A ### Request Example ```rust let span = span!(Level::INFO, "my_span"); let guard = span.enter(); // code here is within the span drop(guard); // code here is no longer within the span ``` ### Response N/A ## Span Lifecycle with Function Scope ### Description Shows how a span can encompass the entire duration of a function call, with the guard automatically dropped upon function exit. ### Method N/A (Illustrative examples) ### Endpoint N/A ### Parameters N/A ### Request Example ```rust fn my_function() -> String { // enter a span for the duration of this function. let span = trace_span!("my_function"); let _enter = span.enter(); // anything happening in functions we call is still inside the span... my_other_function(); // returning from the function drops the guard, exiting the span. return "Hello world".to_owned(); } fn my_other_function() { // ... } ``` ### Response N/A ## Sub-scopes for Span Duration ### Description Illustrates creating sub-scopes to limit the duration for which a span is active. ### Method N/A (Illustrative examples) ### Endpoint N/A ### Parameters N/A ### Request Example ```rust let span = info_span!("my_great_span"); { let _enter = span.enter(); // this event occurs inside the span. info!("i'm in the span!"); // exiting the scope drops the guard, exiting the span. } // this event is not inside the span. info!("i'm outside the span!") ``` ### Response N/A ``` -------------------------------- ### Emitting Debug Events with `debug!` Source: https://docs.rs/tracing/latest/tracing/macro.debug.html Examples demonstrating how to use the `debug!` macro to emit events. Ensure the `tracing` crate is imported. ```rust use tracing::debug; let pos = Position { x: 3.234, y: -1.223 }; debug!(?pos.x, ?pos.y); debug!(target: "app_events", position = ?pos, "New position"); debug!(name: "completed", position = ?pos); ``` -------------------------------- ### Trace Event with Target and Formatted Message Source: https://docs.rs/tracing/latest/tracing/macro.trace.html This example demonstrates creating a trace event with a specific target, formatted string arguments, and conditional logic for message content. It requires the `tracing` crate. ```rust trace!( target: "app_events", position = ?pos, "x is {} and y is {}", if pos.x >= 0.0 { "positive" } else { "negative" }, if pos.y >= 0.0 { "positive" } else { "negative" } ); ``` -------------------------------- ### Use tracing::error! Macro Source: https://docs.rs/tracing/latest/tracing/macro.error.html Examples demonstrating how to use the `error!` macro with different argument formats to log error events. Ensure `tracing` is imported. ```rust use tracing::error; let (err_info, port) = ("No connection", 22); error!(port, error = %err_info); error!(target: "app_events", "App Error: {}", err_info); error!({ info = err_info }, "error on port: {}", port); error!(name: "invalid_input", "Invalid input: {}", err_info); ``` -------------------------------- ### Record multiple values on a span Source: https://docs.rs/tracing/latest/tracing/macro.record_all.html Example usage of the record_all macro to populate fields on an existing span. ```rust let span = info_span!("my span", field1 = field::Empty, field2 = field::Empty, field3 = field::Empty).entered(); record_all!(span, field1 = ?"1", field2 = %"2", field3 = 3); ``` -------------------------------- ### Get Metadata File Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns the name of the source code file where the span occurred, or None if unknown. ```rust pub fn file(&self) -> Option<&'a str> ``` -------------------------------- ### Get Metadata Target Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns a string describing the part of the system where the span or event occurred. This is typically the module path. ```rust pub fn target(&self) -> &'a str ``` -------------------------------- ### Level Struct and Comparisons Source: https://docs.rs/tracing/latest/tracing/struct.Level.html Describes the Level struct, its variants, and how levels can be compared for verbosity. Includes examples of comparing Level variants. ```APIDOC ## Level Describes the level of verbosity of a span or event. ### §Comparing Levels `Level` implements the `PartialOrd` and `Ord` traits, allowing two `Level`s to be compared to determine which is considered more or less verbose. Levels which are more verbose are considered “greater than” levels which are less verbose, with `Level::ERROR` considered the lowest, and `Level::TRACE` considered the highest. For example: ```rust use tracing_core::Level; assert!(Level::TRACE > Level::DEBUG); assert!(Level::ERROR < Level::WARN); assert!(Level::INFO <= Level::DEBUG); assert_eq!(Level::TRACE, Level::TRACE); ``` ### impl Level #### pub const ERROR: Level The “error” level. Designates very serious errors. #### pub const WARN: Level The “warn” level. Designates hazardous situations. #### pub const INFO: Level The “info” level. Designates useful information. #### pub const DEBUG: Level The “debug” level. Designates lower priority information. #### pub const TRACE: Level The “trace” level. Designates very low priority, often extremely verbose, information. #### pub fn as_str(&self) -> &'static str Returns the string representation of the `Level`. This returns the same string as the `fmt::Display` implementation. ``` -------------------------------- ### Entry Point for valueset_all Macro Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html The main entry point for the `valueset_all` macro, which takes a fields expression and a list of key-value pairs, then calls `value_set_all`. ```rust ($fields:expr, $($kvs:tt)+) => { { #[allow(unused_imports)] // This import statement CANNOT be removed as it will break existing use cases. // See #831, #2332, #3424 for the last times we tried. use $crate::field::{debug, display, Value}; $fields.value_set_all($crate::valueset_all!( @ { }, $($kvs)+ )) } }; ``` -------------------------------- ### Declaring Empty Fields Source: https://docs.rs/tracing/latest/src/tracing/span.rs.html Example of creating a span with fields that are not yet initialized. ```rust use tracing::{trace_span, field}; // Create a span with two fields: `greeting`, with the value "hello world", and // `parting`, without a value. ``` -------------------------------- ### Overriding span attributes Source: https://docs.rs/tracing/latest/tracing/attr.instrument.html Examples of customizing the span name, target, and level. ```rust // The generated span's name will be "my_span" rather than "my_function". #[instrument(name = "my_span")] pub fn my_function() { // ... do something incredibly interesting and important ... } ``` ```rust pub mod my_module { // The generated span's target will be "my_crate::some_special_target", // rather than "my_crate::my_module". #[instrument(target = "my_crate::some_special_target")] pub fn my_function() { // ... all kinds of neat code in here ... } } ``` ```rust // The span's level will be TRACE rather than INFO. #[instrument(level = "trace")] pub fn my_function() { // ... I have written a truly marvelous implementation of this function, // which this example is too narrow to contain ... } ``` -------------------------------- ### Get Metadata Name Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns the static string name of the span or event. ```rust pub fn name(&self) -> &'static str ``` -------------------------------- ### Get Metadata Level Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns the verbosity level of the described span or event. ```rust pub fn level(&self) -> &Level ``` -------------------------------- ### Get Metadata Fields Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns the names of the fields associated with the described span or event. ```rust pub fn fields(&self) -> &FieldSet ``` -------------------------------- ### Implement a string-writing visitor Source: https://docs.rs/tracing/latest/tracing/field/trait.Visit.html A basic implementation of Visit that writes field names and debug-formatted values to a string. ```rust use std::fmt::{self, Write}; use tracing::field::{Value, Visit, Field}; pub struct StringVisitor<'a> { string: &'a mut String, } impl<'a> Visit for StringVisitor<'a> { fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { write!(self.string, "{} = {:?}; ", field.name(), value).unwrap(); } } ``` -------------------------------- ### Create and enter a span with let-binding Source: https://docs.rs/tracing/latest/tracing/struct.Span.html Shows the alternative approach using Span::enter which requires a let-binding for the span. ```rust let span = info_span!("something_interesting"); let _e = span.enter(); ``` -------------------------------- ### Type Conversions (Into, TryFrom, TryInto) Source: https://docs.rs/tracing/latest/tracing/subscriber/struct.NoSubscriber.html Explains the different ways types can be converted into each other using `Into`, `TryFrom`, and `TryInto` traits. ```APIDOC ## Type Conversions ### `impl Into for T` #### Description Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ### `impl TryFrom for T` #### Description Performs the conversion. The type returned in the event of a conversion error is `Infallible`. ### `impl TryInto for T` #### Description Performs the conversion. The type returned in the event of a conversion error is the same as the `Error` type for `TryFrom` for `U`. ``` -------------------------------- ### Accessing `Dispatch` and Inner Value in `WithDispatch` Source: https://docs.rs/tracing/latest/src/tracing/instrument.rs.html Methods to get references to the `Dispatch` and the inner wrapped type. ```rust /// Borrows the [`Dispatch`] that is entered when this type is polled. pub fn dispatcher(&self) -> &Dispatch { &self.dispatcher } /// Borrows the wrapped type. pub fn inner(&self) -> &T { &self.inner } /// Mutably borrows the wrapped type. pub fn inner_mut(&mut self) -> &mut T { ``` -------------------------------- ### Instrumenting a Yak Shaving Function with Tracing Source: https://docs.rs/tracing/latest/index.html Demonstrates using `tracing` macros like `debug!`, `warn!`, and `error!` within a function instrumented with `#[tracing::instrument]`. Parameters and local variables can be used as field values. ```rust use std::{error::Error, io}; use tracing::{debug, error, info, span, warn, Level}; // the `#[tracing::instrument]` attribute creates and enters a span // every time the instrumented function is called. The span is named after the // the function or method. Parameters passed to the function are recorded as fields. #[tracing::instrument] pub fn shave(yak: usize) -> Result<(), Box> { // this creates an event at the DEBUG level with two fields: // - `excitement`, with the key "excitement" and the value "yay!" // - `message`, with the key "message" and the value "hello! I'm gonna shave a yak." // // unlike other fields, `message`'s shorthand initialization is just the string itself. debug!(excitement = "yay!", "hello! I'm gonna shave a yak."); if yak == 3 { warn!("could not locate yak!"); // note that this is intended to demonstrate `tracing`'s features, not idiomatic // error handling! in a library or application, you should consider returning // a dedicated `YakError`. libraries like snafu or thiserror make this easy. return Err(io::Error::new(io::ErrorKind::Other, "shaving yak failed!").into()); } else { debug!("yak shaved successfully"); } Ok(()) } pub fn shave_all(yaks: usize) -> usize { // Constructs a new span named "shaving_yaks" at the TRACE level, // and a field whose key is "yaks". This is equivalent to writing: // // let span = span!(Level::TRACE, "shaving_yaks", yaks = yaks); // // local variables (`yaks`) can be used as field values // without an assignment, similar to struct initializers. let _span = span!(Level::TRACE, "shaving_yaks", yaks).entered(); info!("shaving yaks"); let mut yaks_shaved = 0; for yak in 1..=yaks { let res = shave(yak); debug!(yak, shaved = res.is_ok()); if let Err(ref error) = res { // Like spans, events can also use the field initialization shorthand. // In this instance, `yak` is the field being initalized. error!(yak, error = error.as_ref(), "failed to shave yak!"); } else { yaks_shaved += 1; } debug!(yaks_shaved); } yaks_shaved } ``` -------------------------------- ### Accessing `Span` and Inner Value in `Instrumented` Source: https://docs.rs/tracing/latest/src/tracing/instrument.rs.html Methods to get references to the `Span` and the inner wrapped type. ```rust /// Borrows the `Span` that this type is instrumented by. pub fn span(&self) -> &Span { &self.span } /// Mutably borrows the `Span` that this type is instrumented by. pub fn span_mut(&mut self) -> &mut Span { &mut self.span } /// Borrows the wrapped type. pub fn inner(&self) -> &T { &self.inner } /// Mutably borrows the wrapped type. pub fn inner_mut(&mut self) -> &mut T { &mut self.inner } ``` -------------------------------- ### Using info_span to create and enter a span Source: https://docs.rs/tracing/latest/tracing/macro.info_span.html Shows how to create an info span and then use its in_scope method to execute code within that span's context. ```rust let span = info_span!("my span"); span.in_scope(|| { // do work inside the span... }); ``` -------------------------------- ### Get Metadata Callsite Identifier Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns an opaque Identifier that uniquely identifies the callsite this Metadata originated from. ```rust pub fn callsite(&self) -> Identifier ``` -------------------------------- ### Set Default Subscriber and Use with_subscriber Source: https://docs.rs/tracing/latest/src/tracing/instrument.rs.html Demonstrates setting a default subscriber and then using `with_subscriber` to attach a different subscriber to a specific future. Events are recorded by the respective subscribers. ```rust /// use tracing::instrument::WithSubscriber; /// /// // Set the default `Subscriber` /// let _default = tracing::subscriber::set_default(MySubscriber::default()); /// /// tracing::info!("this event will be recorded by the default `Subscriber`"); /// /// // Create a different `Subscriber` and attach it to a future. /// let other_subscriber = MyOtherSubscriber::default(); /// let future = async { /// tracing::info!("this event will be recorded by the other `Subscriber`"); /// // ... /// }; /// /// future /// // Attach the other `Subscriber` to the future before awaiting it /// .with_subscriber(other_subscriber) /// .await; /// /// // Once the future has completed, we return to the default `Subscriber`. /// tracing::info!("this event will be recorded by the default `Subscriber`"); /// # } ``` -------------------------------- ### Get Metadata Module Path Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns the path to the Rust module where the span occurred, or None if unknown. ```rust pub fn module_path(&self) -> Option<&'a str> ``` -------------------------------- ### CloneToUninit for T Source: https://docs.rs/tracing/latest/tracing/struct.Span.html Nightly-only experimental API for copying data to uninitialized memory. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Note This is a nightly-only experimental API. (`clone_to_uninit` #126799) ``` -------------------------------- ### NoSubscriber Constructor Source: https://docs.rs/tracing/latest/tracing/subscriber/struct.NoSubscriber.html Information on how to create a new instance of NoSubscriber. ```APIDOC ## Implementations ### impl NoSubscriber #### pub const fn new() -> NoSubscriber Returns a new `NoSubscriber`. ``` -------------------------------- ### Asynchronous span usage warning Source: https://docs.rs/tracing/latest/src/tracing/span.rs.html Example demonstrating the context for the warning regarding span entry in async functions. ```rust ``` # use tracing::info_span; # async fn some_other_async_function() {} async fn my_async_function() { ``` ``` -------------------------------- ### Create Trace Event with Fields and Arguments Source: https://docs.rs/tracing/latest/src/tracing/macros.rs.html Use this macro to create a trace event specifying fields and arguments. It defaults to WARN level and uses the current module path as the target. ```rust $crate::event!( target: module_path!(), $crate::Level::WARN, { $($field)+ }, $($arg)+ ) ``` ```rust $crate::event!( target: module_path!(), $crate::Level::WARN, { $($k).+ = $($field)*} ) ``` -------------------------------- ### Get Type ID for Metadata Source: https://docs.rs/tracing/latest/struct.Metadata.html Implements the Any trait's type_id method for Metadata, returning the TypeId of the instance. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Event Creation and Observation Source: https://docs.rs/tracing/latest/tracing/event/struct.Event.html Methods for constructing and observing Event instances. ```APIDOC ## Implementations ### impl<'a> Event<'a> #### pub fn dispatch(metadata: &'static Metadata<'static>, fields: &'a ValueSet<'_>) Constructs a new `Event` with the specified metadata and set of values, and observes it with the current subscriber. #### pub fn new( metadata: &'static Metadata<'static>, fields: &'a ValueSet<'a>, ) -> Event<'a> Returns a new `Event` in the current span, with the specified metadata and set of values. #### pub fn new_child_of( parent: impl Into>, metadata: &'static Metadata<'static>, fields: &'a ValueSet<'a>, ) -> Event<'a> Returns a new `Event` as a child of the specified span, with the provided metadata and set of values. #### pub fn child_of( parent: impl Into>, metadata: &'static Metadata<'static>, fields: &'a ValueSet<'_>, ) Constructs a new `Event` with the specified metadata and set of values, and observes it with the current subscriber and an explicit parent. ``` -------------------------------- ### Accessing Inner Value of `Instrumented` Source: https://docs.rs/tracing/latest/src/tracing/instrument.rs.html Provides methods to get references to the inner wrapped type, both pinned and mutable. ```rust /// Get a pinned reference to the wrapped type. pub fn inner_pin_ref(self: Pin<&Self>) -> Pin<&T> { self.project_ref().span_and_inner_pin_ref().1 } /// Get a pinned mutable reference to the wrapped type. pub fn inner_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T> { self.project().span_and_inner_pin_mut().1 } ``` -------------------------------- ### Instrumenting functions and events with tracing Source: https://docs.rs/tracing/latest/tracing/index.html Demonstrates the use of the #[tracing::instrument] attribute and various event macros like debug!, info!, and error!. ```rust use std::{error::Error, io}; use tracing::{debug, error, info, span, warn, Level}; // the `#[tracing::instrument]` attribute creates and enters a span // every time the instrumented function is called. The span is named after the // the function or method. Parameters passed to the function are recorded as fields. #[tracing::instrument] pub fn shave(yak: usize) -> Result<(), Box> { // this creates an event at the DEBUG level with two fields: // - `excitement`, with the key "excitement" and the value "yay!" // - `message`, with the key "message" and the value "hello! I'm gonna shave a yak." // // unlike other fields, `message`'s shorthand initialization is just the string itself. debug!(excitement = "yay!", "hello! I'm gonna shave a yak."); if yak == 3 { warn!("could not locate yak!"); // note that this is intended to demonstrate `tracing`'s features, not idiomatic // error handling! in a library or application, you should consider returning // a dedicated `YakError`. libraries like snafu or thiserror make this easy. return Err(io::Error::new(io::ErrorKind::Other, "shaving yak failed!").into()); } else { debug!("yak shaved successfully"); } Ok(()) } pub fn shave_all(yaks: usize) -> usize { // Constructs a new span named "shaving_yaks" at the TRACE level, // and a field whose key is "yaks". This is equivalent to writing: // // let span = span!(Level::TRACE, "shaving_yaks", yaks = yaks); // // local variables (`yaks`) can be used as field values // without an assignment, similar to struct initializers. let _span = span!(Level::TRACE, "shaving_yaks", yaks).entered(); info!("shaving yaks"); let mut yaks_shaved = 0; for yak in 1..=yaks { let res = shave(yak); debug!(yak, shaved = res.is_ok()); if let Err(ref error) = res { // Like spans, events can also use the field initialization shorthand. // In this instance, `yak` is the field being initalized. error!(yak, error = error.as_ref(), "failed to shave yak!"); } else { yaks_shaved += 1; } debug!(yaks_shaved); } yaks_shaved } ``` -------------------------------- ### Get Event Metadata Source: https://docs.rs/tracing/latest/tracing/event/struct.Event.html Returns metadata describing this Event. The metadata includes information such as the event's name and level. ```rust pub fn metadata(&self) -> &'static Metadata<'static> ``` -------------------------------- ### Get Metadata Line Number Source: https://docs.rs/tracing/latest/struct.Metadata.html Returns the line number in the source code file where the span occurred, or None if unknown. ```rust pub fn line(&self) -> Option ``` -------------------------------- ### Create and Enter a Span using `span!` Macro Source: https://docs.rs/tracing/latest/index.html Use the `span!` macro to construct a `Span` struct. The `enter()` method records the span entry and returns a RAII guard that exits the span when dropped. ```rust use tracing::{span, Level}; // Construct a new span named "my span" with trace log level. let span = span!(Level::TRACE, "my span"); // Enter the span, returning a guard object. let _enter = span.enter(); // Any trace events that occur before the guard is dropped will occur // within the span. // Dropping the guard will exit the span. ``` -------------------------------- ### Event Struct and Creation Source: https://docs.rs/tracing/latest/tracing/struct.Event.html Details on creating and initializing Event objects. ```APIDOC ## Event Struct `Event`s represent single points in time where something occurred during the execution of a program. They exist within the context of a span and have structured key-value data known as fields. ### `pub fn dispatch(metadata: &'static Metadata<'static>, fields: &'a ValueSet<'_>)` Constructs a new `Event` with the specified metadata and set of values, and observes it with the current subscriber. ### `pub fn new( metadata: &'static Metadata<'static>, fields: &'a ValueSet<'a>, ) -> Event<'a>` Returns a new `Event` in the current span, with the specified metadata and set of values. ### `pub fn new_child_of( parent: impl Into>, metadata: &'static Metadata<'static>, fields: &'a ValueSet<'a>, ) -> Event<'a>` Returns a new `Event` as a child of the specified span, with the provided metadata and set of values. ### `pub fn child_of( parent: impl Into>, metadata: &'static Metadata<'static>, fields: &'a ValueSet<'_>, )` Constructs a new `Event` with the specified metadata and set of values, and observes it with the current subscriber and an explicit parent. ``` -------------------------------- ### Basic Trace Event Source: https://docs.rs/tracing/latest/tracing/macro.trace.html Use this snippet to create a basic trace event with structured fields like `position` and `origin_dist`. Ensure the `tracing` crate is imported. ```rust use tracing::trace; let pos = Position { x: 3.234, y: -1.223 }; let origin_dist = pos.dist(Position::ORIGIN); trace!(position = ?pos, ?origin_dist); ``` -------------------------------- ### Implement Subscriber filtering Source: https://docs.rs/tracing/latest/tracing/struct.Level.html Example of using LevelFilter within a custom Subscriber to enable or disable spans and events based on their level. ```rust use tracing_core::{span, Event, Level, LevelFilter, Subscriber, Metadata}; #[derive(Debug)] pub struct MySubscriber { /// The most verbose level that this subscriber will enable. max_level: LevelFilter, // ... } impl MySubscriber { /// Returns a new `MySubscriber` which will record spans and events up to /// `max_level`. pub fn with_max_level(max_level: LevelFilter) -> Self { Self { max_level, // ... } } } impl Subscriber for MySubscriber { fn enabled(&self, meta: &Metadata<'_>) -> bool { // A span or event is enabled if it is at or below the configured // maximum level. meta.level() <= &self.max_level } // This optional method returns the most verbose level that this // subscriber will enable. Although implementing this method is not // *required*, it permits additional optimizations when it is provided, // allowing spans and events above the max level to be skipped // more efficiently. fn max_level_hint(&self) -> Option { Some(self.max_level) } // Implement the rest of the subscriber... fn new_span(&self, span: &span::Attributes<'_>) -> span::Id { // ... } fn event(&self, event: &Event<'_>) { // ... } // ... } ``` -------------------------------- ### Basic Span Entry and Exit Source: https://docs.rs/tracing/latest/src/tracing/span.rs.html Demonstrates the basic usage of entering and exiting a span using `Span::enter` and its guard. This is suitable for synchronous code. ```rust # use tracing::{span, Level}; let span = span!(Level::INFO, "my_span"); let guard = span.enter(); // code here is within the span ``` -------------------------------- ### Record event fields Source: https://docs.rs/tracing/latest/index.html Basic syntax for recording an event with multiple fields using key-value pairs. ```rust // records an event with two fields: // - "answer", with the value 42 // - "question", with the value "life, the universe and everything" event!(Level::INFO, answer = 42, question = "life, the universe, and everything"); ``` -------------------------------- ### Record an Event using `event!` Macro Source: https://docs.rs/tracing/latest/index.html Use the `event!` macro to record a trace event. Specify the `Level` and a message. ```rust use tracing::{event, Level}; event!(Level::INFO, "something has happened!"); ``` -------------------------------- ### Record event fields Source: https://docs.rs/tracing/latest/tracing/index.html Basic syntax for recording an event with multiple key-value fields. ```rust event!(Level::INFO, answer = 42, question = "life, the universe, and everything"); ``` -------------------------------- ### Get Event Fields Source: https://docs.rs/tracing/latest/tracing/event/struct.Event.html Returns an iterator over the set of values (fields) on this Event. This allows access to the structured data associated with the event. ```rust pub fn fields(&self) -> Iter ``` -------------------------------- ### Accessing `Span` and Inner Value with Pinning Source: https://docs.rs/tracing/latest/src/tracing/instrument.rs.html Helper methods to get mutable and immutable pinned references to the span and the inner value. ```rust /// Get a mutable reference to the [`Span`] a pinned mutable reference to /// the wrapped type. fn span_and_inner_pin_mut(self) -> (&'a mut Span, Pin<&'a mut T>) { // SAFETY: As long as `ManuallyDrop` does not move, `T` won't move // and `inner` is valid, because `ManuallyDrop::drop` is called // only inside `Drop` of the `Instrumented`. let inner = unsafe { self.inner.map_unchecked_mut(|v| &mut **v) }; (self.span, inner) } /// Get a reference to the [`Span`] a pinned reference to the wrapped type. fn span_and_inner_pin_ref(self) -> (&'a Span, Pin<&'a T>) { // SAFETY: As long as `ManuallyDrop` does not move, `T` won't move // and `inner` is valid, because `ManuallyDrop::drop` is called // only inside `Drop` of the `Instrumented`. let inner = unsafe { self.inner.map_unchecked(|v| &**v) }; (self.span, inner) } ``` -------------------------------- ### Check Event Enabled with Level and Fields Source: https://docs.rs/tracing/latest/tracing/macro.event_enabled.html This example shows how to use event_enabled! to check if an event with a specific level and fields would be enabled. ```rust if event_enabled!(Level::DEBUG, foo_field) { // some expensive work... } ``` -------------------------------- ### Visit Trait Documentation Source: https://docs.rs/tracing/latest/tracing/field/trait.Visit.html Documentation for the tracing::field::Visit trait, outlining its purpose and methods. ```APIDOC ## Trait tracing::field::Visit ### Description Visits typed values. An instance of `Visit` (“a visitor”) represents the logic necessary to record field values of various types. When an implementor of `Value` is recorded, it calls the appropriate method on the provided visitor to indicate the type that value should be recorded as. When a `Subscriber` implementation records an `Event` or a set of `Value`s added to a `Span`, it can pass an `&mut Visit` to the `record` method on the provided `ValueSet` or `Event`. This visitor will then be used to record all the field-value pairs present on that `Event` or `ValueSet`. ### Required Methods #### fn record_debug(&mut self, field: &Field, value: &dyn Debug) Visit a value implementing `fmt::Debug`. ### Provided Methods #### fn record_value(&mut self, field: &Field, value: Value<'_>) Available on **`tracing_unstable`and crate feature`valuable`** only. Visits an arbitrary type implementing the `valuable` crate’s `Valuable` trait. #### fn record_f64(&mut self, field: &Field, value: f64) Visit a double-precision floating point value. #### fn record_i64(&mut self, field: &Field, value: i64) Visit a signed 64-bit integer value. #### fn record_u64(&mut self, field: &Field, value: u64) Visit an unsigned 64-bit integer value. #### fn record_i128(&mut self, field: &Field, value: i128) Visit a signed 128-bit integer value. #### fn record_u128(&mut self, field: &Field, value: u128) Visit an unsigned 128-bit integer value. #### fn record_bool(&mut self, field: &Field, value: bool) Visit a boolean value. #### fn record_str(&mut self, field: &Field, value: &str) Visit a string value. #### fn record_bytes(&mut self, field: &Field, value: &[u8]) Visit a byte slice. #### fn record_error(&mut self, field: &Field, value: &(dyn Error + 'static)) Note: The record_error trait method is only available when the Rust standard library is present, as it requires the std::error::Error trait. ``` -------------------------------- ### Equivalent span! macro usage Source: https://docs.rs/tracing/latest/tracing/macro.trace_span.html Demonstrates the equivalence between trace_span! and span! for basic usage. ```rust trace_span!("my_span"); // is equivalent to: span!(Level::TRACE, "my_span"); ``` -------------------------------- ### Level Filtering with LevelFilter Source: https://docs.rs/tracing/latest/tracing/struct.Level.html Explains how LevelFilter is used for filtering spans and events based on their verbosity level. Includes examples of comparing Level and LevelFilter. ```APIDOC ### §Filtering `Level`s are typically used to implement filtering that determines which spans and events are enabled. Depending on the use case, more or less verbose diagnostics may be desired. For example, when running in development, `DEBUG`-level traces may be enabled by default. When running in production, only `INFO`-level and lower traces might be enabled. Libraries may include very verbose diagnostics at the `DEBUG` and/or `TRACE` levels. Applications using those libraries typically chose to ignore those traces. However, when debugging an issue involving said libraries, it may be useful to temporarily enable the more verbose traces. The `LevelFilter` type is provided to enable filtering traces by verbosity. `Level`s can be compared against `LevelFilter`s, and `LevelFilter` has a variant for each `Level`, which compares analogously to that level. In addition, `LevelFilter` adds a `LevelFilter::OFF` variant, which is considered “less verbose” than every other `Level`. This is intended to allow filters to completely disable tracing in a particular context. For example: ```rust use tracing_core::{Level, LevelFilter}; assert!(LevelFilter::OFF < Level::TRACE); assert!(LevelFilter::TRACE > Level::DEBUG); assert!(LevelFilter::ERROR < Level::WARN); assert!(LevelFilter::INFO <= Level::DEBUG); assert!(LevelFilter::INFO >= Level::INFO); ``` ``` -------------------------------- ### Get Event Parent Source: https://docs.rs/tracing/latest/tracing/event/struct.Event.html Returns the new event’s explicitly-specified parent, if there is one. Returns `None` if the event is a root or a child of the current span. ```rust pub fn parent(&self) -> Option<&Id> ```