//! `Span` and `Event` key-value data. //! //! Spans and events may be annotated with key-value data, referred to as known //! as _fields_. These fields consist of a mapping from a key (corresponding to //! a `&str` but represented internally as an array index) to a [`Value`]. //! //! # `Value`s and `Subscriber`s //! //! `Subscriber`s consume `Value`s as fields attached to [span]s or [`Event`]s. //! The set of field keys on a given span or is defined on its [`Metadata`]. //! When a span is created, it provides [`Attributes`] to the `Subscriber`'s //! [`new_span`] method, containing any fields whose values were provided when //! the span was created; and may call the `Subscriber`'s [`record`] method //! with additional [`Record`]s if values are added for more of its fields. //! Similarly, the [`Event`] type passed to the subscriber's [`event`] method //! will contain any fields attached to each event. //! //! `tracing` represents values as either one of a set of Rust primitives //! (`i64`, `u64`, `f64`, `i128`, `u128`, `bool`, and `&str`) or using a //! `fmt::Display` or `fmt::Debug` implementation. `Subscriber`s are provided //! these primitive value types as `dyn Value` trait objects. //! //! These trait objects can be formatted using `fmt::Debug`, but may also be //! recorded as typed data by calling the [`Value::record`] method on these //! trait objects with a _visitor_ implementing the [`Visit`] trait. This trait //! represents the behavior used to record values of various types. For example, //! an implementation of `Visit` might record integers by incrementing counters //! for their field names rather than printing them. //! //! //! # Using `valuable` //! //! `tracing`'s [`Value`] trait is intentionally minimalist: it supports only a small //! number of Rust primitives as typed values, and only permits recording //! user-defined types with their [`fmt::Debug`] or [`fmt::Display`] //! implementations. However, there are some cases where it may be useful to record //! nested values (such as arrays, `Vec`s, or `HashMap`s containing values), or //! user-defined `struct` and `enum` types without having to format them as //! unstructured text. //! //! To address `Value`'s limitations, `tracing` offers experimental support for //! the [`valuable`] crate, which provides object-safe inspection of structured //! values. User-defined types can implement the [`valuable::Valuable`] trait, //! and be recorded as a `tracing` field by calling their [`as_value`] method. //! If the [`Subscriber`] also supports the `valuable` crate, it can //! then visit those types fields as structured values using `valuable`. //! //! <pre class="ignore" style="white-space:normal;font:inherit;"> //! <strong>Note</strong>: <code>valuable</code> support is an //! <a href = "../index.html#unstable-features">unstable feature</a>. See //! the documentation on unstable features for details on how to enable it. //! </pre> //! //! For example: //! ```ignore //! // Derive `Valuable` for our types: //! use valuable::Valuable; //! //! #[derive(Clone, Debug, Valuable)] //! struct User { //! name: String, //! age: u32, //! address: Address, //! } //! //! #[derive(Clone, Debug, Valuable)] //! struct Address { //! country: String, //! city: String, //! street: String, //! } //! //! let user = User { //! name: "Arwen Undomiel".to_string(), //! age: 3000, //! address: Address { //! country: "Middle Earth".to_string(), //! city: "Rivendell".to_string(), //! street: "leafy lane".to_string(), //! }, //! }; //! //! // Recording `user` as a `valuable::Value` will allow the `tracing` subscriber //! // to traverse its fields as a nested, typed structure: //! tracing::info!(current_user = user.as_value()); //! ``` //! //! Alternatively, the [`valuable()`] function may be used to convert a type //! implementing [`Valuable`] into a `tracing` field value. //! //! When the `valuable` feature is enabled, the [`Visit`] trait will include an //! optional [`record_value`] method. `Visit` implementations that wish to //! record `valuable` values can implement this method with custom behavior. //! If a visitor does not implement `record_value`, the [`valuable::Value`] will //! be forwarded to the visitor's [`record_debug`] method. //! //! [`valuable`]: https://crates.io/crates/valuable //! [`as_value`]: valuable::Valuable::as_value //! [`Subscriber`]: crate::Subscriber //! [`record_value`]: Visit::record_value //! [`record_debug`]: Visit::record_debug //! //! [span]: super::span //! [`Event`]: super::event::Event //! [`Metadata`]: super::metadata::Metadata //! [`Attributes`]: super::span::Attributes //! [`Record`]: super::span::Record //! [`new_span`]: super::subscriber::Subscriber::new_span //! [`record`]: super::subscriber::Subscriber::record //! [`event`]: super::subscriber::Subscriber::event //! [`Value::record`]: Value::record usecrate::callsite; usecrate::stdlib::{
borrow::Borrow,
fmt,
hash::{Hash, Hasher},
num,
ops::Range,
string::String,
};
useself::private::ValidLen;
/// An opaque key allowing _O_(1) access to a field in a `Span`'s key-value /// data. /// /// As keys are defined by the _metadata_ of a span, rather than by an /// individual instance of a span, a key may be used to access the same field /// across all instances of a given span with the same metadata. Thus, when a /// subscriber observes a new span, it need only access a field by name _once_, /// and use the key for that name for all other accesses. #[derive(Debug)] pubstruct Field {
i: usize,
fields: FieldSet,
}
/// An empty field. /// /// This can be used to indicate that the value of a field is not currently /// present but will be recorded later. /// /// When a field's value is `Empty`. it will not be recorded. #[derive(Debug, Eq, PartialEq)] pubstruct Empty;
/// Describes the fields present on a span. /// /// ## Equality /// /// In well-behaved applications, two `FieldSet`s [initialized] with equal /// [callsite identifiers] will have identical fields. Consequently, in release /// builds, [`FieldSet::eq`] *only* checks that its arguments have equal /// callsites. However, the equality of field names is checked in debug builds. /// /// [initialized]: Self::new /// [callsite identifiers]: callsite::Identifier pubstruct FieldSet { /// The names of each field on the described span.
names: &'static [&'static str], /// The callsite where the described span originates.
callsite: callsite::Identifier,
}
/// A set of fields and values for a span. pubstruct ValueSet<'a> {
values: &'a [(&'a Field, Option<&'a (dyn Value + 'a)>)],
fields: &'a FieldSet,
}
/// An iterator over a set of fields. #[derive(Debug)] pubstruct Iter {
idxs: Range<usize>,
fields: FieldSet,
}
/// 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`. /// /// # Examples /// /// A simple visitor that writes to a string might be implemented like so: /// ``` /// # extern crate tracing_core as tracing; /// 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(); /// } /// } /// ``` /// 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. /// /// The `Visit` trait provides default implementations for `record_i64`, /// `record_u64`, `record_bool`, `record_str`, and `record_error`, which simply /// forward the recorded value to `record_debug`. Thus, `record_debug` is the /// only method which a `Visit` implementation *must* implement. However, /// visitors may override the default implementations of these functions in /// order to implement type-specific behavior. /// /// Additionally, when a visitor receives a value of a type it does not care /// about, it is free to ignore those values completely. For example, a /// visitor which only records numeric data might look like this: /// /// ``` /// # extern crate tracing_core as tracing; /// # use std::fmt::{self, Write}; /// # use tracing::field::{Value, 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: &fmt::Debug) { /// // Do nothing /// } /// } /// ``` /// /// This visitor (which is probably not particularly useful) 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`. /// /// <div class="example-wrap" style="display:inline-block"> /// <pre class="ignore" style="white-space:normal;font:inherit;"> /// <strong>Note</strong>: The <code>record_error</code> trait method is only /// available when the Rust standard library is present, as it requires the /// <code>std::error::Error</code> trait. /// </pre></div> /// /// [recorded]: Value::record /// [`Subscriber`]: super::subscriber::Subscriber /// [records an `Event`]: super::subscriber::Subscriber::event /// [set of `Value`s added to a `Span`]: super::subscriber::Subscriber::record /// [`Event`]: super::event::Event pubtrait Visit { /// Visits an arbitrary type implementing the [`valuable`] crate's `Valuable` trait. /// /// [`valuable`]: https://docs.rs/valuable #[cfg(all(tracing_unstable, feature = "valuable"))] #[cfg_attr(docsrs, doc(cfg(all(tracing_unstable, feature = "valuable"))))] fn record_value(&mutself, field: &Field, value: valuable::Value<'_>) { self.record_debug(field, &value)
}
/// Visit a double-precision floating point value. fn record_f64(&mutself, field: &Field, value: f64) { self.record_debug(field, &value)
}
/// Visit a signed 64-bit integer value. fn record_i64(&mutself, field: &Field, value: i64) { self.record_debug(field, &value)
}
/// Records a type implementing `Error`. /// /// <div class="example-wrap" style="display:inline-block"> /// <pre class="ignore" style="white-space:normal;font:inherit;"> /// <strong>Note</strong>: This is only enabled when the Rust standard library is /// present. /// </pre> #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] fn record_error(&mutself, field: &Field, value: &(dyn std::error::Error + 'static)) { self.record_debug(field, &DisplayValue(value))
}
/// Visit a value implementing `fmt::Debug`. fn record_debug(&mutself, field: &Field, value: &dyn fmt::Debug);
}
/// A field value of an erased type. /// /// Implementors of `Value` may call the appropriate typed recording methods on /// the [visitor] passed to their `record` method in order to indicate how /// their data should be recorded. /// /// [visitor]: Visit pubtrait Value: crate::sealed::Sealed { /// Visits this value with the given `Visitor`. fn record(&self, key: &Field, visitor: &mutdyn Visit);
}
/// A `Value` which serializes using `fmt::Display`. /// /// Uses `record_debug` in the `Value` implementation to /// avoid an unnecessary evaluation. #[derive(Clone)] pubstruct DisplayValue<T: fmt::Display>(T);
/// A `Value` which serializes as a string using `fmt::Debug`. #[derive(Clone)] pubstruct DebugValue<T: fmt::Debug>(T);
/// Wraps a type implementing `fmt::Display` as a `Value` that can be /// recorded using its `Display` implementation. pubfn display<T>(t: T) -> DisplayValue<T> where
T: fmt::Display,
{
DisplayValue(t)
}
/// Wraps a type implementing `fmt::Debug` as a `Value` that can be /// recorded using its `Debug` implementation. pubfn debug<T>(t: T) -> DebugValue<T> where
T: fmt::Debug,
{
DebugValue(t)
}
/// Wraps a type implementing [`Valuable`] as a `Value` that /// can be recorded using its `Valuable` implementation. /// /// [`Valuable`]: https://docs.rs/valuable/latest/valuable/trait.Valuable.html #[cfg(all(tracing_unstable, feature = "valuable"))] #[cfg_attr(docsrs, doc(cfg(all(tracing_unstable, feature = "valuable"))))] pubfn valuable<T>(t: &T) -> valuable::Value<'_> where
T: valuable::Valuable,
{
t.as_value()
}
macro_rules! impl_one_value {
(f32, $op:expr, $record:ident) => {
impl_one_value!(normal, f32, $op, $record);
};
(f64, $op:expr, $record:ident) => {
impl_one_value!(normal, f64, $op, $record);
};
(bool, $op:expr, $record:ident) => {
impl_one_value!(normal, bool, $op, $record);
};
($value_ty:tt, $op:expr, $record:ident) => {
impl_one_value!(normal, $value_ty, $op, $record);
impl_one_value!(nonzero, $value_ty, $op, $record);
};
(normal, $value_ty:tt, $op:expr, $record:ident) => { impl $crate::sealed::Sealed for $value_ty {} impl $crate::field::Value for $value_ty { fn record(&self, key: &$crate::field::Field, visitor: &mutdyn $crate::field::Visit) {
visitor.$record(key, $op(*self))
}
}
};
(nonzero, $value_ty:tt, $op:expr, $record:ident) => { // This `use num::*;` is reported as unused because it gets emitted // for every single invocation of this macro, so there are multiple `use`s. // All but the first are useless indeed. // We need this import because we can't write a path where one part is // the `ty_to_nonzero!($value_ty)` invocation. #[allow(clippy::useless_attribute, unused)] use num::*; impl $crate::sealed::Sealed for ty_to_nonzero!($value_ty) {} impl $crate::field::Value for ty_to_nonzero!($value_ty) { fn record(&self, key: &$crate::field::Field, visitor: &mutdyn $crate::field::Visit) {
visitor.$record(key, $op(self.get()))
}
}
};
}
impl<'a, T: ?Sized> crate::sealed::Sealed for &'a T where T: Value + crate::sealed::Sealed + 'a {}
impl<'a, T: ?Sized> Value for &'a T where
T: Value + 'a,
{ fn record(&self, key: &Field, visitor: &mutdyn Visit) {
(*self).record(key, visitor)
}
}
impl<'a, T: ?Sized> crate::sealed::Sealed for &'a mut T where T: Value + crate::sealed::Sealed + 'a {}
impl<'a, T: ?Sized> Value for &'a mut T where
T: Value + 'a,
{ fn record(&self, key: &Field, visitor: &mutdyn Visit) { // Don't use `(*self).record(key, visitor)`, otherwise would // cause stack overflow due to `unconditional_recursion`.
T::record(self, key, visitor)
}
}
impl<'a> crate::sealed::Sealed for fmt::Arguments<'a> {}
impl<'a> Value for fmt::Arguments<'a> { fn record(&self, key: &Field, visitor: &mutdyn Visit) {
visitor.record_debug(key, self)
}
}
impl<T: ?Sized> crate::sealed::Sealed forcrate::stdlib::boxed::Box<T> where T: Value {}
implcrate::sealed::Sealed for String {} impl Value for String { fn record(&self, key: &Field, visitor: &mutdyn Visit) {
visitor.record_str(key, self.as_str())
}
}
impl fmt::Debug fordyn Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // We are only going to be recording the field value, so we don't // actually care about the field name here. struct NullCallsite; static NULL_CALLSITE: NullCallsite = NullCallsite; implcrate::callsite::Callsite for NullCallsite { fn set_interest(&self, _: crate::subscriber::Interest) {
unreachable!("you somehow managed to register the null callsite?")
}
fn metadata(&self) -> &crate::Metadata<'_> {
unreachable!("you somehow managed to access the null callsite?")
}
}
static FIELD: Field = Field {
i: 0,
fields: FieldSet::new(&[], crate::identify_callsite!(&NULL_CALLSITE)),
};
letmut res = Ok(()); self.record(&FIELD, &mut |_: &Field, val: &dyn fmt::Debug| {
res = write!(f, "{:?}", val);
});
res
}
}
impl Hash for Field { fn hash<H>(&self, state: &mut H) where
H: Hasher,
{ self.callsite().hash(state); self.i.hash(state);
}
}
impl Clone for Field { fn clone(&self) -> Self {
Field {
i: self.i,
fields: FieldSet {
names: self.fields.names,
callsite: self.fields.callsite(),
},
}
}
}
// ===== impl FieldSet =====
impl FieldSet { /// Constructs a new `FieldSet` with the given array of field names and callsite. pubconstfn new(names: &'static [&'static str], callsite: callsite::Identifier) -> Self { Self { names, callsite }
}
/// Returns an [`Identifier`] that uniquely identifies the [`Callsite`] /// which defines this set of fields.. /// /// [`Identifier`]: super::callsite::Identifier /// [`Callsite`]: super::callsite::Callsite pub(crate) fn callsite(&self) -> callsite::Identifier {
callsite::Identifier(self.callsite.0)
}
/// Returns the [`Field`] named `name`, or `None` if no such field exists. /// /// [`Field`]: super::Field pubfn field<Q: ?Sized>(&self, name: &Q) -> Option<Field> where
Q: Borrow<str>,
{ let name = &name.borrow(); self.names.iter().position(|f| f == name).map(|i| Field {
i,
fields: FieldSet {
names: self.names,
callsite: self.callsite(),
},
})
}
/// Returns `true` if `self` contains the given `field`. /// /// <div class="example-wrap" style="display:inline-block"> /// <pre class="ignore" style="white-space:normal;font:inherit;"> /// <strong>Note</strong>: If <code>field</code> shares a name with a field /// in this <code>FieldSet</code>, but was created by a <code>FieldSet</code> /// with a different callsite, this <code>FieldSet</code> does <em>not</em> /// contain it. This is so that if two separate span callsites define a field /// named "foo", the <code>Field</code> corresponding to "foo" for each /// of those callsites are not equivalent. /// </pre></div> pubfn contains(&self, field: &Field) -> bool {
field.callsite() == self.callsite() && field.i <= self.len()
}
/// Returns an iterator over the `Field`s in this `FieldSet`. pubfn iter(&self) -> Iter { let idxs = 0..self.len();
Iter {
idxs,
fields: FieldSet {
names: self.names,
callsite: self.callsite(),
},
}
}
/// Returns a new `ValueSet` with entries for this `FieldSet`'s values. /// /// Note that a `ValueSet` may not be constructed with arrays of over 32 /// elements. #[doc(hidden)] pubfn value_set<'v, V>(&'v self, values: &'v V) -> ValueSet<'v> where
V: ValidLen<'v>,
{
ValueSet {
fields: self,
values: values.borrow(),
}
}
/// Returns the number of fields in this `FieldSet`. #[inline] pubfn len(&self) -> usize { self.names.len()
}
/// Returns whether or not this `FieldSet` has fields. #[inline] pubfn is_empty(&self) -> bool { self.names.is_empty()
}
}
impl<'a> IntoIterator for &'a FieldSet { type IntoIter = Iter; type Item = Field; #[inline] fn into_iter(self) -> Self::IntoIter { self.iter()
}
}
impl PartialEq for FieldSet { fn eq(&self, other: &Self) -> bool { if core::ptr::eq(&self, &other) { true
} elseif cfg!(not(debug_assertions)) { // In a well-behaving application, two `FieldSet`s can be assumed to // be totally equal so long as they share the same callsite. self.callsite == other.callsite
} else { // However, when debug-assertions are enabled, do NOT assume that // the application is well-behaving; check every the field names of // each `FieldSet` for equality.
// `FieldSet` is destructured here to ensure a compile-error if the // fields of `FieldSet` change. letSelf {
names: lhs_names,
callsite: lhs_callsite,
} = self;
// Check callsite equality first, as it is probably cheaper to do // than str equality.
lhs_callsite == rhs_callsite && lhs_names == rhs_names
}
}
}
// ===== impl Iter =====
impl Iterator for Iter { type Item = Field; fn next(&mutself) -> Option<Field> { let i = self.idxs.next()?;
Some(Field {
i,
fields: FieldSet {
names: self.fields.names,
callsite: self.fields.callsite(),
},
})
}
}
// ===== impl ValueSet =====
impl<'a> ValueSet<'a> { /// Returns an [`Identifier`] that uniquely identifies the [`Callsite`] /// defining the fields this `ValueSet` refers to. /// /// [`Identifier`]: super::callsite::Identifier /// [`Callsite`]: super::callsite::Callsite #[inline] pubfn callsite(&self) -> callsite::Identifier { self.fields.callsite()
}
/// Visits all the fields in this `ValueSet` with the provided [visitor]. /// /// [visitor]: Visit pubfn record(&self, visitor: &mutdyn Visit) { let my_callsite = self.callsite(); for (field, value) inself.values { if field.callsite() != my_callsite { continue;
} iflet Some(value) = value {
value.record(field, visitor);
}
}
}
/// Returns the number of fields in this `ValueSet` that would be visited /// by a given [visitor] to the [`ValueSet::record()`] method. /// /// [visitor]: Visit /// [`ValueSet::record()`]: ValueSet::record() pubfn len(&self) -> usize { let my_callsite = self.callsite(); self.values
.iter()
.filter(|(field, _)| field.callsite() == my_callsite)
.count()
}
/// Returns `true` if this `ValueSet` contains a value for the given `Field`. pub(crate) fn contains(&self, field: &Field) -> bool {
field.callsite() == self.callsite()
&& self
.values
.iter()
.any(|(key, val)| *key == field && val.is_some())
}
/// Returns true if this `ValueSet` contains _no_ values. pubfn is_empty(&self) -> bool { let my_callsite = self.callsite(); self.values
.iter()
.all(|(key, val)| val.is_none() || key.callsite() != my_callsite)
}
/// Marker trait implemented by arrays which are of valid length to /// construct a `ValueSet`. /// /// `ValueSet`s may only be constructed from arrays containing 32 or fewer /// elements, to ensure the array is small enough to always be allocated on the /// stack. This trait is only implemented by arrays of an appropriate length, /// ensuring that the correct size arrays are used at compile-time. pubtrait ValidLen<'a>: Borrow<[(&'a Field, Option<&'a (dyn Value + 'a)>)]> {}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.