Introduce tokio-trace (#827)

<!-- Thank you for your Pull Request. Please provide a description above
and review the requirements below.

Bug fixes and new features should include tests.

Contributors guide:
https://github.com/tokio-rs/tokio/blob/master/CONTRIBUTING.md -->

## Motivation

In asynchronous systems like Tokio, interpreting traditional log
messages can often be quite challenging. Since individual tasks are
multiplexed on the same thread, associated events and log lines are
intermixed making it difficult to trace the logic flow. Currently, none
of the available logging frameworks or libraries in Rust offer the
ability to trace logical paths through a futures-based program.

There also are complementary goals that can be accomplished with such a
system. For example, metrics / instrumentation can be tracked by
observing emitted events, or trace data can be exported to a distributed
tracing or event processing system.

In addition, it can often be useful to generate this diagnostic data in
a structured manner that can be consumed programmatically. While prior
art for structured logging in Rust exists, it is not currently
standardized, and is not "Tokio-friendly".

## Solution

This branch adds a new library to the tokio project, `tokio-trace`.
`tokio-trace` expands upon logging-style diagnostics by allowing
libraries and applications to record structured events with additional
information about *temporality* and *causality* --- unlike a log
message, a span in `tokio-trace` has a beginning and end time, may be
entered and exited by the flow of execution, and may exist within a
nested tree of similar spans. In addition, `tokio-trace` spans are
*structured*, with the ability to record typed data as well as textual
messages.

The `tokio-trace-core` crate contains the core primitives for this
system, which are expected to remain stable, while `tokio-trace` crate
provides a more "batteries-included" API. In particular, it provides
macros which are a superset of the `log` crate's `error!`, `warn!`,
`info!`, `debug!`, and `trace!` macros, allowing users to begin the
process of adopting `tokio-trace` by performing a drop-in replacement.

## Notes

Work on this project had previously been carried out in the
[tokio-trace-prototype] repository. In addition to the `tokio-trace` and
`tokio-trace-core` crates, the `tokio-trace-prototype` repo also
contains prototypes or sketches of adapter, compatibility, and utility
crates which provide useful functionality for `tokio-trace`, but these
crates are not yet ready for a release. When this branch is merged, that
repository will be archived, and the remaining unstable crates will be
moved to a new `tokio-trace-nursery` repository. Remaining issues on the
`tokio-trace-prototype` repo will be moved to the appropriate new repo.

The crates added in this branch are not _identical_ to the current head
of the `tokio-trace-prototype` repo, as I did some final clean-up and docs
polish in this branch prior to merging this PR.

[tokio-trace-prototype]: https://github.com/hawkw/tokio-trace-prototype

Closes: #561

Signed-off-by: Eliza Weisman <[email protected]>
This commit is contained in:
Eliza Weisman
2019-02-19 12:15:01 -08:00
committed by GitHub
parent d1d72dc1c8
commit c08e73c8d4
35 changed files with 6358 additions and 0 deletions
+54
View File
@@ -0,0 +1,54 @@
//! Structured data associated with `Span`s and `Event`s.
pub use tokio_trace_core::field::*;
use Metadata;
/// Trait implemented to allow a type to be used as a field key.
///
/// **Note**: Although this is implemented for both the [`Field`] type *and* any
/// type that can be borrowed as an `&str`, only `Field` allows _O_(1) access.
/// Indexing a field with a string results in an iterative search that performs
/// string comparisons. Thus, if possible, once the key for a field is known, it
/// should be used whenever possible.
pub trait AsField: ::sealed::Sealed {
/// Attempts to convert `&self` into a `Field` with the specified `metadata`.
///
/// If `metadata` defines this field, then the field is returned. Otherwise,
/// this returns `None`.
fn as_field(&self, metadata: &Metadata) -> Option<Field>;
}
// ===== impl AsField =====
impl AsField for Field {
#[inline]
fn as_field(&self, metadata: &Metadata) -> Option<Field> {
if self.callsite() == metadata.callsite() {
Some(self.clone())
} else {
None
}
}
}
impl<'a> AsField for &'a Field {
#[inline]
fn as_field(&self, metadata: &Metadata) -> Option<Field> {
if self.callsite() == metadata.callsite() {
Some((*self).clone())
} else {
None
}
}
}
impl AsField for str {
#[inline]
fn as_field(&self, metadata: &Metadata) -> Option<Field> {
metadata.fields().field(&self)
}
}
impl ::sealed::Sealed for Field {}
impl<'a> ::sealed::Sealed for &'a Field {}
impl ::sealed::Sealed for str {}
+983
View File
@@ -0,0 +1,983 @@
//! A scoped, structured logging and diagnostics system.
//!
//! # Overview
//!
//! `tokio-trace` is a framework for instrumenting Rust programs to collect
//! structured, event-based diagnostic information.
//!
//! In asynchronous systems like Tokio, interpreting traditional log messages can
//! often be quite challenging. Since individual tasks are multiplexed on the same
//! thread, associated events and log lines are intermixed making it difficult to
//! trace the logic flow. `tokio-trace` expands upon logging-style diagnostics by
//! allowing libraries and applications to record structured events with additional
//! information about *temporality* and *causality* — unlike a log message, a span
//! in `tokio-trace` has a beginning and end time, may be entered and exited by the
//! flow of execution, and may exist within a nested tree of similar spans. In
//! addition, `tokio-trace` spans are *structured*, with the ability to record typed
//! data as well as textual messages.
//!
//! The `tokio-trace` crate provides the APIs necessary for instrumenting libraries
//! and applications to emit trace data.
//!
//! # Core Concepts
//!
//! The core of `tokio-trace`'s API is composed of `Event`s, `Span`s, and
//! `Subscriber`s. We'll cover these in turn.
//!
//! ## `Span`s
//!
//! A [`Span`] represents a _period of time_ during which a program was executing
//! in some context. A thread of execution is said to _enter_ a span when it
//! begins executing in that context, and to _exit_ the span when switching to
//! another context. The span in which a thread is currently executing is
//! referred to as the _current_ span.
//!
//! Spans form a tree structure — unless it is a root span, all spans have a
//! _parent_, and may have one or more _children_. When a new span is created,
//! the current span becomes the new span's parent. The total execution time of
//! a span consists of the time spent in that span and in the entire subtree
//! represented by its children. Thus, a parent span always lasts for at least
//! as long as the longest-executing span in its subtree.
//!
//! In addition, data may be associated with spans. A span may have _fields_ —
//! a set of key-value pairs describing the state of the program during that
//! span; an optional name, and metadata describing the source code location
//! where the span was originally entered.
//!
//! ### When to use spans
//!
//! As a rule of thumb, spans should be used to represent discrete units of work
//! (e.g., a given request's lifetime in a server) or periods of time spent in a
//! given context (e.g., time spent interacting with an instance of an external
//! system, such as a database).
//!
//! Which scopes in a program correspond to new spans depend somewhat on user
//! intent. For example, consider the case of a loop in a program. Should we
//! construct one span and perform the entire loop inside of that span, like:
//! ```rust
//! # #[macro_use] extern crate tokio_trace;
//! # fn main() {
//! # let n = 1;
//! span!("my loop").enter(|| {
//! for i in 0..n {
//! # let _ = i;
//! // ...
//! }
//! })
//! # }
//! ```
//! Or, should we create a new span for each iteration of the loop, as in:
//! ```rust
//! # #[macro_use] extern crate tokio_trace;
//! # fn main() {
//! # let n = 1u64;
//! for i in 0..n {
//! # let _ = i;
//! span!("my loop", iteration = i).enter(|| {
//! // ...
//! })
//! }
//! # }
//! ```
//!
//! Depending on the circumstances, we might want to do either, or both. For
//! example, if we want to know how long was spent in the loop overall, we would
//! create a single span around the entire loop; whereas if we wanted to know how
//! much time was spent in each individual iteration, we would enter a new span
//! on every iteration.
//!
//! ## Events
//!
//! An [`Event`] represents a _point_ in time. It signifies something that
//! happened while the trace was executing. `Event`s are comparable to the log
//! records emitted by unstructured logging code, but unlike a typical log line,
//! an `Event` may occur within the context of a `Span`. Like a `Span`, it
//! may have fields, and implicitly inherits any of the fields present on its
//! parent span, and it may be linked with one or more additional
//! spans that are not its parent; in this case, the event is said to _follow
//! from_ those spans.
//!
//! Essentially, `Event`s exist to bridge the gap between traditional
//! unstructured logging and span-based tracing. Similar to log records, they
//! may be recorded at a number of levels, and can have unstructured,
//! human-readable messages; however, they also carry key-value data and exist
//! within the context of the tree of spans that comprise a trace. Thus,
//! individual log record-like events can be pinpointed not only in time, but
//! in the logical execution flow of the system.
//!
//! Events are represented as a special case of spans — they are created, they
//! may have fields added, and then they close immediately, without being
//! entered.
//!
//! In general, events should be used to represent points in time _within_ a
//! span — a request returned with a given status code, _n_ new items were
//! taken from a queue, and so on.
//!
//! ## `Subscriber`s
//!
//! As `Span`s and `Event`s occur, they are recorded or aggregated by
//! implementations of the [`Subscriber`] trait. `Subscriber`s are notified
//! when an `Event` takes place and when a `Span` is entered or exited. These
//! notifications are represented by the following `Subscriber` trait methods:
//! + [`observe_event`], called when an `Event` takes place,
//! + [`enter`], called when execution enters a `Span`,
//! + [`exit`], called when execution exits a `Span`
//!
//! In addition, subscribers may implement the [`enabled`] function to _filter_
//! the notifications they receive based on [metadata] describing each `Span`
//! or `Event`. If a call to `Subscriber::enabled` returns `false` for a given
//! set of metadata, that `Subscriber` will *not* be notified about the
//! corresponding `Span` or `Event`. For performance reasons, if no currently
//! active subscribers express interest in a given set of metadata by returning
//! `true`, then the corresponding `Span` or `Event` will never be constructed.
//!
//! # Usage
//!
//! First, add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! tokio-trace = { git = "https://github.com/tokio-rs/tokio" }
//! ```
//!
//! Next, add this to your crate:
//!
//! ```rust
//! #[macro_use]
//! extern crate tokio_trace;
//! # fn main() {}
//! ```
//!
//! `Span`s are constructed using the `span!` macro, and then _entered_
//! to indicate that some code takes place within the context of that `Span`:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate tokio_trace;
//! # fn main() {
//! // Construct a new span named "my span".
//! let mut span = span!("my span");
//! span.enter(|| {
//! // Any trace events in this closure or code called by it will occur within
//! // the span.
//! });
//! // Dropping the span will close it, indicating that it has ended.
//! # }
//! ```
//!
//! `Event`s are created using the `event!` macro, and are recorded when the
//! event is dropped:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate tokio_trace;
//! # fn main() {
//! use tokio_trace::Level;
//! event!(Level::INFO, "something has happened!");
//! # }
//! ```
//!
//! Users of the [`log`] crate should note that `tokio-trace` exposes a set of
//! macros for creating `Event`s (`trace!`, `debug!`, `info!`, `warn!`, and
//! `error!`) which may be invoked with the same syntax as the similarly-named
//! macros from the `log` crate. Often, the process of converting a project to
//! use `tokio-trace` can begin with a simple drop-in replacement.
//!
//! Let's consider the `log` crate's yak-shaving example:
//!
//! ```rust
//! #[macro_use]
//! extern crate tokio_trace;
//! use tokio_trace::field;
//! # #[derive(Debug)] pub struct Yak(String);
//! # impl Yak { fn shave(&mut self, _: u32) {} }
//! # fn find_a_razor() -> Result<u32, u32> { Ok(1) }
//! # fn main() {
//! pub fn shave_the_yak(yak: &mut Yak) {
//! // Create a new span for this invocation of `shave_the_yak`, annotated
//! // with the yak being shaved as a *field* on the span.
//! span!("shave_the_yak", yak = field::debug(&yak)).enter(|| {
//! // Since the span is annotated with the yak, it is part of the context
//! // for everything happening inside the span. Therefore, we don't need
//! // to add it to the message for this event, as the `log` crate does.
//! info!(target: "yak_events", "Commencing yak shaving");
//!
//! loop {
//! match find_a_razor() {
//! Ok(razor) => {
//! // We can add the razor as a field rather than formatting it
//! // as part of the message, allowing subscribers to consume it
//! // in a more structured manner:
//! info!({ razor = field::display(razor) }, "Razor located");
//! yak.shave(razor);
//! break;
//! }
//! Err(err) => {
//! // However, we can also create events with formatted messages,
//! // just as we would for log records.
//! warn!("Unable to locate a razor: {}, retrying", err);
//! }
//! }
//! }
//! })
//! }
//! # }
//! ```
//!
//! You can find examples showing how to use this crate in the examples
//! directory.
//!
//! ### In libraries
//!
//! Libraries should link only to the `tokio-trace` crate, and use the provided
//! macros to record whatever information will be useful to downstream
//! consumers.
//!
//! ### In executables
//!
//! In order to record trace events, executables have to use a `Subscriber`
//! implementation compatible with `tokio-trace`. A `Subscriber` implements a
//! way of collecting trace data, such as by logging it to standard output.
//!
//! Unlike the `log` crate, `tokio-trace` does *not* use a global `Subscriber`
//! which is initialized once. Instead, it follows the `tokio` pattern of
//! executing code in a context. For example:
//!
//! ```rust
//! #[macro_use]
//! extern crate tokio_trace;
//! # pub struct FooSubscriber;
//! # use tokio_trace::{span::Id, Metadata, field::ValueSet};
//! # impl tokio_trace::Subscriber for FooSubscriber {
//! # fn new_span(&self, _: &Metadata, _: &ValueSet) -> Id { Id::from_u64(0) }
//! # fn record(&self, _: &Id, _: &ValueSet) {}
//! # fn event(&self, _: &tokio_trace::Event) {}
//! # fn record_follows_from(&self, _: &Id, _: &Id) {}
//! # fn enabled(&self, _: &Metadata) -> bool { false }
//! # fn enter(&self, _: &Id) {}
//! # fn exit(&self, _: &Id) {}
//! # }
//! # impl FooSubscriber {
//! # fn new() -> Self { FooSubscriber }
//! # }
//! # fn main() {
//! let my_subscriber = FooSubscriber::new();
//!
//! tokio_trace::subscriber::with_default(my_subscriber, || {
//! // Any trace events generated in this closure or by functions it calls
//! // will be collected by `my_subscriber`.
//! })
//! # }
//! ```
//!
//! This approach allows trace data to be collected by multiple subscribers
//! within different contexts in the program. Alternatively, a single subscriber
//! may be constructed by the `main` function and all subsequent code executed
//! with that subscriber as the default. Any trace events generated outside the
//! context of a subscriber will not be collected.
//!
//! The executable itself may use the `tokio-trace` crate to instrument itself
//! as well.
//!
//! The [`tokio-trace-nursery`] repository contains less stable crates designed
//! to be used with the `tokio-trace` ecosystem. It includes a collection of
//! `Subscriber` implementations, as well as utility and adapter crates.
//!
//! [`log`]: https://docs.rs/log/0.4.6/log/
//! [`Span`]: span/struct.Span
//! [`Event`]: struct.Event.html
//! [`Subscriber`]: subscriber/trait.Subscriber.html
//! [`observe_event`]: subscriber/trait.Subscriber.html#tymethod.observe_event
//! [`enter`]: subscriber/trait.Subscriber.html#tymethod.enter
//! [`exit`]: subscriber/trait.Subscriber.html#tymethod.exit
//! [`enabled`]: subscriber/trait.Subscriber.html#tymethod.enabled
//! [metadata]: struct.Metadata.html
//! [`tokio-trace-nursury`]: https://github.com/tokio-rs/tokio-trace-nursery
extern crate tokio_trace_core;
// Somehow this `use` statement is necessary for us to re-export the `core`
// macros on Rust 1.26.0. I'm not sure how this makes it work, but it does.
#[allow(unused_imports)]
#[doc(hidden)]
use tokio_trace_core::*;
pub use self::{
dispatcher::Dispatch,
event::Event,
field::Value,
span::Span,
subscriber::Subscriber,
tokio_trace_core::{dispatcher, event, Level, Metadata},
};
#[doc(hidden)]
pub use self::{
span::Id,
tokio_trace_core::{
callsite::{self, Callsite},
metadata,
},
};
/// Constructs a new static callsite for a span or event.
#[doc(hidden)]
#[macro_export]
macro_rules! callsite {
(name: $name:expr, fields: $( $field_name:expr ),* $(,)*) => ({
callsite! {
name: $name,
target: module_path!(),
level: $crate::Level::TRACE,
fields: $( $field_name ),*
}
});
(name: $name:expr, level: $lvl:expr, fields: $( $field_name:expr ),* $(,)*) => ({
callsite! {
name: $name,
target: module_path!(),
level: $lvl,
fields: $( $field_name ),*
}
});
(
name: $name:expr,
target: $target:expr,
level: $lvl:expr,
fields: $( $field_name:expr ),*
$(,)*
) => ({
use std::sync::{Once, atomic::{self, AtomicUsize, Ordering}};
use $crate::{callsite, Metadata, subscriber::Interest};
struct MyCallsite;
static META: Metadata<'static> = {
metadata! {
name: $name,
target: $target,
level: $lvl,
fields: &[ $( stringify!($field_name) ),* ],
callsite: &MyCallsite,
}
};
// FIXME: Rust 1.34 deprecated ATOMIC_USIZE_INIT. When Tokio's minimum
// supported version is 1.34, replace this with the const fn `::new`.
#[allow(deprecated)]
static INTEREST: AtomicUsize = atomic::ATOMIC_USIZE_INIT;
static REGISTRATION: Once = Once::new();
impl MyCallsite {
#[inline]
fn interest(&self) -> Interest {
match INTEREST.load(Ordering::Relaxed) {
0 => Interest::never(),
2 => Interest::always(),
_ => Interest::sometimes(),
}
}
}
impl callsite::Callsite for MyCallsite {
fn add_interest(&self, interest: Interest) {
let current_interest = self.interest();
let interest = match () {
// If the added interest is `never()`, don't change anything
// — either a different subscriber added a higher
// interest, which we want to preserve, or the interest is 0
// anyway (as it's initialized to 0).
_ if interest.is_never() => return,
// If the interest is `sometimes()`, that overwrites a `never()`
// interest, but doesn't downgrade an `always()` interest.
_ if interest.is_sometimes() && current_interest.is_never() => 1,
// If the interest is `always()`, we overwrite the current
// interest, as always() is the highest interest level and
// should take precedent.
_ if interest.is_always() => 2,
_ => return,
};
INTEREST.store(interest, Ordering::Relaxed);
}
fn clear_interest(&self) {
INTEREST.store(0, Ordering::Relaxed);
}
fn metadata(&self) -> &Metadata {
&META
}
}
REGISTRATION.call_once(|| {
callsite::register(&MyCallsite);
});
&MyCallsite
})
}
/// Constructs a new span.
///
/// # Examples
///
/// Creating a new span with no fields:
/// ```
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// let mut span = span!("my span");
/// span.enter(|| {
/// // do work inside the span...
/// });
/// # }
/// ```
///
/// Creating a span with fields:
/// ```
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// span!("my span", foo = 2, bar = "a string").enter(|| {
/// // do work inside the span...
/// });
/// # }
/// ```
///
/// Note that a trailing comma on the final field is valid:
/// ```
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// span!(
/// "my span",
/// foo = 2,
/// bar = "a string",
/// );
/// # }
/// ```
///
/// Creating a span with custom target and log level:
/// ```
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// span!(
/// target: "app_span",
/// level: tokio_trace::Level::TRACE,
/// "my span",
/// foo = 3,
/// bar = "another string"
/// );
/// # }
/// ```
///
/// Field values may be recorded after the span is created:
/// ```
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// let mut my_span = span!("my span", foo = 2, bar);
/// my_span.record("bar", &7);
/// # }
/// ```
///
/// Note that a span may have up to 32 fields. The following will not compile:
/// ```rust,compile_fail
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// span!(
/// "too many fields!",
/// a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, i = 9,
/// j = 10, k = 11, l = 12, m = 13, n = 14, o = 15, p = 16, q = 17,
/// r = 18, s = 19, t = 20, u = 21, v = 22, w = 23, x = 24, y = 25,
/// z = 26, aa = 27, bb = 28, cc = 29, dd = 30, ee = 31, ff = 32, gg = 33
/// );
/// # }
/// ```
#[macro_export]
macro_rules! span {
(target: $target:expr, level: $lvl:expr, $name:expr, $($k:ident $( = $val:expr )* ),*,) => {
span!(target: $target, level: $lvl, $name, $($k $( = $val)*),*)
};
(target: $target:expr, level: $lvl:expr, $name:expr, $($k:ident $( = $val:expr )* ),*) => {
{
use $crate::{callsite, field::{Value, ValueSet, AsField}, Span};
use $crate::callsite::Callsite;
let callsite = callsite! {
name: $name,
target: $target,
level: $lvl,
fields: $($k),*
};
if is_enabled!(callsite) {
let meta = callsite.metadata();
Span::new(meta, &valueset!(meta.fields(), $($k $( = $val)*),*))
} else {
Span::new_disabled()
}
}
};
(target: $target:expr, level: $lvl:expr, $name:expr) => {
span!(target: $target, level: $lvl, $name,)
};
(level: $lvl:expr, $name:expr, $($k:ident $( = $val:expr )* ),*,) => {
span!(target: module_path!(), level: $lvl, $name, $($k $( = $val)*),*)
};
(level: $lvl:expr, $name:expr, $($k:ident $( = $val:expr )* ),*) => {
span!(target: module_path!(), level: $lvl, $name, $($k $( = $val)*),*)
};
(level: $lvl:expr, $name:expr) => {
span!(target: module_path!(), level: $lvl, $name,)
};
($name:expr, $($k:ident $( = $val:expr)*),*,) => {
span!(target: module_path!(), level: $crate::Level::TRACE, $name, $($k $( = $val)*),*)
};
($name:expr, $($k:ident $( = $val:expr)*),*) => {
span!(target: module_path!(), level: $crate::Level::TRACE, $name, $($k $( = $val)*),*)
};
($name:expr) => { span!(target: module_path!(), level: $crate::Level::TRACE, $name,) };
}
/// Constructs a new `Event`.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate tokio_trace;
/// use tokio_trace::{Level, field};
///
/// # fn main() {
/// let data = (42, "fourty-two");
/// let private_data = "private";
/// let error = "a bad error";
///
/// event!(Level::ERROR, { error = field::display(error) }, "Received error");
/// event!(target: "app_events", Level::WARN, {
/// private_data = private_data,
/// data = field::debug(data),
/// },
/// "App warning: {}", error
/// );
/// event!(Level::INFO, the_answer = data.0);
/// # }
/// ```
///
/// Note that *unlike `span!`*, `event!` requires a value for all fields. As
/// events are recorded immediately when the macro is invoked, there is no
/// opportunity for fields to be recorded later. A trailing comma on the final
/// field is valid.
///
/// For example, the following does not compile:
/// ```rust,compile_fail
/// # #[macro_use]
/// # extern crate tokio_trace;
/// use tokio_trace::{Level, field};
///
/// # fn main() {
/// event!(Level::Info, foo = 5, bad_field, bar = field::display("hello"))
/// #}
/// ```
///
/// Events may have up to 32 fields. The following will not compile:
/// ```rust,compile_fail
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// event!(tokio_trace::Level::INFO,
/// a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, i = 9,
/// j = 10, k = 11, l = 12, m = 13, n = 14, o = 15, p = 16, q = 17,
/// r = 18, s = 19, t = 20, u = 21, v = 22, w = 23, x = 24, y = 25,
/// z = 26, aa = 27, bb = 28, cc = 29, dd = 30, ee = 31, ff = 32, gg = 33
/// );
/// # }
/// ```
#[macro_export]
macro_rules! event {
(target: $target:expr, $lvl:expr, { $( $k:ident = $val:expr ),* $(,)*} )=> ({
{
#[allow(unused_imports)]
use $crate::{callsite, dispatcher, Event, field::{Value, ValueSet}};
use $crate::callsite::Callsite;
let callsite = callsite! {
name: concat!("event ", file!(), ":", line!()),
target: $target,
level: $lvl,
fields: $( $k ),*
};
if is_enabled!(callsite) {
let meta = callsite.metadata();
Event::observe(meta, &valueset!(meta.fields(), $( $k = $val),* ));
}
}
});
(target: $target:expr, $lvl:expr, { $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => ({
event!(target: $target, $lvl, { message = format_args!($($arg)+), $( $k = $val ),* })
});
(target: $target:expr, $lvl:expr, { $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => ({
event!(target: $target, $lvl, { message = format_args!($($arg)+), $( $k = $val ),* })
});
(target: $target:expr, $lvl:expr, $( $k:ident = $val:expr ),+, ) => (
event!(target: $target, $lvl, { $($k = $val),+ })
);
(target: $target:expr, $lvl:expr, $( $k:ident = $val:expr ),+ ) => (
event!(target: $target, $lvl, { $($k = $val),+ })
);
(target: $target:expr, $lvl:expr, $($arg:tt)+ ) => (
event!(target: $target, $lvl, { }, $($arg)+)
);
( $lvl:expr, { $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: module_path!(), $lvl, { message = format_args!($($arg)+), $($k = $val),* })
);
( $lvl:expr, { $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: module_path!(), $lvl, { message = format_args!($($arg)+), $($k = $val),* })
);
( $lvl:expr, $( $k:ident = $val:expr ),*, ) => (
event!(target: module_path!(), $lvl, { $($k = $val),* })
);
( $lvl:expr, $( $k:ident = $val:expr ),* ) => (
event!(target: module_path!(), $lvl, { $($k = $val),* })
);
( $lvl:expr, $($arg:tt)+ ) => (
event!(target: module_path!(), $lvl, { }, $($arg)+)
);
}
/// Constructs an event at the trace level.
///
/// When both a message and fields are included, curly braces (`{` and `}`) are
/// used to delimit the list of fields from the format string for the message.
/// A trailing comma on the final field is valid.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # use std::time::SystemTime;
/// # #[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() {
/// use tokio_trace::field;
///
/// let pos = Position { x: 3.234, y: -1.223 };
/// let origin_dist = pos.dist(Position::ORIGIN);
///
/// trace!(position = field::debug(pos), origin_dist = field::debug(origin_dist));
/// trace!(target: "app_events",
/// { position = field::debug(pos) },
/// "x is {} and y is {}",
/// if pos.x >= 0.0 { "positive" } else { "negative" },
/// if pos.y >= 0.0 { "positive" } else { "negative" });
/// # }
/// ```
#[macro_export]
macro_rules! trace {
(target: $target:expr, { $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::TRACE, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, { $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::TRACE, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, $( $k:ident = $val:expr ),*, ) => (
event!(target: $target, $crate::Level::TRACE, { $($k = $val),* })
);
(target: $target:expr, $( $k:ident = $val:expr ),* ) => (
event!(target: $target, $crate::Level::TRACE, { $($k = $val),* })
);
(target: $target:expr, $($arg:tt)+ ) => (
// When invoking this macro with `log`-style syntax (no fields), we
// drop the event immediately — the `log` crate's macros don't
// expand to an item, and if this did, it would break drop-in
// compatibility with `log`'s macros. Since it defines no fields,
// the handle won't be used later to add values to them.
drop(event!(target: $target, $crate::Level::TRACE, {}, $($arg)+));
);
({ $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::TRACE, { $($k = $val),* }, $($arg)+)
);
({ $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::TRACE, { $($k = $val),* }, $($arg)+)
);
($( $k:ident = $val:expr ),*, ) => (
event!(target: module_path!(), $crate::Level::TRACE, { $($k = $val),* })
);
($( $k:ident = $val:expr ),* ) => (
event!(target: module_path!(), $crate::Level::TRACE, { $($k = $val),* })
);
($($arg:tt)+ ) => (
drop(event!(target: module_path!(), $crate::Level::TRACE, {}, $($arg)+));
);
}
/// Constructs an event at the debug level.
///
/// When both a message and fields are included, curly braces (`{` and `}`) are
/// used to delimit the list of fields from the format string for the message.
/// A trailing comma on the final field is valid.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// # #[derive(Debug)] struct Position { x: f32, y: f32 }
/// use tokio_trace::field;
///
/// let pos = Position { x: 3.234, y: -1.223 };
///
/// debug!(x = field::debug(pos.x), y = field::debug(pos.y));
/// debug!(target: "app_events", { position = field::debug(pos) }, "New position");
/// # }
/// ```
#[macro_export]
macro_rules! debug {
(target: $target:expr, { $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::DEBUG, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, { $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::DEBUG, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, $( $k:ident = $val:expr ),*, ) => (
event!(target: $target, $crate::Level::DEBUG, { $($k = $val),* })
);
(target: $target:expr, $( $k:ident = $val:expr ),* ) => (
event!(target: $target, $crate::Level::DEBUG, { $($k = $val),* })
);
(target: $target:expr, $($arg:tt)+ ) => (
drop(event!(target: $target, $crate::Level::DEBUG, {}, $($arg)+));
);
({ $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::DEBUG, { $($k = $val),* }, $($arg)+)
);
({ $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::DEBUG, { $($k = $val),* }, $($arg)+)
);
($( $k:ident = $val:expr ),*, ) => (
event!(target: module_path!(), $crate::Level::DEBUG, { $($k = $val),* })
);
($( $k:ident = $val:expr ),* ) => (
event!(target: module_path!(), $crate::Level::DEBUG, { $($k = $val),* })
);
($($arg:tt)+ ) => (
drop(event!(target: module_path!(), $crate::Level::DEBUG, {}, $($arg)+));
);
}
/// Constructs an event at the info level.
///
/// When both a message and fields are included, curly braces (`{` and `}`) are
/// used to delimit the list of fields from the format string for the message.
/// A trailing comma on the final field is valid.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # use std::net::Ipv4Addr;
/// # fn main() {
/// # struct Connection { port: u32, speed: f32 }
/// use tokio_trace::field;
///
/// let addr = Ipv4Addr::new(127, 0, 0, 1);
/// let conn_info = Connection { port: 40, speed: 3.20 };
///
/// info!({ port = conn_info.port }, "connected to {}", addr);
/// info!(
/// target: "connection_events",
/// ip = field::display(addr),
/// port = conn_info.port,
/// speed = field::debug(conn_info.speed)
/// );
/// # }
/// ```
#[macro_export]
macro_rules! info {
(target: $target:expr, { $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::INFO, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, { $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::INFO, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, $( $k:ident = $val:expr ),*, ) => (
event!(target: $target, $crate::Level::INFO, { $($k = $val),* })
);
(target: $target:expr, $( $k:ident = $val:expr ),* ) => (
event!(target: $target, $crate::Level::INFO, { $($k = $val),* })
);
(target: $target:expr, $($arg:tt)+ ) => (
drop(event!(target: $target, $crate::Level::INFO, {}, $($arg)+));
);
({ $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::INFO, { $($k = $val),* }, $($arg)+)
);
({ $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::INFO, { $($k = $val),* }, $($arg)+)
);
($( $k:ident = $val:expr ),*, ) => (
event!(target: module_path!(), $crate::Level::INFO, { $($k = $val),* })
);
($( $k:ident = $val:expr ),* ) => (
event!(target: module_path!(), $crate::Level::INFO, { $($k = $val),* })
);
($($arg:tt)+ ) => (
drop(event!(target: module_path!(), $crate::Level::INFO, {}, $($arg)+));
);
}
/// Constructs an event at the warn level.
///
/// When both a message and fields are included, curly braces (`{` and `}`) are
/// used to delimit the list of fields from the format string for the message.
/// A trailing comma on the final field is valid.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// use tokio_trace::field;
///
/// let warn_description = "Invalid Input";
/// let input = &[0x27, 0x45];
///
/// warn!(input = field::debug(input), warning = warn_description);
/// warn!(
/// target: "input_events",
/// { warning = warn_description },
/// "Received warning for input: {:?}", input,
/// );
/// # }
/// ```
#[macro_export]
macro_rules! warn {
(target: $target:expr, { $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::WARN, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, { $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::WARN, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, $( $k:ident = $val:expr ),*, ) => (
event!(target: $target, $crate::Level::WARN, { $($k = $val),* })
);
(target: $target:expr, $( $k:ident = $val:expr ),* ) => (
event!(target: $target, $crate::Level::WARN, { $($k = $val),* })
);
(target: $target:expr, $($arg:tt)+ ) => (
drop(event!(target: $target, $crate::Level::WARN, {}, $($arg)+));
);
({ $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::WARN, { $($k = $val),* }, $($arg)+)
);
({ $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::WARN, { $($k = $val),* }, $($arg)+)
);
($( $k:ident = $val:expr ),*, ) => (
event!(target: module_path!(), $crate::Level::WARN,{ $($k = $val),* })
);
($( $k:ident = $val:expr ),* ) => (
event!(target: module_path!(), $crate::Level::WARN,{ $($k = $val),* })
);
($($arg:tt)+ ) => (
drop(event!(target: module_path!(), $crate::Level::WARN, {}, $($arg)+));
);
}
/// Constructs an event at the error level.
///
/// When both a message and fields are included, curly braces (`{` and `}`) are
/// used to delimit the list of fields from the format string for the message.
/// A trailing comma on the final field is valid.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate tokio_trace;
/// # fn main() {
/// use tokio_trace::field;
/// let (err_info, port) = ("No connection", 22);
///
/// error!(port = port, error = field::display(err_info));
/// error!(target: "app_events", "App Error: {}", err_info);
/// error!({ info = err_info }, "error on port: {}", port);
/// # }
/// ```
#[macro_export]
macro_rules! error {
(target: $target:expr, { $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::ERROR, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, { $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: $target, $crate::Level::ERROR, { $($k = $val),* }, $($arg)+)
);
(target: $target:expr, $( $k:ident = $val:expr ),*, ) => (
event!(target: $target, $crate::Level::ERROR, { $($k = $val),* })
);
(target: $target:expr, $( $k:ident = $val:expr ),* ) => (
event!(target: $target, $crate::Level::ERROR, { $($k = $val),* })
);
(target: $target:expr, $($arg:tt)+ ) => (
drop(event!(target: $target, $crate::Level::ERROR, {}, $($arg)+));
);
({ $( $k:ident = $val:expr ),*, }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::ERROR, { $($k = $val),* }, $($arg)+)
);
({ $( $k:ident = $val:expr ),* }, $($arg:tt)+ ) => (
event!(target: module_path!(), $crate::Level::ERROR, { $($k = $val),* }, $($arg)+)
);
($( $k:ident = $val:expr ),*, ) => (
event!(target: module_path!(), $crate::Level::ERROR, { $($k = $val),* })
);
($( $k:ident = $val:expr ),* ) => (
event!(target: module_path!(), $crate::Level::ERROR, { $($k = $val),* })
);
($($arg:tt)+ ) => (
drop(event!(target: module_path!(), $crate::Level::ERROR, {}, $($arg)+));
);
}
#[macro_export]
// TODO: determine if this ought to be public API?
#[doc(hidden)]
macro_rules! is_enabled {
($callsite:expr) => {{
let interest = $callsite.interest();
if interest.is_never() {
false
} else if interest.is_always() {
true
} else {
let meta = $callsite.metadata();
$crate::dispatcher::with(|current| current.enabled(meta))
}
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! valueset {
($fields:expr, $($k:ident $( = $val:expr )* ) ,*) => {
{
let mut iter = $fields.iter();
$fields.value_set(&[
$((
&iter.next().expect("FieldSet corrupted (this is a bug)"),
valueset!(@val $k $(= $val)*)
)),*
])
}
};
(@val $k:ident = $val:expr) => {
Some(&$val as &$crate::field::Value)
};
(@val $k:ident) => { None };
}
pub mod field;
pub mod span;
pub mod subscriber;
mod sealed {
pub trait Sealed {}
}
+495
View File
@@ -0,0 +1,495 @@
//! Spans represent periods of time in the execution of a program.
//!
//! # Entering a Span
//!
//! A thread of execution is said to _enter_ a span when it begins executing,
//! and _exit_ the span when it switches to another context. Spans may be
//! entered through the [`enter`](`Span::enter`) method, which enters the target span,
//! performs a given function (either a closure or a function pointer), exits
//! the span, and then returns the result.
//!
//! Calling `enter` on a span handle enters the span that handle corresponds to,
//! if the span exists:
//! ```
//! # #[macro_use] extern crate tokio_trace;
//! # fn main() {
//! let my_var: u64 = 5;
//! let mut my_span = span!("my_span", my_var = &my_var);
//!
//! my_span.enter(|| {
//! // perform some work in the context of `my_span`...
//! });
//!
//! // Perform some work outside of the context of `my_span`...
//!
//! my_span.enter(|| {
//! // Perform some more work in the context of `my_span`.
//! });
//! # }
//! ```
//!
//! # The Span Lifecycle
//!
//! Execution may enter and exit a span multiple times before that
//! span is _closed_. Consider, for example, a future which has an associated
//! span and enters that span every time it is polled:
//! ```rust
//! # extern crate tokio_trace;
//! # extern crate futures;
//! # use futures::{Future, Poll, Async};
//! struct MyFuture<'a> {
//! // data
//! span: tokio_trace::Span<'a>,
//! }
//!
//! impl<'a> Future for MyFuture<'a> {
//! type Item = ();
//! type Error = ();
//!
//! fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
//! self.span.enter(|| {
//! // Do actual future work
//! # Ok(Async::Ready(()))
//! })
//! }
//! }
//! ```
//!
//! If this future was spawned on an executor, it might yield one or more times
//! before `poll` returns `Ok(Async::Ready)`. If the future were to yield, then
//! the executor would move on to poll the next future, which may _also_ enter
//! an associated span or series of spans. Therefore, it is valid for a span to
//! be entered repeatedly before it completes. Only the time when that span or
//! one of its children was the current span is considered to be time spent in
//! that span. A span which is not executing and has not yet been closed is said
//! to be _idle_.
//!
//! Because spans may be entered and exited multiple times before they close,
//! [`Subscriber`]s have separate trait methods which are called to notify them
//! of span exits and when span handles are dropped. When execution exits a
//! span, [`exit`](::Subscriber::exit) will always be called with that span's ID
//! to notify the subscriber that the span has been exited. When span handles
//! are dropped, the [`drop_span`](::Subscriber::drop_span) method is called
//! with that span's ID. The subscriber may use this to determine whether or not
//! the span will be entered again.
//!
//! If there is only a single handle with the capacity to exit a span, dropping
//! that handle "close" the span, since the capacity to enter it no longer
//! exists. For example:
//! ```
//! # #[macro_use] extern crate tokio_trace;
//! # fn main() {
//! {
//! span!("my_span").enter(|| {
//! // perform some work in the context of `my_span`...
//! }); // --> Subscriber::exit(my_span)
//!
//! // The handle to `my_span` only lives inside of this block; when it is
//! // dropped, the subscriber will be informed that `my_span` has closed.
//!
//! } // --> Subscriber::close(my_span)
//! # }
//! ```
//!
//! A span may be explicitly closed before when the span handle is dropped by
//! calling the [`Span::close`] method. Doing so will drop that handle the next
//! time it is exited. For example:
//! ```
//! # #[macro_use] extern crate tokio_trace;
//! # fn main() {
//! use tokio_trace::Span;
//!
//! let mut my_span = span!("my_span");
//! // Signal to my_span that it should close when it exits
//! my_span.close();
//! my_span.enter(|| {
//! // ...
//! }); // --> Subscriber::exit(my_span); Subscriber::drop_span(my_span)
//!
//! // The handle to `my_span` still exists, but it now knows that the span was
//! // closed while it was executing.
//! my_span.is_closed(); // ==> true
//!
//! // Attempting to enter the span using the handle again will do nothing.
//! my_span.enter(|| {
//! // no-op
//! });
//! # }
//! ```
//! However, if multiple handles exist, the span can still be re-entered even if
//! one or more is dropped. For determining when _all_ handles to a span have
//! been dropped, `Subscriber`s have a [`clone_span`](::Subscriber::clone_span)
//! method, which is called every time a span handle is cloned. Combined with
//! `drop_span`, this may be used to track the number of handles to a given span
//! — if `drop_span` has been called one more time than the number of calls to
//! `clone_span` for a given ID, then no more handles to the span with that ID
//! exist. The subscriber may then treat it as closed.
//!
//! # Accessing a Span's Attributes
//!
//! The [`Attributes`] type represents a *non-entering* reference to a `Span`'s data
//! — a set of key-value pairs (known as _fields_), a creation timestamp,
//! a reference to the span's parent in the trace tree, and metadata describing
//! the source code location where the span was created. This data is provided
//! to the [`Subscriber`] when the span is created; it may then choose to cache
//! the data for future use, record it in some manner, or discard it completely.
//!
//! [`Subscriber`]: ::Subscriber
// TODO: remove this re-export?
pub use tokio_trace_core::span::Span as Id;
use std::{
borrow::Borrow,
cmp, fmt,
hash::{Hash, Hasher},
};
use {
dispatcher::{self, Dispatch},
field, Metadata,
};
/// A handle representing a span, with the capability to enter the span if it
/// exists.
///
/// If the span was rejected by the current `Subscriber`'s filter, entering the
/// span will silently do nothing. Thus, the handle can be used in the same
/// manner regardless of whether or not the trace is currently being collected.
#[derive(Clone, PartialEq, Hash)]
pub struct Span<'a> {
/// A handle used to enter the span when it is not executing.
///
/// If this is `None`, then the span has either closed or was never enabled.
inner: Option<Inner<'a>>,
/// Set to `true` when the span closes.
///
/// This allows us to distinguish if `inner` is `None` because the span was
/// never enabled (and thus the inner state was never created), or if the
/// previously entered, but it is now closed.
is_closed: bool,
}
/// A handle representing the capacity to enter a span which is known to exist.
///
/// Unlike `Span`, this type is only constructed for spans which _have_ been
/// enabled by the current filter. This type is primarily used for implementing
/// span handles; users should typically not need to interact with it directly.
#[derive(Debug)]
pub(crate) struct Inner<'a> {
/// The span's ID, as provided by `subscriber`.
id: Id,
/// The subscriber that will receive events relating to this span.
///
/// This should be the same subscriber that provided this span with its
/// `id`.
subscriber: Dispatch,
/// A flag indicating that the span has been instructed to close when
/// possible.
closed: bool,
meta: &'a Metadata<'a>,
}
/// A guard representing a span which has been entered and is currently
/// executing.
///
/// This guard may be used to exit the span, returning an `Enter` to
/// re-enter it.
///
/// This type is primarily used for implementing span handles; users should
/// typically not need to interact with it directly.
#[derive(Debug)]
#[must_use = "once a span has been entered, it should be exited"]
struct Entered<'a> {
inner: Inner<'a>,
}
// ===== impl Span =====
impl<'a> Span<'a> {
/// Constructs a new `Span` with the given [metadata] and set of [field values].
///
/// The new span will be constructed by the currently-active [`Subscriber`],
/// with the current span as its parent (if one exists).
///
/// After the span is constructed, [field values] and/or [`follows_from`]
/// annotations may be added to it.
///
/// [metadata]: ::metadata::Metadata
/// [`Subscriber`]: ::subscriber::Subscriber
/// [field values]: ::field::ValueSet
/// [`follows_from`]: ::span::Span::follows_from
#[inline]
pub fn new(meta: &'a Metadata<'a>, values: &field::ValueSet) -> Span<'a> {
let inner = dispatcher::with(move |dispatch| {
let id = dispatch.new_span(meta, values);
Some(Inner::new(id, dispatch, meta))
});
Self {
inner,
is_closed: false,
}
}
/// Constructs a new disabled span.
#[inline(always)]
pub fn new_disabled() -> Span<'a> {
Span {
inner: None,
is_closed: false,
}
}
/// Executes the given function in the context of this span.
///
/// If this span is enabled, then this function enters the span, invokes
/// and then exits the span. If the span is disabled, `f` will still be
/// invoked, but in the context of the currently-executing span (if there is
/// one).
///
/// Returns the result of evaluating `f`.
pub fn enter<F: FnOnce() -> T, T>(&mut self, f: F) -> T {
match self.inner.take() {
Some(inner) => dispatcher::with_default(inner.subscriber.clone(), || {
let guard = inner.enter();
let result = f();
self.inner = guard.exit();
result
}),
None => f(),
}
}
/// Returns a [`Field`](::field::Field) for the field with the given `name`, if
/// one exists,
pub fn field<Q>(&self, name: &Q) -> Option<field::Field>
where
Q: Borrow<str>,
{
self.inner
.as_ref()
.and_then(|inner| inner.meta.fields().field(name))
}
/// Returns true if this `Span` has a field for the given
/// [`Field`](::field::Field) or field name.
pub fn has_field<Q: ?Sized>(&self, field: &Q) -> bool
where
Q: field::AsField,
{
self.metadata()
.and_then(|meta| field.as_field(meta))
.is_some()
}
/// Records that the field described by `field` has the value `value`.
pub fn record<Q: ?Sized, V>(&mut self, field: &Q, value: &V) -> &mut Self
where
Q: field::AsField,
V: field::Value,
{
if let Some(ref mut inner) = self.inner {
let meta = inner.metadata();
if let Some(field) = field.as_field(meta) {
inner.record(
&meta
.fields()
.value_set(&[(&field, Some(value as &field::Value))]),
)
}
}
self
}
/// Record all the fields in the span
pub fn record_all(&mut self, values: &field::ValueSet) -> &mut Self {
if let Some(ref mut inner) = self.inner {
inner.record(&values);
}
self
}
/// Closes this span handle, dropping its internal state.
///
/// Once this function has been called, subsequent calls to `enter` on this
/// handle will no longer enter the span. If this is the final handle with
/// the potential to enter that span, the subscriber may consider the span to
/// have ended.
pub fn close(&mut self) {
if let Some(mut inner) = self.inner.take() {
inner.close();
}
self.is_closed = true;
}
/// Returns `true` if this span is closed.
pub fn is_closed(&self) -> bool {
self.is_closed
}
/// Returns `true` if this span was disabled by the subscriber and does not
/// exist.
#[inline]
pub fn is_disabled(&self) -> bool {
self.inner.is_none() && !self.is_closed
}
/// Indicates that the span with the given ID has an indirect causal
/// relationship with this span.
///
/// This relationship differs somewhat from the parent-child relationship: a
/// span may have any number of prior spans, rather than a single one; and
/// spans are not considered to be executing _inside_ of the spans they
/// follow from. This means that a span may close even if subsequent spans
/// that follow from it are still open, and time spent inside of a
/// subsequent span should not be included in the time its precedents were
/// executing. This is used to model causal relationships such as when a
/// single future spawns several related background tasks, et cetera.
///
/// If this span is disabled, or the resulting follows-from relationship
/// would be invalid, this function will do nothing.
pub fn follows_from(&self, from: &Id) -> &Self {
if let Some(ref inner) = self.inner {
inner.follows_from(from);
}
self
}
/// Returns this span's `Id`, if it is enabled.
pub fn id(&self) -> Option<Id> {
self.inner.as_ref().map(Inner::id)
}
/// Returns this span's `Metadata`, if it is enabled.
pub fn metadata(&self) -> Option<&'a Metadata<'a>> {
self.inner.as_ref().map(Inner::metadata)
}
}
impl<'a> fmt::Debug for Span<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut span = f.debug_struct("Span");
if let Some(ref inner) = self.inner {
span.field("id", &inner.id())
} else {
span.field("disabled", &true)
}
.finish()
}
}
// ===== impl Inner =====
impl<'a> Inner<'a> {
/// Indicates that this handle will not be reused to enter the span again.
///
/// After calling `close`, the `Entered` guard returned by `self.enter()`
/// will _drop_ this handle when it is exited.
fn close(&mut self) {
self.closed = true;
}
/// Enters the span, returning a guard that may be used to exit the span and
/// re-enter the prior span.
///
/// This is used internally to implement `Span::enter`. It may be used for
/// writing custom span handles, but should generally not be called directly
/// when entering a span.
fn enter(self) -> Entered<'a> {
self.subscriber.enter(&self.id);
Entered { inner: self }
}
/// Indicates that the span with the given ID has an indirect causal
/// relationship with this span.
///
/// This relationship differs somewhat from the parent-child relationship: a
/// span may have any number of prior spans, rather than a single one; and
/// spans are not considered to be executing _inside_ of the spans they
/// follow from. This means that a span may close even if subsequent spans
/// that follow from it are still open, and time spent inside of a
/// subsequent span should not be included in the time its precedents were
/// executing. This is used to model causal relationships such as when a
/// single future spawns several related background tasks, et cetera.
///
/// If this span is disabled, this function will do nothing. Otherwise, it
/// returns `Ok(())` if the other span was added as a precedent of this
/// span, or an error if this was not possible.
fn follows_from(&self, from: &Id) {
self.subscriber.record_follows_from(&self.id, &from)
}
/// Returns the span's ID.
fn id(&self) -> Id {
self.id.clone()
}
/// Returns the span's metadata.
fn metadata(&self) -> &'a Metadata<'a> {
self.meta
}
fn record(&mut self, values: &field::ValueSet) {
if values.callsite() == self.meta.callsite() {
self.subscriber.record(&self.id, &values)
}
}
fn new(id: Id, subscriber: &Dispatch, meta: &'a Metadata<'a>) -> Self {
Inner {
id,
subscriber: subscriber.clone(),
closed: false,
meta,
}
}
}
impl<'a> cmp::PartialEq for Inner<'a> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl<'a> Hash for Inner<'a> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl<'a> Drop for Inner<'a> {
fn drop(&mut self) {
self.subscriber.drop_span(self.id.clone());
}
}
impl<'a> Clone for Inner<'a> {
fn clone(&self) -> Self {
Inner {
id: self.subscriber.clone_span(&self.id),
subscriber: self.subscriber.clone(),
closed: self.closed,
meta: self.meta,
}
}
}
// ===== impl Entered =====
impl<'a> Entered<'a> {
/// Exit the `Entered` guard, returning an `Inner` handle that may be used
/// to re-enter the span, or `None` if the span closed while performing the
/// exit.
fn exit(self) -> Option<Inner<'a>> {
self.inner.subscriber.exit(&self.inner.id);
if self.inner.closed {
// Dropping `inner` will allow it to perform the closure if
// able.
None
} else {
Some(self.inner)
}
}
}
+19
View File
@@ -0,0 +1,19 @@
//! Collects and records trace data.
pub use tokio_trace_core::subscriber::*;
/// Sets this dispatch as the default for the duration of a closure.
///
/// The default dispatcher is used when creating a new [`Span`] or
/// [`Event`], _if no span is currently executing_. If a span is currently
/// executing, new spans or events are dispatched to the subscriber that
/// tagged that span, instead.
///
/// [`Span`]: ::span::Span
/// [`Subscriber`]: ::Subscriber
/// [`Event`]: ::Event
pub fn with_default<T, S>(subscriber: S, f: impl FnOnce() -> T) -> T
where
S: Subscriber + Send + Sync + 'static,
{
::dispatcher::with_default(::Dispatch::new(subscriber), f)
}