diff --git a/README.md b/README.md index a3e0b362aa..624f9cf6d3 100644 --- a/README.md +++ b/README.md @@ -35,11 +35,11 @@ Tokio project, but does _not_ require the `tokio` runtime to be used. ### In Applications -In order to record trace events, executables have to use a `Subscriber` -implementation compatible with `tracing`. A `Subscriber` implements a way of +In order to record trace events, executables have to use a collector +implementation compatible with `tracing`. A collector implements a way of collecting trace data, such as by logging it to standard output. [`tracing-subscriber`][tracing-subscriber-docs]'s [`fmt` module][fmt] provides -a subscriber for logging traces with reasonable defaults. Additionally, +a collector for logging traces with reasonable defaults. Additionally, `tracing-subscriber` is able to consume messages emitted by `log`-instrumented libraries and modules. @@ -51,14 +51,14 @@ tracing = "0.1" tracing-subscriber = "0.2" ``` -Then create and install a `Subscriber`, for example using [`init()`]: +Then create and install a collector, for example using [`init()`]: ```rust use tracing::info; use tracing_subscriber; fn main() { - // install global subscriber configured based on RUST_LOG envvar. + // install global collector configured based on RUST_LOG env var. tracing_subscriber::fmt::init(); let number_of_yaks = 3; @@ -73,7 +73,7 @@ fn main() { } ``` -Using `init()` calls [`set_global_default()`] so this subscriber will be used +Using `init()` calls [`set_global_default()`] so this collector will be used as the default in all threads for the remainder of the duration of the program, similar to how loggers work in the `log` crate. @@ -82,34 +82,34 @@ program, similar to how loggers work in the `log` crate. [`set_global_default`]: https://docs.rs/tracing/latest/tracing/subscriber/fn.set_global_default.html -For more control, a subscriber can be built in stages and not set globally, -but instead used to locally override the default subscriber. For example: +For more control, a collector can be built in stages and not set globally, +but instead used to locally override the default collector. For example: ```rust use tracing::{info, Level}; use tracing_subscriber; fn main() { - let subscriber = tracing_subscriber::fmt() + let collector = tracing_subscriber::fmt() // filter spans/events with level TRACE or higher. .with_max_level(Level::TRACE) // build but do not install the subscriber. .finish(); - tracing::subscriber::with_default(subscriber, || { + tracing::collector::with_default(collector, || { info!("This will be logged to stdout"); }); info!("This will _not_ be logged to stdout"); } ``` -Any trace events generated outside the context of a subscriber will not be collected. +Any trace events generated outside the context of a collector will not be collected. -This approach allows trace data to be collected by multiple subscribers +This approach allows trace data to be collected by multiple collectors within different contexts in the program. Note that the override only applies to the currently executing thread; other threads will not see the change from with_default. -Once a subscriber has been set, instrumentation points may be added to the +Once a collector has been set, instrumentation points may be added to the executable using the `tracing` crate's macros. [`tracing-subscriber`]: https://docs.rs/tracing-subscriber/ @@ -186,7 +186,7 @@ pub fn shave_all(yaks: usize) -> usize { tracing = "0.1" ``` -Note: Libraries should *NOT* install a subscriber by using a method that calls +Note: Libraries should *NOT* install a collector by using a method that calls [`set_global_default()`], as this will cause conflicts when executables try to set the default later. @@ -317,8 +317,8 @@ The crates included as part of Tracing are: * [`tracing-serde`]: A compatibility layer for serializing trace data with `serde` (unstable). -* [`tracing-subscriber`]: Subscriber implementations, and utilities for - implementing and composing `Subscriber`s. +* [`tracing-subscriber`]: Collector implementations, and utilities for + implementing and composing `Collector`s. ([crates.io][sub-crates]|[docs][sub-docs]) * [`tracing-tower`]: Compatibility with the `tower` ecosystem (unstable). @@ -391,11 +391,11 @@ are not maintained by the `tokio` project. These include: pretty printing them. - [`spandoc`] provides a proc macro for constructing spans from doc comments _inside_ of functions. -- [`tracing-wasm`] provides a `Subscriber`/`Layer` implementation that reports +- [`tracing-wasm`] provides a `Collector`/`Subscriber` implementation that reports events and spans via browser `console.log` and [User Timing API (`window.performance`)]. - [`test-env-log`] takes care of initializing `tracing` for tests, based on environment variables with an `env_logger` compatible syntax. -- [`tracing-unwrap`] provides convenience methods to report failed unwraps on `Result` or `Option` types to a `Subscriber`. +- [`tracing-unwrap`] provides convenience methods to report failed unwraps on `Result` or `Option` types to a `Collector`. - [`diesel-tracing`] provides integration with [`diesel`] database connections. - [`tracing-tracy`] provides a way to collect [Tracy] profiles in instrumented applications. diff --git a/examples/README.md b/examples/README.md index 61a4383ae9..cc7a3d057f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -5,8 +5,8 @@ This directory contains a collection of examples that demonstrate the use of the - **tracing**: + `counters`: Implements a very simple metrics system to demonstrate how - subscribers can consume field values as typed data. - + `sloggish`: A demo `Subscriber` implementation that mimics the output of + collectors can consume field values as typed data. + + `sloggish`: A demo `Collect` implementation that mimics the output of `slog-term`'s `Compact` formatter. - **tracing-attributes**: + `attrs-basic`: A simple example of the `#[instrument]` attribute. @@ -17,15 +17,15 @@ This directory contains a collection of examples that demonstrate the use of the record function arguments. - **tracing-subscriber**: + `fmt`: Demonstrates the use of the `fmt` module in `tracing-subscriber`, - which provides a subscriber implementation that logs traces to the console. + which provides a collector implementation that logs traces to the console. + `fmt-stderr`: Demonstrates overriding the output stream used by the `fmt` - subscriber. - + `fmt-custom-field`: Demonstrates overriding how the `fmt` subscriber formats + collector. + + `fmt-custom-field`: Demonstrates overriding how the `fmt` collector formats fields on spans and events. - + `fmt-custom-event`: Demonstrates overriding how the `fmt` subscriber formats + + `fmt-custom-event`: Demonstrates overriding how the `fmt` collector formats events. + `subscriber-filter`: Demonstrates the `tracing-subscriber::filter` module, - which provides a layer which adds configurable filtering to a subscriber + which provides a layer which adds configurable filtering to a collector implementation. + `tower-load`: Demonstrates how dynamically reloadable filters can be used to debug a server under load in production. @@ -55,7 +55,7 @@ This directory contains a collection of examples that demonstrate the use of the simple `tower` HTTP/1.1 server. - **tracing-serde**: + `serde-yak-shave`: Demonstrates the use of `tracing-serde` by implementing a - subscriber that emits trace output as JSON. + collector that emits trace output as JSON. - **tracing-log**: + `hyper-echo`: Demonstrates how `tracing-log` can be used to record unstructured logs from dependencies as `tracing` events, by instrumenting diff --git a/examples/examples/all-levels.rs b/examples/examples/all-levels.rs index 692204add0..9ae95e632d 100644 --- a/examples/examples/all-levels.rs +++ b/examples/examples/all-levels.rs @@ -11,7 +11,7 @@ fn main() { // all spans/events with a level higher than TRACE (e.g, info, warn, etc.) // will be written to stdout. .with_max_level(Level::TRACE) - // sets this to be the default, global subscriber for this application. + // sets this to be the default, global collector for this application. .init(); event(); diff --git a/examples/examples/attrs-args.rs b/examples/examples/attrs-args.rs index c420cd5e79..a5ba5aa0b1 100644 --- a/examples/examples/attrs-args.rs +++ b/examples/examples/attrs-args.rs @@ -31,7 +31,7 @@ fn main() { .with_env_filter("attrs_args=trace") .finish(); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { let n = 5; let sequence = fibonacci_seq(n); info!("The first {} fibonacci numbers are {:?}", n, sequence); diff --git a/examples/examples/attrs-basic.rs b/examples/examples/attrs-basic.rs index 7e5e058a9b..a77074d3c9 100644 --- a/examples/examples/attrs-basic.rs +++ b/examples/examples/attrs-basic.rs @@ -14,7 +14,7 @@ fn main() { let subscriber = tracing_subscriber::fmt() .with_env_filter("attrs_basic=trace") .finish(); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { let num_recs = 1; let span = span!(Level::TRACE, "get_band_rec", ?num_recs); diff --git a/examples/examples/attrs-literal-field-names.rs b/examples/examples/attrs-literal-field-names.rs index 0701cf1fd1..778403f427 100644 --- a/examples/examples/attrs-literal-field-names.rs +++ b/examples/examples/attrs-literal-field-names.rs @@ -14,7 +14,7 @@ fn main() { let subscriber = tracing_subscriber::fmt() .with_env_filter("attrs_literal_field_names=trace") .finish(); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { let span = span!(Level::TRACE, "get_band_rec", "guid:x-request-id" = "abcdef"); let _enter = span.enter(); suggest_band(); diff --git a/examples/examples/counters.rs b/examples/examples/counters.rs index 8383379e1b..1da2e9c0cb 100644 --- a/examples/examples/counters.rs +++ b/examples/examples/counters.rs @@ -1,10 +1,9 @@ #![deny(rust_2018_idioms)] use tracing::{ + collect::{self, Collect}, field::{Field, Visit}, - info, span, - subscriber::{self, Subscriber}, - warn, Event, Id, Level, Metadata, + info, span, warn, Event, Id, Level, Metadata, }; use std::{ @@ -19,7 +18,7 @@ use std::{ #[derive(Clone)] struct Counters(Arc>>); -struct CounterSubscriber { +struct CounterCollector { ids: AtomicUsize, counters: Counters, } @@ -50,7 +49,7 @@ impl<'a> Visit for Count<'a> { fn record_debug(&mut self, _: &Field, _: &dyn fmt::Debug) {} } -impl CounterSubscriber { +impl CounterCollector { fn visitor(&self) -> Count<'_> { Count { counters: self.counters.0.read().unwrap(), @@ -58,9 +57,9 @@ impl CounterSubscriber { } } -impl Subscriber for CounterSubscriber { - fn register_callsite(&self, meta: &Metadata<'_>) -> subscriber::Interest { - let mut interest = subscriber::Interest::never(); +impl Collect for CounterCollector { + fn register_callsite(&self, meta: &Metadata<'_>) -> collect::Interest { + let mut interest = collect::Interest::never(); for key in meta.fields() { let name = key.name(); if name.contains("count") { @@ -70,7 +69,7 @@ impl Subscriber for CounterSubscriber { .unwrap() .entry(name.to_owned()) .or_insert_with(|| AtomicUsize::new(0)); - interest = subscriber::Interest::always(); + interest = collect::Interest::always(); } } interest @@ -109,20 +108,20 @@ impl Counters { } } - fn new() -> (Self, CounterSubscriber) { + fn new() -> (Self, CounterCollector) { let counters = Counters(Arc::new(RwLock::new(HashMap::new()))); - let subscriber = CounterSubscriber { + let collector = CounterCollector { ids: AtomicUsize::new(1), counters: counters.clone(), }; - (counters, subscriber) + (counters, collector) } } fn main() { - let (counters, subscriber) = Counters::new(); + let (counters, collector) = Counters::new(); - tracing::subscriber::set_global_default(subscriber).unwrap(); + tracing::collect::set_global_default(collector).unwrap(); let mut foo: u64 = 2; span!(Level::TRACE, "my_great_span", foo_count = &foo).in_scope(|| { diff --git a/examples/examples/custom-error.rs b/examples/examples/custom-error.rs index 423ed547a6..b2e6004097 100644 --- a/examples/examples/custom-error.rs +++ b/examples/examples/custom-error.rs @@ -51,7 +51,7 @@ fn do_another_thing( #[tracing::instrument] fn main() { tracing_subscriber::registry() - .with(tracing_subscriber::fmt::layer()) + .with(tracing_subscriber::fmt::subscriber()) // The `ErrorLayer` subscriber layer enables the use of `SpanTrace`. .with(ErrorLayer::default()) .init(); diff --git a/examples/examples/fmt-stderr.rs b/examples/examples/fmt-stderr.rs index d173f7b019..eeb8a9e1c0 100644 --- a/examples/examples/fmt-stderr.rs +++ b/examples/examples/fmt-stderr.rs @@ -5,7 +5,7 @@ use tracing::error; fn main() { let subscriber = tracing_subscriber::fmt().with_writer(io::stderr).finish(); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { error!("This event will be printed to `stderr`."); }); } diff --git a/examples/examples/fmt.rs b/examples/examples/fmt.rs index 5ae5cbf854..0554a40061 100644 --- a/examples/examples/fmt.rs +++ b/examples/examples/fmt.rs @@ -9,7 +9,7 @@ fn main() { // all spans/events with a level higher than DEBUG (e.g, info, warn, etc.) // will be written to stdout. .with_max_level(Level::DEBUG) - // sets this to be the default, global subscriber for this application. + // sets this to be the default, global collector for this application. .init(); let number_of_yaks = 3; diff --git a/examples/examples/hyper-echo.rs b/examples/examples/hyper-echo.rs index 19c664bfdb..d996741000 100644 --- a/examples/examples/hyper-echo.rs +++ b/examples/examples/hyper-echo.rs @@ -100,7 +100,7 @@ async fn main() -> Result<(), Box> { .filter(Some("hyper"), log::LevelFilter::Trace) .emit_traces() // from `tracing_log::env_logger::BuilderExt` .try_init()?; - tracing::subscriber::set_global_default(subscriber)?; + tracing::collect::set_global_default(subscriber)?; let local_addr: std::net::SocketAddr = ([127, 0, 0, 1], 3000).into(); let server_span = span!(Level::TRACE, "server", %local_addr); diff --git a/examples/examples/inferno-flame.rs b/examples/examples/inferno-flame.rs index 171b1df221..1b54589816 100644 --- a/examples/examples/inferno-flame.rs +++ b/examples/examples/inferno-flame.rs @@ -5,17 +5,17 @@ use std::thread::sleep; use std::time::Duration; use tempdir::TempDir; use tracing::{span, Level}; -use tracing_flame::FlameLayer; +use tracing_flame::FlameSubscriber; use tracing_subscriber::{prelude::*, registry::Registry}; static PATH: &str = "flame.folded"; fn setup_global_subscriber(dir: &Path) -> impl Drop { - let (flame_layer, _guard) = FlameLayer::with_file(dir.join(PATH)).unwrap(); + let (flame_layer, _guard) = FlameSubscriber::with_file(dir.join(PATH)).unwrap(); let subscriber = Registry::default().with(flame_layer); - tracing::subscriber::set_global_default(subscriber).unwrap(); + tracing::collect::set_global_default(subscriber).unwrap(); _guard } diff --git a/examples/examples/instrumented-error.rs b/examples/examples/instrumented-error.rs index 291eb812be..367e38e0e1 100644 --- a/examples/examples/instrumented-error.rs +++ b/examples/examples/instrumented-error.rs @@ -44,7 +44,7 @@ fn do_another_thing( #[tracing::instrument] fn main() { tracing_subscriber::registry() - .with(tracing_subscriber::fmt::layer()) + .with(tracing_subscriber::fmt::subscriber()) // The `ErrorLayer` subscriber layer enables the use of `SpanTrace`. .with(ErrorLayer::default()) .init(); diff --git a/examples/examples/journald.rs b/examples/examples/journald.rs index e2471415b3..ba811ac4a1 100644 --- a/examples/examples/journald.rs +++ b/examples/examples/journald.rs @@ -6,11 +6,11 @@ use tracing_subscriber::prelude::*; mod yak_shave; fn main() { - let registry = - tracing_subscriber::registry().with(tracing_subscriber::fmt::layer().with_target(false)); - match tracing_journald::layer() { - Ok(layer) => { - registry.with(layer).init(); + let registry = tracing_subscriber::registry() + .with(tracing_subscriber::fmt::subscriber().with_target(false)); + match tracing_journald::subscriber() { + Ok(subscriber) => { + registry.with(subscriber).init(); } // journald is typically available on Linux systems, but nowhere else. Portable software // should handle its absence gracefully. diff --git a/examples/examples/opentelemetry-remote-context.rs b/examples/examples/opentelemetry-remote-context.rs index d3af423d38..11647ae6e9 100644 --- a/examples/examples/opentelemetry-remote-context.rs +++ b/examples/examples/opentelemetry-remote-context.rs @@ -2,7 +2,7 @@ use opentelemetry::{api, api::HttpTextFormat}; use std::collections::HashMap; use tracing::span; use tracing_opentelemetry::OpenTelemetrySpanExt; -use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::subscribe::CollectorExt; use tracing_subscriber::Registry; fn make_request(_cx: api::Context) { @@ -27,7 +27,7 @@ fn main() { // Propagator can be swapped with trace context propagator binary propagator, etc. let propagator = api::B3Propagator::new(); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { // Extract from request headers, or any type that impls `opentelemetry::api::Carrier` let parent_context = propagator.extract(&build_example_carrier()); diff --git a/examples/examples/serde-yak-shave.rs b/examples/examples/serde-yak-shave.rs index e00591f56e..7bc2fcf9b7 100644 --- a/examples/examples/serde-yak-shave.rs +++ b/examples/examples/serde-yak-shave.rs @@ -2,10 +2,10 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use tracing::debug; use tracing_core::{ + collect::Collect, event::Event, metadata::Metadata, span::{Attributes, Id, Record}, - subscriber::Subscriber, }; use tracing_serde::AsSerde; @@ -18,7 +18,7 @@ pub struct JsonSubscriber { next_id: AtomicUsize, // you need to assign span IDs, so you need a counter } -impl Subscriber for JsonSubscriber { +impl Collect for JsonSubscriber { fn enabled(&self, metadata: &Metadata<'_>) -> bool { let json = json!({ "enabled": { @@ -85,7 +85,7 @@ fn main() { next_id: AtomicUsize::new(1), }; - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { let number_of_yaks = 3; debug!("preparing to shave {} yaks", number_of_yaks); diff --git a/examples/examples/sloggish/main.rs b/examples/examples/sloggish/main.rs index e41ed70d86..11b6fda2c8 100644 --- a/examples/examples/sloggish/main.rs +++ b/examples/examples/sloggish/main.rs @@ -19,7 +19,7 @@ use self::sloggish_subscriber::SloggishSubscriber; fn main() { let subscriber = SloggishSubscriber::new(2); - tracing::subscriber::set_global_default(subscriber).unwrap(); + tracing::collect::set_global_default(subscriber).unwrap(); let app_span = span!(Level::TRACE, "", version = %5.0); let _e = app_span.enter(); diff --git a/examples/examples/sloggish/sloggish_subscriber.rs b/examples/examples/sloggish/sloggish_subscriber.rs index 94cf90a378..3b9fa14988 100644 --- a/examples/examples/sloggish/sloggish_subscriber.rs +++ b/examples/examples/sloggish/sloggish_subscriber.rs @@ -13,7 +13,7 @@ use ansi_term::{Color, Style}; use tracing::{ field::{Field, Visit}, - Id, Level, Subscriber, + Collect, Id, Level, }; use std::{ @@ -194,7 +194,7 @@ impl SloggishSubscriber { } } -impl Subscriber for SloggishSubscriber { +impl Collect for SloggishSubscriber { fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool { true } diff --git a/examples/examples/subscriber-filter.rs b/examples/examples/subscriber-filter.rs index 459b76b67b..3e5b9adc8a 100644 --- a/examples/examples/subscriber-filter.rs +++ b/examples/examples/subscriber-filter.rs @@ -5,11 +5,11 @@ mod yak_shave; fn main() { use tracing_subscriber::{fmt, EnvFilter}; - let subscriber = fmt::Subscriber::builder() + let subscriber = fmt::Collector::builder() .with_env_filter(EnvFilter::from_default_env()) .finish(); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { let number_of_yaks = 3; tracing::debug!("preparing to shave {} yaks", number_of_yaks); diff --git a/examples/examples/toggle-layers.rs b/examples/examples/toggle-layers.rs index f4cbe4b222..2f53fe8dfd 100644 --- a/examples/examples/toggle-layers.rs +++ b/examples/examples/toggle-layers.rs @@ -1,5 +1,5 @@ #![deny(rust_2018_idioms)] -/// This is a example showing how `Layer` can be enabled or disabled by +/// This is a example showing how `Subscriber`s can be enabled or disabled by /// by wrapping them with an `Option`. This example shows `fmt` and `json` /// being toggled based on the `json` command line flag. /// @@ -28,9 +28,9 @@ fn main() { .get_matches(); let (json, plain) = if matches.is_present("json") { - (Some(tracing_subscriber::fmt::layer().json()), None) + (Some(tracing_subscriber::fmt::subscriber().json()), None) } else { - (None, Some(tracing_subscriber::fmt::layer())) + (None, Some(tracing_subscriber::fmt::subscriber())) }; tracing_subscriber::registry().with(json).with(plain).init(); diff --git a/examples/examples/tower-server.rs b/examples/examples/tower-server.rs index dceb71ba5e..da859dd1df 100644 --- a/examples/examples/tower-server.rs +++ b/examples/examples/tower-server.rs @@ -4,7 +4,7 @@ use hyper::{Body, Server}; use std::task::{Context, Poll}; use std::time::Duration; use tower::{Service, ServiceBuilder}; -use tracing::dispatcher; +use tracing::dispatch; use tracing::info; use tracing_tower::request_span::make; @@ -54,7 +54,7 @@ impl Service> for Svc { rsp.headers = ?rsp.headers() ); - dispatcher::get_default(|dispatch| { + dispatch::get_default(|dispatch| { let id = span.id().expect("Missing ID; this is a bug"); if let Some(current) = dispatch.current_span().id() { dispatch.record_follows_from(&id, current) diff --git a/tracing-appender/src/lib.rs b/tracing-appender/src/lib.rs index 7476f079bc..a6ba0f00ea 100644 --- a/tracing-appender/src/lib.rs +++ b/tracing-appender/src/lib.rs @@ -175,7 +175,7 @@ mod worker; /// # fn docs() { /// let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); /// let subscriber = tracing_subscriber::fmt().with_writer(non_blocking); -/// tracing::subscriber::with_default(subscriber.finish(), || { +/// tracing::collect::with_default(subscriber.finish(), || { /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// # } diff --git a/tracing-appender/src/non_blocking.rs b/tracing-appender/src/non_blocking.rs index 5cabc0db4b..464017affe 100644 --- a/tracing-appender/src/non_blocking.rs +++ b/tracing-appender/src/non_blocking.rs @@ -40,8 +40,8 @@ //! ``` rust //! # fn docs() { //! let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); -//! let subscriber = tracing_subscriber::fmt().with_writer(non_blocking); -//! tracing::subscriber::with_default(subscriber.finish(), || { +//! let collector = tracing_subscriber::fmt().with_writer(non_blocking); +//! tracing::collect::with_default(collector.finish(), || { //! tracing::event!(tracing::Level::INFO, "Hello"); //! }); //! # } @@ -92,8 +92,8 @@ pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// fn main () { /// # fn doc() { /// let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); -/// let subscriber = tracing_subscriber::fmt().with_writer(non_blocking); -/// tracing::subscriber::with_default(subscriber.finish(), || { +/// let collector = tracing_subscriber::fmt().with_writer(non_blocking); +/// tracing::collect::with_default(collector.finish(), || { /// // Emit some tracing events within context of the non_blocking `_guard` and tracing subscriber /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); @@ -111,7 +111,7 @@ pub struct WorkerGuard { /// A non-blocking writer. /// /// While the line between "blocking" and "non-blocking" IO is fuzzy, writing to a file is typically -/// considered to be a _blocking_ operation. For an application whose `Subscriber` writes spans and events +/// considered to be a _blocking_ operation. For an application whose `Collector` writes spans and events /// as they are emitted, an application might find the latency profile to be unacceptable. /// `NonBlocking` moves the writing out of an application's data path by sending spans and events /// to a dedicated logging thread. @@ -396,8 +396,8 @@ mod test { for _ in 0..10 { let cloned_non_blocking = non_blocking.clone(); join_handles.push(thread::spawn(move || { - let subscriber = tracing_subscriber::fmt().with_writer(cloned_non_blocking); - tracing::subscriber::with_default(subscriber.finish(), || { + let collector = tracing_subscriber::fmt().with_writer(cloned_non_blocking); + tracing::collect::with_default(collector.finish(), || { tracing::event!(tracing::Level::INFO, "Hello"); }); })); diff --git a/tracing-appender/src/rolling.rs b/tracing-appender/src/rolling.rs index a2b1f9c1bc..0eeab87f1e 100644 --- a/tracing-appender/src/rolling.rs +++ b/tracing-appender/src/rolling.rs @@ -130,9 +130,9 @@ impl io::Write for RollingFileAppender { /// let appender = tracing_appender::rolling::minutely("/some/path", "rolling.log"); /// let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender); /// -/// let subscriber = tracing_subscriber::fmt().with_writer(non_blocking_appender); +/// let collector = tracing_subscriber::fmt().with_writer(non_blocking_appender); /// -/// tracing::subscriber::with_default(subscriber.finish(), || { +/// tracing::collect::with_default(collector.finish(), || { /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// # } @@ -165,9 +165,9 @@ pub fn minutely( /// let appender = tracing_appender::rolling::hourly("/some/path", "rolling.log"); /// let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender); /// -/// let subscriber = tracing_subscriber::fmt().with_writer(non_blocking_appender); +/// let collector = tracing_subscriber::fmt().with_writer(non_blocking_appender); /// -/// tracing::subscriber::with_default(subscriber.finish(), || { +/// tracing::collect::with_default(collector.finish(), || { /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// # } @@ -201,9 +201,9 @@ pub fn hourly( /// let appender = tracing_appender::rolling::daily("/some/path", "rolling.log"); /// let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender); /// -/// let subscriber = tracing_subscriber::fmt().with_writer(non_blocking_appender); +/// let collector = tracing_subscriber::fmt().with_writer(non_blocking_appender); /// -/// tracing::subscriber::with_default(subscriber.finish(), || { +/// tracing::collect::with_default(collector.finish(), || { /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// # } @@ -235,9 +235,9 @@ pub fn daily( /// let appender = tracing_appender::rolling::never("/some/path", "non-rolling.log"); /// let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender); /// -/// let subscriber = tracing_subscriber::fmt().with_writer(non_blocking_appender); +/// let collector = tracing_subscriber::fmt().with_writer(non_blocking_appender); /// -/// tracing::subscriber::with_default(subscriber.finish(), || { +/// tracing::collect::with_default(collector.finish(), || { /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// # } diff --git a/tracing-attributes/tests/async_fn.rs b/tracing-attributes/tests/async_fn.rs index f7e5f3b743..71bafbf994 100644 --- a/tracing-attributes/tests/async_fn.rs +++ b/tracing-attributes/tests/async_fn.rs @@ -4,7 +4,7 @@ mod support; use support::*; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing_attributes::instrument; #[instrument] @@ -16,7 +16,7 @@ async fn test_async_fn(polls: usize) -> Result<(), ()> { #[test] fn async_fn_only_enters_for_polls() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("test_async_fn")) .enter(span::mock().named("test_async_fn")) .event(event::mock().with_fields(field::mock("awaiting").with_value(&true))) @@ -26,7 +26,7 @@ fn async_fn_only_enters_for_polls() { .drop_span(span::mock().named("test_async_fn")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { block_on_future(async { test_async_fn(2).await }).unwrap(); }); handle.assert_finished(); @@ -46,7 +46,7 @@ fn async_fn_nested() { let span = span::mock().named("test_async_fns_nested"); let span2 = span::mock().named("test_async_fns_nested_other"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span.clone()) .enter(span.clone()) .new_span(span2.clone()) @@ -59,7 +59,7 @@ fn async_fn_nested() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { block_on_future(async { test_async_fns_nested().await }); }); @@ -121,7 +121,7 @@ fn async_fn_with_async_trait() { let span = span::mock().named("foo"); let span2 = span::mock().named("bar"); let span3 = span::mock().named("baz"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone() .with_field(field::mock("self")) @@ -143,7 +143,7 @@ fn async_fn_with_async_trait() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let mut test = TestImpl(2); block_on_future(async { test.foo(5).await }); }); @@ -177,7 +177,7 @@ fn async_fn_with_async_trait_and_fields_expressions() { } let span = span::mock().named("call"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("v") @@ -192,7 +192,7 @@ fn async_fn_with_async_trait_and_fields_expressions() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { block_on_future(async { TestImpl.call(5).await }); }); @@ -229,7 +229,7 @@ fn async_fn_with_async_trait_and_fields_expressions_with_generic_parameter() { //let span = span::mock().named("call"); let span2 = span::mock().named("call_with_self"); let span3 = span::mock().named("call_with_mut_self"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() /*.new_span(span.clone() .with_field( field::mock("Self").with_value(&"TestImpler"))) @@ -255,7 +255,7 @@ fn async_fn_with_async_trait_and_fields_expressions_with_generic_parameter() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { block_on_future(async { TestImpl::call().await; TestImpl.call_with_self().await; diff --git a/tracing-attributes/tests/destructuring.rs b/tracing-attributes/tests/destructuring.rs index 9d01d415ed..71149bb89d 100644 --- a/tracing-attributes/tests/destructuring.rs +++ b/tracing-attributes/tests/destructuring.rs @@ -1,7 +1,7 @@ mod support; use support::*; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing_attributes::instrument; #[test] @@ -11,7 +11,7 @@ fn destructure_tuples() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("arg1") @@ -26,7 +26,7 @@ fn destructure_tuples() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn((1, 2)); }); @@ -40,7 +40,7 @@ fn destructure_nested_tuples() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("arg1") @@ -57,7 +57,7 @@ fn destructure_nested_tuples() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(((1, 2), (3, 4))); }); @@ -71,7 +71,7 @@ fn destructure_refs() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone() .with_field(field::mock("arg1").with_value(&format_args!("1")).only()), @@ -82,7 +82,7 @@ fn destructure_refs() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(&1); }); @@ -98,7 +98,7 @@ fn destructure_tuple_structs() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("arg1") @@ -113,7 +113,7 @@ fn destructure_tuple_structs() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(Foo(1, 2)); }); @@ -139,7 +139,7 @@ fn destructure_structs() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("arg1") @@ -154,7 +154,7 @@ fn destructure_structs() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(Foo { bar: 1, baz: 2 }); }); @@ -184,7 +184,7 @@ fn destructure_everything() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("arg1") @@ -201,7 +201,7 @@ fn destructure_everything() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = Foo { bar: Bar((1, 2)), baz: (3, 4), diff --git a/tracing-attributes/tests/err.rs b/tracing-attributes/tests/err.rs index b2b61bde5f..cacf49b850 100644 --- a/tracing-attributes/tests/err.rs +++ b/tracing-attributes/tests/err.rs @@ -4,7 +4,7 @@ mod support; use support::*; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing::Level; use tracing_attributes::instrument; @@ -19,7 +19,7 @@ fn err() -> Result { #[test] fn test() { let span = span::mock().named("err"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span.clone()) .enter(span.clone()) .event(event::mock().at_level(Level::ERROR)) @@ -27,7 +27,7 @@ fn test() { .drop_span(span) .done() .run_with_handle(); - with_default(subscriber, || err().ok()); + with_default(collector, || err().ok()); handle.assert_finished(); } @@ -40,7 +40,7 @@ fn err_early_return() -> Result { #[test] fn test_early_return() { let span = span::mock().named("err_early_return"); - let (subscriber, handle) = subscriber::mock() + let (subscriber, handle) = collector::mock() .new_span(span.clone()) .enter(span.clone()) .event(event::mock().at_level(Level::ERROR)) @@ -63,7 +63,7 @@ async fn err_async(polls: usize) -> Result { #[test] fn test_async() { let span = span::mock().named("err_async"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span.clone()) .enter(span.clone()) .event( @@ -78,7 +78,7 @@ fn test_async() { .drop_span(span) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { block_on_future(async { err_async(2).await }).ok(); }); handle.assert_finished(); diff --git a/tracing-attributes/tests/fields.rs b/tracing-attributes/tests/fields.rs index de038ca7b1..9b18cf6b2c 100644 --- a/tracing-attributes/tests/fields.rs +++ b/tracing-attributes/tests/fields.rs @@ -3,7 +3,7 @@ use support::*; use crate::support::field::mock; use crate::support::span::NewSpan; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing_attributes::instrument; #[instrument(fields(foo = "bar", dsa = true, num = 1))] @@ -137,13 +137,13 @@ fn empty_field() { } fn run_test T, T>(span: NewSpan, fun: F) { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span) .enter(span::mock()) .exit(span::mock()) .done() .run_with_handle(); - with_default(subscriber, fun); + with_default(collector, fun); handle.assert_finished(); } diff --git a/tracing-attributes/tests/instrument.rs b/tracing-attributes/tests/instrument.rs index d4ebcdba25..3a3a54dd62 100644 --- a/tracing-attributes/tests/instrument.rs +++ b/tracing-attributes/tests/instrument.rs @@ -1,7 +1,7 @@ mod support; use support::*; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing::Level; use tracing_attributes::instrument; @@ -21,7 +21,7 @@ fn override_everything() { .named("my_other_fn") .at_level(Level::DEBUG) .with_target("my_target"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span.clone()) .enter(span.clone()) .exit(span.clone()) @@ -33,7 +33,7 @@ fn override_everything() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(); my_other_fn(); }); @@ -55,7 +55,7 @@ fn fields() { .named("my_fn") .at_level(Level::DEBUG) .with_target("my_target"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("arg1") @@ -81,7 +81,7 @@ fn fields() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(2, false); my_fn(3, true); }); @@ -105,7 +105,7 @@ fn skip() { .named("my_fn") .at_level(Level::DEBUG) .with_target("my_target"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone() .with_field(field::mock("arg1").with_value(&format_args!("2")).only()), @@ -124,7 +124,7 @@ fn skip() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(2, UnDebug(0), UnDebug(1)); my_fn(3, UnDebug(0), UnDebug(1)); }); @@ -146,7 +146,7 @@ fn generics() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("arg1") @@ -160,7 +160,7 @@ fn generics() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { my_fn(Foo, false); }); @@ -179,7 +179,7 @@ fn methods() { let span = span::mock().named("my_fn"); - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span.clone().with_field( field::mock("self") @@ -193,7 +193,7 @@ fn methods() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = Foo; foo.my_fn(42); }); diff --git a/tracing-attributes/tests/levels.rs b/tracing-attributes/tests/levels.rs index d1ce6b53b6..dfd064bb04 100644 --- a/tracing-attributes/tests/levels.rs +++ b/tracing-attributes/tests/levels.rs @@ -1,7 +1,7 @@ mod support; use support::*; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing::Level; use tracing_attributes::instrument; @@ -21,7 +21,7 @@ fn named_levels() { #[instrument(level = "eRrOr")] fn error() {} - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("trace").at_level(Level::TRACE)) .enter(span::mock().named("trace").at_level(Level::TRACE)) .exit(span::mock().named("trace").at_level(Level::TRACE)) @@ -40,7 +40,7 @@ fn named_levels() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { trace(); debug(); info(); @@ -67,7 +67,7 @@ fn numeric_levels() { #[instrument(level = 5)] fn error() {} - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("trace").at_level(Level::TRACE)) .enter(span::mock().named("trace").at_level(Level::TRACE)) .exit(span::mock().named("trace").at_level(Level::TRACE)) @@ -86,7 +86,7 @@ fn numeric_levels() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { trace(); debug(); info(); diff --git a/tracing-attributes/tests/names.rs b/tracing-attributes/tests/names.rs index 15497784ca..b272f9dad0 100644 --- a/tracing-attributes/tests/names.rs +++ b/tracing-attributes/tests/names.rs @@ -1,7 +1,7 @@ mod support; use support::*; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing_attributes::instrument; #[instrument] @@ -18,14 +18,14 @@ fn custom_name_no_equals() {} #[test] fn default_name_test() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("default_name")) .enter(span::mock().named("default_name")) .exit(span::mock().named("default_name")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { default_name(); }); @@ -34,14 +34,14 @@ fn default_name_test() { #[test] fn custom_name_test() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("my_name")) .enter(span::mock().named("my_name")) .exit(span::mock().named("my_name")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { custom_name(); }); @@ -50,14 +50,14 @@ fn custom_name_test() { #[test] fn custom_name_no_equals_test() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("my_other_name")) .enter(span::mock().named("my_other_name")) .exit(span::mock().named("my_other_name")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { custom_name_no_equals(); }); diff --git a/tracing-attributes/tests/targets.rs b/tracing-attributes/tests/targets.rs index 516a8f4aec..08949e0c52 100644 --- a/tracing-attributes/tests/targets.rs +++ b/tracing-attributes/tests/targets.rs @@ -1,7 +1,7 @@ mod support; use support::*; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing_attributes::instrument; #[instrument] @@ -24,7 +24,7 @@ mod my_mod { #[test] fn default_targets() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock() .named("default_target") @@ -58,7 +58,7 @@ fn default_targets() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { default_target(); my_mod::default_target(); }); @@ -68,7 +68,7 @@ fn default_targets() { #[test] fn custom_targets() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("custom_target").with_target("my_target")) .enter(span::mock().named("custom_target").with_target("my_target")) .exit(span::mock().named("custom_target").with_target("my_target")) @@ -90,7 +90,7 @@ fn custom_targets() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { custom_target(); my_mod::custom_target(); }); diff --git a/tracing-core/README.md b/tracing-core/README.md index 715af65370..edc5251c9c 100644 --- a/tracing-core/README.md +++ b/tracing-core/README.md @@ -40,7 +40,7 @@ The crate provides: * [`Event`] represents a single event within a trace. -* [`Subscriber`], the trait implemented to collect trace data. +* [`Collect`], the trait implemented to collect trace data. * [`Metadata`] and [`Callsite`] provide information describing spans and events. @@ -87,7 +87,7 @@ The following crate feature flags are available: [`tracing`]: ../tracing [`span::Id`]: https://docs.rs/tracing-core/0.1.17/tracing_core/span/struct.Id.html [`Event`]: https://docs.rs/tracing-core/0.1.17/tracing_core/event/struct.Event.html -[`Subscriber`]: https://docs.rs/tracing-core/0.1.17/tracing_core/subscriber/trait.Subscriber.html +[`Collect`]: https://docs.rs/tracing-core/0.1.17/tracing_core/collect/trait.Collect.html [`Metadata`]: https://docs.rs/tracing-core/0.1.17/tracing_core/metadata/struct.Metadata.html [`Callsite`]: https://docs.rs/tracing-core/0.1.17/tracing_core/callsite/trait.Callsite.html [`Field`]: https://docs.rs/tracing-core/0.1.17/tracing_core/field/struct.Field.html diff --git a/tracing-core/src/callsite.rs b/tracing-core/src/callsite.rs index 01fecb3a2b..8fad4f8ae1 100644 --- a/tracing-core/src/callsite.rs +++ b/tracing-core/src/callsite.rs @@ -1,9 +1,9 @@ //! Callsites represent the source locations from which spans or events //! originate. use crate::{ - dispatcher::{self, Dispatch}, + collect::Interest, + dispatch::{self, Dispatch}, metadata::{LevelFilter, Metadata}, - subscriber::Interest, }; use core::{ fmt, @@ -17,11 +17,11 @@ type Callsites = LinkedList; /// Trait implemented by callsites. /// /// These functions are only intended to be called by the callsite registry, which -/// correctly handles determining the common interest between all subscribers. +/// correctly handles determining the common interest between all collectors. pub trait Callsite: Sync { /// Sets the [`Interest`] for this callsite. /// - /// [`Interest`]: super::subscriber::Interest + /// [`Interest`]: super::collect::Interest fn set_interest(&self, interest: Interest); /// Returns the [metadata] associated with the callsite. @@ -70,7 +70,7 @@ mod inner { use std::sync::RwLock; use std::vec::Vec; - type Dispatchers = Vec; + type Dispatchers = Vec; struct Registry { callsites: Callsites, @@ -88,21 +88,21 @@ mod inner { /// /// This function is intended for runtime reconfiguration of filters on traces /// when the filter recalculation is much less frequent than trace events are. - /// The alternative is to have the [`Subscriber`] that supports runtime + /// The alternative is to have the [`Collect`] that supports runtime /// reconfiguration of filters always return [`Interest::sometimes()`] so that /// [`enabled`] is evaluated for every event. /// /// This function will also re-compute the global maximum level as determined by - /// the [`max_level_hint`] method. If a [`Subscriber`] + /// the [`max_level_hint`] method. If a [`Collect`] /// implementation changes the value returned by its `max_level_hint` /// implementation at runtime, then it **must** call this function after that /// value changes, in order for the change to be reflected. /// - /// [`max_level_hint`]: crate::subscriber::Subscriber::max_level_hint + /// [`max_level_hint`]: crate::collect::Collect::max_level_hint /// [`Callsite`]: crate::callsite::Callsite - /// [`enabled`]: crate::subscriber::Subscriber::enabled - /// [`Interest::sometimes()`]: crate::subscriber::Interest::sometimes - /// [`Subscriber`]: crate::subscriber::Subscriber + /// [`enabled`]: crate::collect::Collect::enabled + /// [`Interest::sometimes()`]: crate::collect::Interest::sometimes + /// [`Collect`]: crate::collect::Collect pub fn rebuild_interest_cache() { let mut dispatchers = REGISTRY.dispatchers.write().unwrap(); let callsites = ®ISTRY.callsites; @@ -129,12 +129,12 @@ mod inner { } fn rebuild_callsite_interest( - dispatchers: &[dispatcher::Registrar], + dispatchers: &[dispatch::Registrar], callsite: &'static dyn Callsite, ) { let meta = callsite.metadata(); - // Iterate over the subscribers in the registry, and — if they are + // Iterate over the collectors in the registry, and — if they are // active — register the callsite with them. let mut interests = dispatchers.iter().filter_map(|registrar| { registrar @@ -142,7 +142,7 @@ mod inner { .map(|dispatch| dispatch.register_callsite(meta)) }); - // Use the first subscriber's `Interest` as the base value. + // Use the first collector's `Interest` as the base value. let interest = if let Some(interest) = interests.next() { // Combine all remaining `Interest`s. interests.fold(interest, Interest::and) @@ -154,11 +154,11 @@ mod inner { callsite.set_interest(interest) } - fn rebuild_interest(callsites: &Callsites, dispatchers: &mut Vec) { + fn rebuild_interest(callsites: &Callsites, dispatchers: &mut Vec) { let mut max_level = LevelFilter::OFF; dispatchers.retain(|registrar| { if let Some(dispatch) = registrar.upgrade() { - // If the subscriber did not provide a max level hint, assume + // If the collector did not provide a max level hint, assume // that it may enable every level. let level_hint = dispatch.max_level_hint().unwrap_or(LevelFilter::TRACE); if level_hint > max_level { @@ -185,23 +185,24 @@ mod inner { /// /// This function is intended for runtime reconfiguration of filters on traces /// when the filter recalculation is much less frequent than trace events are. - /// The alternative is to have the [`Subscriber`] that supports runtime + /// The alternative is to have the [collector] that supports runtime /// reconfiguration of filters always return [`Interest::sometimes()`] so that /// [`enabled`] is evaluated for every event. /// /// This function will also re-compute the global maximum level as determined by - /// the [`max_level_hint`] method. If a [`Subscriber`] + /// the [`max_level_hint`] method. If a [`Collect`] /// implementation changes the value returned by its `max_level_hint` /// implementation at runtime, then it **must** call this function after that /// value changes, in order for the change to be reflected. /// - /// [`max_level_hint`]: crate::subscriber::Subscriber::max_level_hint + /// [`max_level_hint`]: crate::collector::Collector::max_level_hint /// [`Callsite`]: crate::callsite::Callsite - /// [`enabled`]: crate::subscriber::Subscriber::enabled - /// [`Interest::sometimes()`]: crate::subscriber::Interest::sometimes - /// [`Subscriber`]: crate::subscriber::Subscriber + /// [`enabled`]: crate::collector::Collector::enabled + /// [`Interest::sometimes()`]: crate::collect::Interest::sometimes + /// [collector]: crate::collect::Collect + /// [`Collect`]: crate::collect::Collect pub fn rebuild_interest_cache() { - register_dispatch(dispatcher::get_global()); + register_dispatch(dispatch::get_global()); } /// Register a new `Callsite` with the global registry. @@ -209,12 +210,12 @@ mod inner { /// This should be called once per callsite after the callsite has been /// constructed. pub fn register(registration: &'static Registration) { - rebuild_callsite_interest(dispatcher::get_global(), registration.callsite); + rebuild_callsite_interest(dispatch::get_global(), registration.callsite); REGISTRY.push(registration); } pub(crate) fn register_dispatch(dispatcher: &Dispatch) { - // If the subscriber did not provide a max level hint, assume + // If the collector did not provide a max level hint, assume // that it may enable every level. let level_hint = dispatcher.max_level_hint().unwrap_or(LevelFilter::TRACE); diff --git a/tracing-core/src/subscriber.rs b/tracing-core/src/collect.rs similarity index 68% rename from tracing-core/src/subscriber.rs rename to tracing-core/src/collect.rs index 1dcd541987..ef5ad95ac9 100644 --- a/tracing-core/src/subscriber.rs +++ b/tracing-core/src/collect.rs @@ -1,4 +1,4 @@ -//! Subscribers collect and record trace data. +//! Collectors collect and record trace data. use crate::{span, Event, LevelFilter, Metadata}; use core::any::{Any, TypeId}; @@ -6,15 +6,15 @@ use core::any::{Any, TypeId}; /// Trait representing the functions required to collect trace data. /// /// Crates that provide implementations of methods for collecting or recording -/// trace data should implement the `Subscriber` interface. This trait is +/// trace data should implement the `Collect` interface. This trait is /// intended to represent fundamental primitives for collecting trace events and /// spans — other libraries may offer utility functions and types to make -/// subscriber implementations more modular or improve the ergonomics of writing -/// subscribers. +/// collector implementations more modular or improve the ergonomics of writing +/// collectors. /// -/// A subscriber is responsible for the following: +/// A collector is responsible for the following: /// - Registering new spans as they are created, and providing them with span -/// IDs. Implicitly, this means the subscriber may determine the strategy for +/// IDs. Implicitly, this means the collector may determine the strategy for /// determining span equality. /// - Recording the attachment of field values and follows-from annotations to /// spans. @@ -23,114 +23,114 @@ use core::any::{Any, TypeId}; /// - Observing spans as they are entered, exited, and closed, and events as /// they occur. /// -/// When a span is entered or exited, the subscriber is provided only with the +/// When a span is entered or exited, the collector is provided only with the /// [ID] with which it tagged that span when it was created. This means -/// that it is up to the subscriber to determine whether and how span _data_ — +/// that it is up to the collector to determine whether and how span _data_ — /// the fields and metadata describing the span — should be stored. The /// [`new_span`] function is called when a new span is created, and at that -/// point, the subscriber _may_ choose to store the associated data if it will +/// point, the collector _may_ choose to store the associated data if it will /// be referenced again. However, if the data has already been recorded and will -/// not be needed by the implementations of `enter` and `exit`, the subscriber +/// not be needed by the implementations of `enter` and `exit`, the collector /// may freely discard that data without allocating space to store it. /// /// ## Overriding default impls /// -/// Some trait methods on `Subscriber` have default implementations, either in -/// order to reduce the surface area of implementing `Subscriber`, or for -/// backward-compatibility reasons. However, many subscribers will likely want +/// Some trait methods on `Collect` have default implementations, either in +/// order to reduce the surface area of implementing `Collect`, or for +/// backward-compatibility reasons. However, many collectors will likely want /// to override these default implementations. /// /// The following methods are likely of interest: /// /// - [`register_callsite`] is called once for each callsite from which a span /// event may originate, and returns an [`Interest`] value describing whether or -/// not the subscriber wishes to see events or spans from that callsite. By +/// not the collector wishes to see events or spans from that callsite. By /// default, it calls [`enabled`], and returns `Interest::always()` if /// `enabled` returns true, or `Interest::never()` if enabled returns false. -/// However, if the subscriber's interest can change dynamically at runtime, +/// However, if the collector's interest can change dynamically at runtime, /// it may want to override this function to return `Interest::sometimes()`. -/// Additionally, subscribers which wish to perform a behaviour once for each +/// Additionally, collectors which wish to perform a behaviour once for each /// callsite, such as allocating storage for data related to that callsite, /// can perform it in `register_callsite`. /// - [`clone_span`] is called every time a span ID is cloned, and [`try_close`] /// is called when a span ID is dropped. By default, these functions do /// nothing. However, they can be used to implement reference counting for -/// spans, allowing subscribers to free storage for span data and to determine +/// spans, allowing collectors to free storage for span data and to determine /// when a span has _closed_ permanently (rather than being exited). -/// Subscribers which store per-span data or which need to track span closures +/// Collectors which store per-span data or which need to track span closures /// should override these functions together. /// /// [ID]: super::span::Id -/// [`new_span`]: Subscriber::new_span -/// [`register_callsite`]: Subscriber::register_callsite +/// [`new_span`]: Collect::new_span +/// [`register_callsite`]: Collect::register_callsite /// [`Interest`]: Interest -/// [`enabled`]: Subscriber::enabled -/// [`clone_span`]: Subscriber::clone_span -/// [`try_close`]: Subscriber::try_close -pub trait Subscriber: 'static { +/// [`enabled`]: Collect::enabled +/// [`clone_span`]: Collect::clone_span +/// [`try_close`]: Collect::try_close +pub trait Collect: 'static { // === Span registry methods ============================================== - /// Registers a new callsite with this subscriber, returning whether or not - /// the subscriber is interested in being notified about the callsite. + /// Registers a new callsite with this collector, returning whether or not + /// the collector is interested in being notified about the callsite. /// - /// By default, this function assumes that the subscriber's [filter] + /// By default, this function assumes that the collector's [filter] /// represents an unchanging view of its interest in the callsite. However, - /// if this is not the case, subscribers may override this function to + /// if this is not the case, collectors may override this function to /// indicate different interests, or to implement behaviour that should run /// once for every callsite. /// /// This function is guaranteed to be called at least once per callsite on - /// every active subscriber. The subscriber may store the keys to fields it + /// every active collector. The collector may store the keys to fields it /// cares about in order to reduce the cost of accessing fields by name, /// preallocate storage for that callsite, or perform any other actions it /// wishes to perform once for each callsite. /// - /// The subscriber should then return an [`Interest`], indicating + /// The collector should then return an [`Interest`], indicating /// whether it is interested in being notified about that callsite in the - /// future. This may be `Always` indicating that the subscriber always + /// future. This may be `Always` indicating that the collector always /// wishes to be notified about the callsite, and its filter need not be - /// re-evaluated; `Sometimes`, indicating that the subscriber may sometimes + /// re-evaluated; `Sometimes`, indicating that the collector may sometimes /// care about the callsite but not always (such as when sampling), or - /// `Never`, indicating that the subscriber never wishes to be notified about - /// that callsite. If all active subscribers return `Never`, a callsite will - /// never be enabled unless a new subscriber expresses interest in it. + /// `Never`, indicating that the collector never wishes to be notified about + /// that callsite. If all active collectors return `Never`, a callsite will + /// never be enabled unless a new collector expresses interest in it. /// - /// `Subscriber`s which require their filters to be run every time an event + /// `Collector`s which require their filters to be run every time an event /// occurs or a span is entered::exited should return `Interest::sometimes`. - /// If a subscriber returns `Interest::sometimes`, then its' [`enabled`] method + /// If a collector returns `Interest::sometimes`, then its' [`enabled`] method /// will be called every time an event or span is created from that callsite. /// - /// For example, suppose a sampling subscriber is implemented by + /// For example, suppose a sampling collector is implemented by /// incrementing a counter every time `enabled` is called and only returning /// `true` when the counter is divisible by a specified sampling rate. If - /// that subscriber returns `Interest::always` from `register_callsite`, then + /// that collector returns `Interest::always` from `register_callsite`, then /// the filter will not be re-evaluated once it has been applied to a given /// set of metadata. Thus, the counter will not be incremented, and the span /// or event that corresponds to the metadata will never be `enabled`. /// - /// `Subscriber`s that need to change their filters occasionally should call + /// `Collector`s that need to change their filters occasionally should call /// [`rebuild_interest_cache`] to re-evaluate `register_callsite` for all /// callsites. /// - /// Similarly, if a `Subscriber` has a filtering strategy that can be + /// Similarly, if a `Collector` has a filtering strategy that can be /// changed dynamically at runtime, it would need to re-evaluate that filter /// if the cached results have changed. /// - /// A subscriber which manages fanout to multiple other subscribers - /// should proxy this decision to all of its child subscribers, + /// A collector which manages fanout to multiple other collectors + /// should proxy this decision to all of its child collectors, /// returning `Interest::never` only if _all_ such children return - /// `Interest::never`. If the set of subscribers to which spans are - /// broadcast may change dynamically, the subscriber should also never - /// return `Interest::Never`, as a new subscriber may be added that _is_ + /// `Interest::never`. If the set of collectors to which spans are + /// broadcast may change dynamically, the collector should also never + /// return `Interest::Never`, as a new collector may be added that _is_ /// interested. /// /// # Notes - /// This function may be called again when a new subscriber is created or + /// This function may be called again when a new collector is created or /// when the registry is invalidated. /// - /// If a subscriber returns `Interest::never` for a particular callsite, it + /// If a collector returns `Interest::never` for a particular callsite, it /// _may_ still see spans and events originating from that callsite, if - /// another subscriber expressed interest in it. + /// another collector expressed interest in it. /// /// [filter]: Self::enabled /// [metadata]: super::metadata::Metadata @@ -150,12 +150,12 @@ pub trait Subscriber: 'static { /// /// By default, it is assumed that this filter needs only be evaluated once /// for each callsite, so it is called by [`register_callsite`] when each - /// callsite is registered. The result is used to determine if the subscriber + /// callsite is registered. The result is used to determine if the collector /// is always [interested] or never interested in that callsite. This is intended /// primarily as an optimization, so that expensive filters (such as those /// involving string search, et cetera) need not be re-evaluated. /// - /// However, if the subscriber's interest in a particular span or event may + /// However, if the collector's interest in a particular span or event may /// change, or depends on contexts only determined dynamically at runtime, /// then the `register_callsite` method should be overridden to return /// [`Interest::sometimes`]. In that case, this function will be called every @@ -167,22 +167,22 @@ pub trait Subscriber: 'static { /// [`register_callsite`]: Self::register_callsite fn enabled(&self, metadata: &Metadata<'_>) -> bool; - /// Returns the highest [verbosity level][level] that this `Subscriber` will - /// enable, or `None`, if the subscriber does not implement level-based + /// Returns the highest [verbosity level][level] that this `Collector` will + /// enable, or `None`, if the collector does not implement level-based /// filtering or chooses not to implement this method. /// /// If this method returns a [`Level`][level], it will be used as a hint to /// determine the most verbose level that will be enabled. This will allow /// spans and events which are more verbose than that level to be skipped - /// more efficiently. Subscribers which perform filtering are strongly + /// more efficiently. collectors which perform filtering are strongly /// encouraged to provide an implementation of this method. /// - /// If the maximum level the subscriber will enable can change over the + /// If the maximum level the collector will enable can change over the /// course of its lifetime, it is free to return a different value from /// multiple invocations of this method. However, note that changes in the /// maximum level will **only** be reflected after the callsite [`Interest`] /// cache is rebuilt, by calling the [`callsite::rebuild_interest_cache`][rebuild] - /// function. Therefore, if the subscriber will change the value returned by + /// function. Therefore, if the collector will change the value returned by /// this method, it is responsible for ensuring that /// [`rebuild_interest_cache`][rebuild] is called after the value of the max /// level changes. @@ -198,21 +198,21 @@ pub trait Subscriber: 'static { /// span being constructed. /// /// The provided [`Attributes`] contains any field values that were provided - /// when the span was created. The subscriber may pass a [visitor] to the + /// when the span was created. The collector may pass a [visitor] to the /// `Attributes`' [`record` method] to record these values. /// /// IDs are used to uniquely identify spans and events within the context of a - /// subscriber, so span equality will be based on the returned ID. Thus, if - /// the subscriber wishes for all spans with the same metadata to be + /// collector, so span equality will be based on the returned ID. Thus, if + /// the collector wishes for all spans with the same metadata to be /// considered equal, it should return the same ID every time it is given a /// particular set of metadata. Similarly, if it wishes for two separate /// instances of a span with the same metadata to *not* be equal, it should /// return a distinct ID every time this function is called, regardless of /// the metadata. /// - /// Note that the subscriber is free to assign span IDs based on whatever + /// Note that the collector is free to assign span IDs based on whatever /// scheme it sees fit. Any guarantees about uniqueness, ordering, or ID - /// reuse are left up to the subscriber implementation to determine. + /// reuse are left up to the collector implementation to determine. /// /// [span ID]: super::span::Id /// [`Attributes`]: super::span::Attributes @@ -226,12 +226,12 @@ pub trait Subscriber: 'static { /// /// This method will be invoked when value is recorded on a span. /// Recording multiple values for the same field is possible, - /// but the actual behaviour is defined by the subscriber implementation. + /// but the actual behaviour is defined by the collector implementation. /// /// Keep in mind that a span might not provide a value /// for each field it declares. /// - /// The subscriber is expected to provide a [visitor] to the `Record`'s + /// The collector is expected to provide a [visitor] to the `Record`'s /// [`record` method] in order to record the added values. /// /// # Example @@ -247,11 +247,11 @@ pub trait Subscriber: 'static { /// /// let mut span = span!("my_span", foo = 3, bar, baz); /// - /// // `Subscriber::record` will be called with a `Record` + /// // `Collector::record` will be called with a `Record` /// // containing "bar = false" /// span.record("bar", &false); /// - /// // `Subscriber::record` will be called with a `Record` + /// // `Collector::record` will be called with a `Record` /// // containing "baz = "a string"" /// span.record("baz", &"a string"); /// ``` @@ -273,10 +273,10 @@ pub trait Subscriber: 'static { /// executing. This is used to model causal relationships such as when a /// single future spawns several related background tasks, et cetera. /// - /// If the subscriber has spans corresponding to the given IDs, it should + /// If the collector has spans corresponding to the given IDs, it should /// record this relationship in whatever way it deems necessary. Otherwise, /// if one or both of the given span IDs do not correspond to spans that the - /// subscriber knows about, or if a cyclical relationship would be created + /// collector knows about, or if a cyclical relationship would be created /// (i.e., some span _a_ which proceeds some other span _b_ may not also /// follow from _b_), it may silently do nothing. fn record_follows_from(&self, span: &span::Id, follows: &span::Id); @@ -292,7 +292,7 @@ pub trait Subscriber: 'static { /// while `event` is called when a new event occurs. /// /// The provided `Event` struct contains any field values attached to the - /// event. The subscriber may pass a [visitor] to the `Event`'s + /// event. The collector may pass a [visitor] to the `Event`'s /// [`record` method] to record these values. /// /// [`Event`]: super::event::Event @@ -303,8 +303,8 @@ pub trait Subscriber: 'static { /// Records that a span has been entered. /// - /// When entering a span, this method is called to notify the subscriber - /// that the span has been entered. The subscriber is provided with the + /// When entering a span, this method is called to notify the collector + /// that the span has been entered. The collector is provided with the /// [span ID] of the entered span, and should update any internal state /// tracking the current span accordingly. /// @@ -313,8 +313,8 @@ pub trait Subscriber: 'static { /// Records that a span has been exited. /// - /// When exiting a span, this method is called to notify the subscriber - /// that the span has been exited. The subscriber is provided with the + /// When exiting a span, this method is called to notify the collector + /// that the span has been exited. The collector is provided with the /// [span ID] of the exited span, and should update any internal state /// tracking the current span accordingly. /// @@ -323,17 +323,17 @@ pub trait Subscriber: 'static { /// [span ID]: super::span::Id fn exit(&self, span: &span::Id); - /// Notifies the subscriber that a [span ID] has been cloned. + /// Notifies the collector that a [span ID] has been cloned. /// /// This function is guaranteed to only be called with span IDs that were - /// returned by this subscriber's `new_span` function. + /// returned by this collector's `new_span` function. /// /// Note that the default implementation of this function this is just the /// identity function, passing through the identifier. However, it can be /// used in conjunction with [`try_close`] to track the number of handles /// capable of `enter`ing a span. When all the handles have been dropped /// (i.e., `try_close` has been called one more time than `clone_span` for a - /// given ID), the subscriber may assume that the span will not be entered + /// given ID), the collector may assume that the span will not be entered /// again. It is then free to deallocate storage for data associated with /// that span, write data from that span to IO, and so on. /// @@ -342,39 +342,39 @@ pub trait Subscriber: 'static { /// what that means for the specified pointer. /// /// [span ID]: super::span::Id - /// [`try_close`]: Subscriber::try_close + /// [`try_close`]: Collect::try_close fn clone_span(&self, id: &span::Id) -> span::Id { id.clone() } /// **This method is deprecated.** /// - /// Using `drop_span` may result in subscribers composed using - /// `tracing-subscriber` crate's `Layer` trait from observing close events. + /// Using `drop_span` may result in collectors composed using + /// `tracing-subscriber` crate's `Subscriber` trait from observing close events. /// Use [`try_close`] instead. /// /// The default implementation of this function does nothing. /// - /// [`try_close`]: Subscriber::try_close - #[deprecated(since = "0.1.2", note = "use `Subscriber::try_close` instead")] + /// [`try_close`]: Collect::try_close + #[deprecated(since = "0.1.2", note = "use `Collector::try_close` instead")] fn drop_span(&self, _id: span::Id) {} - /// Notifies the subscriber that a [`span ID`] has been dropped, and returns + /// Notifies the collector that a [`span ID`] has been dropped, and returns /// `true` if there are now 0 IDs that refer to that span. /// /// Higher-level libraries providing functionality for composing multiple - /// subscriber implementations may use this return value to notify any - /// "layered" subscribers that this subscriber considers the span closed. + /// collector implementations may use this return value to notify any + /// "layered" collectors that this collector considers the span closed. /// - /// The default implementation of this method calls the subscriber's + /// The default implementation of this method calls the collector's /// [`drop_span`] method and returns `false`. This means that, unless the - /// subscriber overrides the default implementation, close notifications - /// will never be sent to any layered subscribers. In general, if the - /// subscriber tracks reference counts, this method should be implemented, + /// collector overrides the default implementation, close notifications + /// will never be sent to any layered collectors. In general, if the + /// collector tracks reference counts, this method should be implemented, /// rather than `drop_span`. /// /// This function is guaranteed to only be called with span IDs that were - /// returned by this subscriber's `new_span` function. + /// returned by this collector's `new_span` function. /// /// It's guaranteed that if this function has been called once more than the /// number of times `clone_span` was called with the same `id`, then no more @@ -382,7 +382,7 @@ pub trait Subscriber: 'static { /// can be used in conjunction with [`clone_span`] to track the number of /// handles capable of `enter`ing a span. When all the handles have been /// dropped (i.e., `try_close` has been called one more time than - /// `clone_span` for a given ID), the subscriber may assume that the span + /// `clone_span` for a given ID), the collector may assume that the span /// will not be entered again, and should return `true`. It is then free to /// deallocate storage for data associated with that span, write data from /// that span to IO, and so on. @@ -393,23 +393,23 @@ pub trait Subscriber: 'static { /// was dropped due to a thread unwinding. /// /// [span ID]: super::span::Id - /// [`clone_span`]: Subscriber::clone_span - /// [`drop_span`]: Subscriber::drop_span + /// [`clone_span`]: Collect::clone_span + /// [`drop_span`]: Collect::drop_span fn try_close(&self, id: span::Id) -> bool { #[allow(deprecated)] self.drop_span(id); false } - /// Returns a type representing this subscriber's view of the current span. + /// Returns a type representing this collector's view of the current span. /// - /// If subscribers track a current span, they should override this function + /// If collectors track a current span, they should override this function /// to return [`Current::new`] if the thread from which this method is /// called is inside a span, or [`Current::none`] if the thread is not /// inside a span. /// - /// By default, this returns a value indicating that the subscriber - /// does **not** track what span is current. If the subscriber does not + /// By default, this returns a value indicating that the collector + /// does **not** track what span is current. If the collector does not /// implement a current span, it should not override this method. /// /// [`Current::new`]: super::span::Current::new @@ -423,18 +423,18 @@ pub trait Subscriber: 'static { /// If `self` is the same type as the provided `TypeId`, returns an untyped /// `*const` pointer to that type. Otherwise, returns `None`. /// - /// If you wish to downcast a `Subscriber`, it is strongly advised to use + /// If you wish to downcast a `Collector`, it is strongly advised to use /// the safe API provided by [`downcast_ref`] instead. /// /// This API is required for `downcast_raw` to be a trait method; a method /// signature like [`downcast_ref`] (with a generic type parameter) is not - /// object-safe, and thus cannot be a trait method for `Subscriber`. This - /// means that if we only exposed `downcast_ref`, `Subscriber` + /// object-safe, and thus cannot be a trait method for `Collector`. This + /// means that if we only exposed `downcast_ref`, `Collector` /// implementations could not override the downcasting behavior /// - /// This method may be overridden by "fan out" or "chained" subscriber + /// This method may be overridden by "fan out" or "chained" collector /// implementations which consist of multiple composed types. Such - /// subscribers might allow `downcast_raw` by returning references to those + /// collectors might allow `downcast_raw` by returning references to those /// component if they contain components with the given `TypeId`. /// /// # Safety @@ -454,13 +454,13 @@ pub trait Subscriber: 'static { } } -impl dyn Subscriber { - /// Returns `true` if this `Subscriber` is the same type as `T`. +impl dyn Collect { + /// Returns `true` if this `Collector` is the same type as `T`. pub fn is(&self) -> bool { self.downcast_ref::().is_some() } - /// Returns some reference to this `Subscriber` value if it is of type `T`, + /// Returns some reference to this `Collector` value if it is of type `T`, /// or `None` if it isn't. pub fn downcast_ref(&self) -> Option<&T> { unsafe { @@ -474,13 +474,13 @@ impl dyn Subscriber { } } -/// Indicates a [`Subscriber`]'s interest in a particular callsite. +/// Indicates a [`Collect`]'s interest in a particular callsite. /// -/// `Subscriber`s return an `Interest` from their [`register_callsite`] methods +/// Collectors return an `Interest` from their [`register_callsite`] methods /// in order to determine whether that span should be enabled or disabled. /// -/// [`Subscriber`]: super::Subscriber -/// [`register_callsite`]: super::Subscriber::register_callsite +/// [`Collect`]: super::Collect +/// [`register_callsite`]: super::Collect::register_callsite #[derive(Clone, Debug)] pub struct Interest(InterestKind); @@ -492,53 +492,53 @@ enum InterestKind { } impl Interest { - /// Returns an `Interest` indicating that the subscriber is never interested + /// Returns an `Interest` indicating that the collector is never interested /// in being notified about a callsite. /// - /// If all active subscribers are `never()` interested in a callsite, it will - /// be completely disabled unless a new subscriber becomes active. + /// If all active collectors are `never()` interested in a callsite, it will + /// be completely disabled unless a new collector becomes active. #[inline] pub fn never() -> Self { Interest(InterestKind::Never) } - /// Returns an `Interest` indicating the subscriber is sometimes interested + /// Returns an `Interest` indicating the collector is sometimes interested /// in being notified about a callsite. /// - /// If all active subscribers are `sometimes` or `never` interested in a - /// callsite, the currently active subscriber will be asked to filter that + /// If all active collectors are `sometimes` or `never` interested in a + /// callsite, the currently active collector will be asked to filter that /// callsite every time it creates a span. This will be the case until a new - /// subscriber expresses that it is `always` interested in the callsite. + /// collector expresses that it is `always` interested in the callsite. #[inline] pub fn sometimes() -> Self { Interest(InterestKind::Sometimes) } - /// Returns an `Interest` indicating the subscriber is always interested in + /// Returns an `Interest` indicating the collector is always interested in /// being notified about a callsite. /// - /// If any subscriber expresses that it is `always()` interested in a given + /// If any collector expresses that it is `always()` interested in a given /// callsite, then the callsite will always be enabled. #[inline] pub fn always() -> Self { Interest(InterestKind::Always) } - /// Returns `true` if the subscriber is never interested in being notified + /// Returns `true` if the collector is never interested in being notified /// about this callsite. #[inline] pub fn is_never(&self) -> bool { matches!(self.0, InterestKind::Never) } - /// Returns `true` if the subscriber is sometimes interested in being notified + /// Returns `true` if the collector is sometimes interested in being notified /// about this callsite. #[inline] pub fn is_sometimes(&self) -> bool { matches!(self.0, InterestKind::Sometimes) } - /// Returns `true` if the subscriber is always interested in being notified + /// Returns `true` if the collector is always interested in being notified /// about this callsite. #[inline] pub fn is_always(&self) -> bool { @@ -549,9 +549,9 @@ impl Interest { /// /// If both interests are the same, this propagates that interest. /// Otherwise, if they differ, the result must always be - /// `Interest::sometimes` --- if the two subscribers differ in opinion, we - /// will have to ask the current subscriber what it thinks, no matter what. - // Only needed when combining interest from multiple subscribers. + /// `Interest::sometimes` --- if the two collectors differ in opinion, we + /// will have to ask the current collector what it thinks, no matter what. + // Only needed when combining interest from multiple collectors. #[cfg(feature = "std")] pub(crate) fn and(self, rhs: Interest) -> Self { if self.0 == rhs.0 { diff --git a/tracing-core/src/dispatcher.rs b/tracing-core/src/dispatch.rs similarity index 72% rename from tracing-core/src/dispatcher.rs rename to tracing-core/src/dispatch.rs index 086e53d40b..cc526daae4 100644 --- a/tracing-core/src/dispatcher.rs +++ b/tracing-core/src/dispatch.rs @@ -1,34 +1,34 @@ -//! Dispatches trace events to [`Subscriber`]s. +//! Dispatches trace events to [`Collect`]s. //! //! The _dispatcher_ is the component of the tracing system which is responsible //! for forwarding trace data from the instrumentation points that generate it -//! to the subscriber that collects it. +//! to the collector that collects it. //! //! # Using the Trace Dispatcher //! -//! Every thread in a program using `tracing` has a _default subscriber_. When +//! Every thread in a program using `tracing` has a _default collector_. When //! events occur, or spans are created, they are dispatched to the thread's -//! current subscriber. +//! current collector. //! -//! ## Setting the Default Subscriber +//! ## Setting the Default Collector //! -//! By default, the current subscriber is an empty implementation that does -//! nothing. To use a subscriber implementation, it must be set as the default. +//! By default, the current collector is an empty implementation that does +//! nothing. To use a collector implementation, it must be set as the default. //! There are two methods for doing so: [`with_default`] and -//! [`set_global_default`]. `with_default` sets the default subscriber for the -//! duration of a scope, while `set_global_default` sets a default subscriber +//! [`set_global_default`]. `with_default` sets the default collector for the +//! duration of a scope, while `set_global_default` sets a default collector //! for the entire process. //! -//! To use either of these functions, we must first wrap our subscriber in a -//! [`Dispatch`], a cloneable, type-erased reference to a subscriber. For +//! To use either of these functions, we must first wrap our collector in a +//! [`Dispatch`], a cloneable, type-erased reference to a collector. For //! example: //! ```rust -//! # pub struct FooSubscriber; +//! # pub struct FooCollector; //! # use tracing_core::{ -//! # dispatcher, Event, Metadata, +//! # dispatch, Event, Metadata, //! # span::{Attributes, Id, Record} //! # }; -//! # impl tracing_core::Subscriber for FooSubscriber { +//! # impl tracing_core::Collect for FooCollector { //! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } //! # fn record(&self, _: &Id, _: &Record) {} //! # fn event(&self, _: &Event) {} @@ -37,24 +37,24 @@ //! # fn enter(&self, _: &Id) {} //! # fn exit(&self, _: &Id) {} //! # } -//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } } +//! # impl FooCollector { fn new() -> Self { FooCollector } } //! # #[cfg(feature = "alloc")] -//! use dispatcher::Dispatch; +//! use dispatch::Dispatch; //! //! # #[cfg(feature = "alloc")] -//! let my_subscriber = FooSubscriber::new(); +//! let my_collector = FooCollector::new(); //! # #[cfg(feature = "alloc")] -//! let my_dispatch = Dispatch::new(my_subscriber); +//! let my_dispatch = Dispatch::new(my_collector); //! ``` //! Then, we can use [`with_default`] to set our `Dispatch` as the default for //! the duration of a block: //! ```rust -//! # pub struct FooSubscriber; +//! # pub struct FooCollector; //! # use tracing_core::{ -//! # dispatcher, Event, Metadata, +//! # dispatch, Event, Metadata, //! # span::{Attributes, Id, Record} //! # }; -//! # impl tracing_core::Subscriber for FooSubscriber { +//! # impl tracing_core::Collect for FooCollector { //! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } //! # fn record(&self, _: &Id, _: &Record) {} //! # fn event(&self, _: &Event) {} @@ -63,34 +63,34 @@ //! # fn enter(&self, _: &Id) {} //! # fn exit(&self, _: &Id) {} //! # } -//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } } -//! # let _my_subscriber = FooSubscriber::new(); +//! # impl FooCollector { fn new() -> Self { FooCollector } } +//! # let _my_collector = FooCollector::new(); //! # #[cfg(feature = "std")] -//! # let my_dispatch = dispatcher::Dispatch::new(_my_subscriber); -//! // no default subscriber +//! # let my_dispatch = dispatch::Dispatch::new(_my_collector); +//! // no default collector //! //! # #[cfg(feature = "std")] -//! dispatcher::with_default(&my_dispatch, || { -//! // my_subscriber is the default +//! dispatch::with_default(&my_dispatch, || { +//! // my_collector is the default //! }); //! -//! // no default subscriber again +//! // no default collector again //! ``` //! It's important to note that `with_default` will not propagate the current -//! thread's default subscriber to any threads spawned within the `with_default` -//! block. To propagate the default subscriber to new threads, either use +//! thread's default collector to any threads spawned within the `with_default` +//! block. To propagate the default collector to new threads, either use //! `with_default` from the new thread, or use `set_global_default`. //! //! As an alternative to `with_default`, we can use [`set_global_default`] to //! set a `Dispatch` as the default for all threads, for the lifetime of the //! program. For example: //! ```rust -//! # pub struct FooSubscriber; +//! # pub struct FooCollector; //! # use tracing_core::{ -//! # dispatcher, Event, Metadata, +//! # dispatch, Event, Metadata, //! # span::{Attributes, Id, Record} //! # }; -//! # impl tracing_core::Subscriber for FooSubscriber { +//! # impl tracing_core::Collect for FooCollector { //! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } //! # fn record(&self, _: &Id, _: &Record) {} //! # fn event(&self, _: &Event) {} @@ -99,20 +99,20 @@ //! # fn enter(&self, _: &Id) {} //! # fn exit(&self, _: &Id) {} //! # } -//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } } +//! # impl FooCollector { fn new() -> Self { FooCollector } } //! # #[cfg(feature = "std")] -//! # let my_subscriber = FooSubscriber::new(); +//! # let my_collector = FooCollector::new(); //! # #[cfg(feature = "std")] -//! # let my_dispatch = dispatcher::Dispatch::new(my_subscriber); -//! // no default subscriber +//! # let my_dispatch = dispatch::Dispatch::new(my_collector); +//! // no default collector //! //! # #[cfg(feature = "std")] -//! dispatcher::set_global_default(my_dispatch) +//! dispatch::set_global_default(my_dispatch) //! // `set_global_default` will return an error if the global default -//! // subscriber has already been set. +//! // collector has already been set. //! .expect("global default was already set!"); //! -//! // `my_subscriber` is now the default +//! // `my_collector` is now the default //! ``` //! //!
@@ -126,16 +126,15 @@ //! //!
//! -//! ## Accessing the Default Subscriber +//! ## Accessing the Default Collector //! -//! A thread's current default subscriber can be accessed using the +//! A thread's current default collector can be accessed using the //! [`get_default`] function, which executes a closure with a reference to the //! currently default `Dispatch`. This is used primarily by `tracing` //! instrumentation. use crate::{ - span, - subscriber::{self, Subscriber}, - Event, LevelFilter, Metadata, + collect::{self, Collect}, + span, Event, LevelFilter, Metadata, }; use core::{ @@ -157,20 +156,20 @@ use alloc::sync::Arc; #[cfg(feature = "alloc")] use core::ops::Deref; -/// `Dispatch` trace data to a [`Subscriber`]. +/// `Dispatch` trace data to a [`Collect`]. #[derive(Clone)] pub struct Dispatch { #[cfg(feature = "alloc")] - subscriber: Kind>, + collector: Kind>, #[cfg(not(feature = "alloc"))] - subscriber: &'static (dyn Subscriber + Send + Sync), + collector: &'static (dyn Collect + Send + Sync), } #[cfg(feature = "alloc")] #[derive(Clone)] enum Kind { - Global(&'static (dyn Subscriber + Send + Sync)), + Global(&'static (dyn Collect + Send + Sync)), Scoped(T), } @@ -194,17 +193,17 @@ const INITIALIZED: usize = 2; static mut GLOBAL_DISPATCH: Dispatch = Dispatch { #[cfg(feature = "alloc")] - subscriber: Kind::Global(&NO_SUBSCRIBER), + collector: Kind::Global(&NO_COLLECTOR), #[cfg(not(feature = "alloc"))] - subscriber: &NO_SUBSCRIBER, + collector: &NO_COLLECTOR, }; static NONE: Dispatch = Dispatch { #[cfg(feature = "alloc")] - subscriber: Kind::Global(&NO_SUBSCRIBER), + collector: Kind::Global(&NO_COLLECTOR), #[cfg(not(feature = "alloc"))] - subscriber: &NO_SUBSCRIBER, + collector: &NO_COLLECTOR, }; -static NO_SUBSCRIBER: NoSubscriber = NoSubscriber; +static NO_COLLECTOR: NoCollector = NoCollector; /// The dispatch state of a thread. #[cfg(feature = "std")] @@ -221,7 +220,7 @@ struct State { can_enter: Cell, } -/// While this guard is active, additional calls to subscriber functions on +/// While this guard is active, additional calls to collector functions on /// the default dispatcher will not be able to access the dispatch context. /// Dropping the guard will allow the dispatch context to be re-entered. #[cfg(feature = "std")] @@ -252,7 +251,6 @@ pub struct DefaultGuard(Option); /// /// /// [span]: super::span -/// [`Subscriber`]: super::subscriber::Subscriber /// [`Event`]: super::event::Event #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] @@ -301,33 +299,32 @@ pub fn set_default(dispatcher: &Dispatch) -> DefaultGuard { ///
 /// Warning: In general, libraries should not call
 /// set_global_default()! Doing so will cause conflicts when
-/// executables that depend on the library try to set the default later.
+/// executables that depend on the library try to set the default collector later.
 /// 
/// /// [span]: super::span -/// [`Subscriber`]: super::subscriber::Subscriber /// [`Event`]: super::event::Event pub fn set_global_default(dispatcher: Dispatch) -> Result<(), SetGlobalDefaultError> { if GLOBAL_INIT.compare_and_swap(UNINITIALIZED, INITIALIZING, Ordering::SeqCst) == UNINITIALIZED { #[cfg(feature = "alloc")] - let subscriber = { - let subscriber = match dispatcher.subscriber { + let collector = { + let collector = match dispatcher.collector { Kind::Global(s) => s, Kind::Scoped(s) => unsafe { - // safety: this leaks the subscriber onto the heap. the + // safety: this leaks the collector onto the heap. the // reference count will always be at least 1. &*Arc::into_raw(s) }, }; - Kind::Global(subscriber) + Kind::Global(collector) }; #[cfg(not(feature = "alloc"))] - let subscriber = dispatcher.subscriber; + let collector = dispatcher.collector; unsafe { - GLOBAL_DISPATCH = Dispatch { subscriber }; + GLOBAL_DISPATCH = Dispatch { collector }; } GLOBAL_INIT.store(INITIALIZED, Ordering::SeqCst); EXISTS.store(true, Ordering::Release); @@ -369,7 +366,7 @@ impl error::Error for SetGlobalDefaultError {} /// called while inside of another `get_default`, that closure will be provided /// with `Dispatch::none` rather than the previously set dispatcher. /// -/// [dispatcher]: super::dispatcher::Dispatch +/// [dispatcher]: super::dispatch::Dispatch #[cfg(feature = "std")] pub fn get_default(mut f: F) -> T where @@ -381,7 +378,7 @@ where return f(get_global()); } - // While this guard is active, additional calls to subscriber functions on + // While this guard is active, additional calls to collector functions on // the default dispatcher will not be able to access the dispatch context. // Dropping the guard will allow the dispatch context to be re-entered. struct Entered<'a>(&'a Cell); @@ -399,7 +396,7 @@ where let mut default = state.default.borrow_mut(); - if default.is::() { + if default.is::() { // don't redo this call on the next check *default = get_global().clone(); } @@ -463,7 +460,7 @@ pub(crate) fn get_global() -> &'static Dispatch { } #[cfg(feature = "std")] -pub(crate) struct Registrar(Kind>); +pub(crate) struct Registrar(Kind>); impl Dispatch { /// Returns a new `Dispatch` that discards events and spans. @@ -471,43 +468,43 @@ impl Dispatch { pub fn none() -> Self { Dispatch { #[cfg(feature = "alloc")] - subscriber: Kind::Global(&NO_SUBSCRIBER), + collector: Kind::Global(&NO_COLLECTOR), #[cfg(not(feature = "alloc"))] - subscriber: &NO_SUBSCRIBER, + collector: &NO_COLLECTOR, } } - /// Returns a `Dispatch` that forwards to the given [`Subscriber`]. + /// Returns a `Dispatch` that forwards to the given [`Collect`]. /// - /// [`Subscriber`]: super::subscriber::Subscriber + /// [`Collect`]: super::collect::Collect #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] - pub fn new(subscriber: S) -> Self + pub fn new(collector: S) -> Self where - S: Subscriber + Send + Sync + 'static, + S: Collect + Send + Sync + 'static, { let me = Dispatch { - subscriber: Kind::Scoped(Arc::new(subscriber)), + collector: Kind::Scoped(Arc::new(collector)), }; crate::callsite::register_dispatch(&me); me } - /// Returns a `Dispatch` that forwards to the given static [`Subscriber`]. + /// Returns a `Dispatch` that forwards to the given static [collector]. /// /// Unlike [`Dispatch::new`], this function is always available on all /// platforms, even when the `std` or `alloc` features are disabled. /// - /// In order to use `from_static`, the `Subscriber` itself must be stored in + /// In order to use `from_static`, the `Collector` itself must be stored in /// a static. For example: /// /// ```rust - /// struct MySubscriber { + /// struct MyCollector { /// // ... /// } /// /// # use tracing_core::{span::{Id, Attributes, Record}, Event, Metadata}; - /// impl tracing_core::Subscriber for MySubscriber { + /// impl tracing_core::Collect for MyCollector { /// // ... /// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } /// # fn record(&self, _: &Id, _: &Record) {} @@ -518,21 +515,21 @@ impl Dispatch { /// # fn exit(&self, _: &Id) {} /// } /// - /// static SUBSCRIBER: MySubscriber = MySubscriber { + /// static COLLECTOR: MyCollector = MyCollector { /// // ... /// }; /// /// fn main() { - /// use tracing_core::dispatcher::{self, Dispatch}; + /// use tracing_core::dispatch::{self, Dispatch}; /// - /// let dispatch = Dispatch::from_static(&SUBSCRIBER); + /// let dispatch = Dispatch::from_static(&COLLECTOR); /// - /// dispatcher::set_global_default(dispatch) - /// .expect("no global default subscriber should have been set previously!"); + /// dispatch::set_global_default(dispatch) + /// .expect("no global default collector should have been set previously!"); /// } /// ``` /// - /// Constructing the subscriber in a static initializer may make some forms + /// Constructing the collector in a static initializer may make some forms /// of runtime configuration more challenging. If this is the case, users /// with access to `liballoc` or the Rust standard library are encouraged to /// use [`Dispatch::new`] rather than `from_static`. `no_std` users who @@ -540,23 +537,23 @@ impl Dispatch { /// the [`lazy_static`] crate, or another library which allows lazy /// initialization of statics. /// - /// [`Subscriber`]: super::subscriber::Subscriber + /// [collector]: super::collect::Collect /// [`Dispatch::new`]: Dispatch::new /// [`lazy_static`]: https://crates.io/crates/lazy_static - pub fn from_static(subscriber: &'static (dyn Subscriber + Send + Sync)) -> Self { + pub fn from_static(collector: &'static (dyn Collect + Send + Sync)) -> Self { #[cfg(feature = "alloc")] let me = Self { - subscriber: Kind::Global(subscriber), + collector: Kind::Global(collector), }; #[cfg(not(feature = "alloc"))] - let me = Self { subscriber }; + let me = Self { collector }; crate::callsite::register_dispatch(&me); me } #[cfg(feature = "std")] pub(crate) fn registrar(&self) -> Registrar { - Registrar(match self.subscriber { + Registrar(match self.collector { Kind::Scoped(ref s) => Kind::Scoped(Arc::downgrade(s)), Kind::Global(s) => Kind::Global(s), }) @@ -564,8 +561,8 @@ impl Dispatch { #[inline(always)] #[cfg(feature = "alloc")] - fn subscriber(&self) -> &(dyn Subscriber + Send + Sync) { - match self.subscriber { + fn collector(&self) -> &(dyn Collect + Send + Sync) { + match self.collector { Kind::Scoped(ref s) => Arc::deref(s), Kind::Global(s) => s, } @@ -573,156 +570,157 @@ impl Dispatch { #[inline(always)] #[cfg(not(feature = "alloc"))] - fn subscriber(&self) -> &(dyn Subscriber + Send + Sync) { - self.subscriber + fn collector(&self) -> &(dyn Collect + Send + Sync) { + self.collector } - /// Registers a new callsite with this subscriber, returning whether or not - /// the subscriber is interested in being notified about the callsite. + /// Registers a new callsite with this collector, returning whether or not + /// the collector is interested in being notified about the callsite. /// - /// This calls the [`register_callsite`] function on the [`Subscriber`] + /// This calls the [`register_callsite`] function on the [`Collect`] /// that this `Dispatch` forwards to. /// - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`register_callsite`]: super::subscriber::Subscriber::register_callsite + /// [`Collect`]: super::collect::Collect + /// [`register_callsite`]: super::collect::Collect::register_callsite #[inline] - pub fn register_callsite(&self, metadata: &'static Metadata<'static>) -> subscriber::Interest { - self.subscriber().register_callsite(metadata) + pub fn register_callsite(&self, metadata: &'static Metadata<'static>) -> collect::Interest { + self.collector().register_callsite(metadata) } - /// Returns the highest [verbosity level][level] that this [`Subscriber`] will - /// enable, or `None`, if the subscriber does not implement level-based + /// Returns the highest [verbosity level][level] that this [collector] will + /// enable, or `None`, if the collector does not implement level-based /// filtering or chooses not to implement this method. /// - /// This calls the [`max_level_hint`] function on the [`Subscriber`] + /// This calls the [`max_level_hint`] function on the [`Collect`] /// that this `Dispatch` forwards to. /// /// [level]: super::Level - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`register_callsite`]: super::subscriber::Subscriber::max_level_hint + /// [collector]: super::collect::Collect + /// [`Collect`]: super::collect::Collect + /// [`register_callsite`]: super::collect::Collect::max_level_hint // TODO(eliza): consider making this a public API? #[inline] pub(crate) fn max_level_hint(&self) -> Option { - self.subscriber().max_level_hint() + self.collector().max_level_hint() } /// Record the construction of a new span, returning a new [ID] for the /// span being constructed. /// - /// This calls the [`new_span`] function on the [`Subscriber`] that this + /// This calls the [`new_span`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// /// [ID]: super::span::Id - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`new_span`]: super::subscriber::Subscriber::new_span + /// [`Collect`]: super::collect::Collect + /// [`new_span`]: super::collect::Collect::new_span #[inline] pub fn new_span(&self, span: &span::Attributes<'_>) -> span::Id { - self.subscriber().new_span(span) + self.collector().new_span(span) } /// Record a set of values on a span. /// - /// This calls the [`record`] function on the [`Subscriber`] that this + /// This calls the [`record`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`record`]: super::subscriber::Subscriber::record + /// [`Collect`]: super::collect::Collect + /// [`record`]: super::collect::Collect::record #[inline] pub fn record(&self, span: &span::Id, values: &span::Record<'_>) { - self.subscriber().record(span, values) + self.collector().record(span, values) } /// Adds an indication that `span` follows from the span with the id /// `follows`. /// - /// This calls the [`record_follows_from`] function on the [`Subscriber`] + /// This calls the [`record_follows_from`] function on the [`Collect`] /// that this `Dispatch` forwards to. /// - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`record_follows_from`]: super::subscriber::Subscriber::record_follows_from + /// [`Collect`]: super::collect::Collect + /// [`record_follows_from`]: super::collect::Collect::record_follows_from #[inline] pub fn record_follows_from(&self, span: &span::Id, follows: &span::Id) { - self.subscriber().record_follows_from(span, follows) + self.collector().record_follows_from(span, follows) } /// Returns true if a span with the specified [metadata] would be /// recorded. /// - /// This calls the [`enabled`] function on the [`Subscriber`] that this + /// This calls the [`enabled`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// /// [metadata]: super::metadata::Metadata - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`enabled`]: super::subscriber::Subscriber::enabled + /// [`Collect`]: super::collect::Collect + /// [`enabled`]: super::collect::Collect::enabled #[inline] pub fn enabled(&self, metadata: &Metadata<'_>) -> bool { - self.subscriber().enabled(metadata) + self.collector().enabled(metadata) } /// Records that an [`Event`] has occurred. /// - /// This calls the [`event`] function on the [`Subscriber`] that this + /// This calls the [`event`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// /// [`Event`]: super::event::Event - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`event`]: super::subscriber::Subscriber::event + /// [`Collect`]: super::collect::Collect + /// [`event`]: super::collect::Collect::event #[inline] pub fn event(&self, event: &Event<'_>) { - self.subscriber().event(event) + self.collector().event(event) } /// Records that a span has been can_enter. /// - /// This calls the [`enter`] function on the [`Subscriber`] that this + /// This calls the [`enter`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`enter`]: super::subscriber::Subscriber::enter + /// [`Collect`]: super::collect::Collect + /// [`enter`]: super::collect::Collect::enter #[inline] pub fn enter(&self, span: &span::Id) { - self.subscriber().enter(span); + self.collector().enter(span); } /// Records that a span has been exited. /// - /// This calls the [`exit`] function on the [`Subscriber`] that this + /// This calls the [`exit`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`exit`]: super::subscriber::Subscriber::exit + /// [`Collect`]: super::collect::Collect + /// [`exit`]: super::collect::Collect::exit #[inline] pub fn exit(&self, span: &span::Id) { - self.subscriber().exit(span); + self.collector().exit(span); } - /// Notifies the subscriber that a [span ID] has been cloned. + /// Notifies the [collector] that a [span ID] has been cloned. /// /// This function must only be called with span IDs that were returned by /// this `Dispatch`'s [`new_span`] function. The `tracing` crate upholds /// this guarantee and any other libraries implementing instrumentation APIs /// must as well. /// - /// This calls the [`clone_span`] function on the `Subscriber` that this + /// This calls the [`clone_span`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// /// [span ID]: super::span::Id - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`clone_span`]: super::subscriber::Subscriber::clone_span - /// [`new_span`]: super::subscriber::Subscriber::new_span + /// [collector]: super::collect::Collect + /// [`clone_span`]: super::collect::Collect::clone_span + /// [`new_span`]: super::collect::Collect::new_span #[inline] pub fn clone_span(&self, id: &span::Id) -> span::Id { - self.subscriber().clone_span(&id) + self.collector().clone_span(&id) } - /// Notifies the subscriber that a [span ID] has been dropped. + /// Notifies the collector that a [span ID] has been dropped. /// /// This function must only be called with span IDs that were returned by /// this `Dispatch`'s [`new_span`] function. The `tracing` crate upholds /// this guarantee and any other libraries implementing instrumentation APIs /// must as well. /// - /// This calls the [`drop_span`] function on the [`Subscriber`] that this + /// This calls the [`drop_span`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// ///
@@ -736,18 +734,18 @@ impl Dispatch { ///
/// /// [span ID]: super::span::Id - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`drop_span`]: super::subscriber::Subscriber::drop_span - /// [`new_span`]: super::subscriber::Subscriber::new_span + /// [`Collect`]: super::collect::Collect + /// [`drop_span`]: super::collect::Collect::drop_span + /// [`new_span`]: super::collect::Collect::new_span /// [`try_close`]: Self::try_close #[inline] #[deprecated(since = "0.1.2", note = "use `Dispatch::try_close` instead")] pub fn drop_span(&self, id: span::Id) { #[allow(deprecated)] - self.subscriber().drop_span(id); + self.collector().drop_span(id); } - /// Notifies the subscriber that a [span ID] has been dropped, and returns + /// Notifies the collector that a [span ID] has been dropped, and returns /// `true` if there are now 0 IDs referring to that span. /// /// This function must only be called with span IDs that were returned by @@ -755,41 +753,44 @@ impl Dispatch { /// this guarantee and any other libraries implementing instrumentation APIs /// must as well. /// - /// This calls the [`try_close`] function on the [`Subscriber`] that this - /// `Dispatch` forwards to. + /// This calls the [`try_close`] function on the [`Collect`] trait + /// that this `Dispatch` forwards to. /// /// [span ID]: super::span::Id - /// [`Subscriber`]: super::subscriber::Subscriber - /// [`try_close`]: super::subscriber::Subscriber::try_close - /// [`new_span`]: super::subscriber::Subscriber::new_span + /// [`Collect`]: super::collect::Collect + /// [`try_close`]: super::collect::Collect::try_close + /// [`new_span`]: super::collect::Collect::new_span #[inline] pub fn try_close(&self, id: span::Id) -> bool { - self.subscriber().try_close(id) + self.collector().try_close(id) } - /// Returns a type representing this subscriber's view of the current span. + /// Returns a type representing this collector's view of the current span. /// - /// This calls the [`current`] function on the `Subscriber` that this + /// This calls the [`current`] function on the [`Collect`] that this /// `Dispatch` forwards to. /// - /// [`current`]: super::subscriber::Subscriber::current_span + /// [`Collect`]: super::collect::Collect + /// [`current`]: super::collect::Collect::current_span #[inline] pub fn current_span(&self) -> span::Current { - self.subscriber().current_span() + self.collector().current_span() } - /// Returns `true` if this `Dispatch` forwards to a `Subscriber` of type + /// Returns `true` if this `Dispatch` forwards to a collector of type /// `T`. #[inline] pub fn is(&self) -> bool { - Subscriber::is::(&*self.subscriber()) + Collect::is::(&*self.collector()) } - /// Returns some reference to the `Subscriber` this `Dispatch` forwards to + /// Returns some reference to the [`Collect`] this `Dispatch` forwards to /// if it is of type `T`, or `None` if it isn't. + /// + /// [`Collect`]: super::collect::Collect #[inline] pub fn downcast_ref(&self) -> Option<&T> { - Subscriber::downcast_ref(&*self.subscriber()) + Collect::downcast_ref(&*self.collector()) } } @@ -809,19 +810,19 @@ impl fmt::Debug for Dispatch { #[cfg(feature = "std")] impl From for Dispatch where - S: Subscriber + Send + Sync + 'static, + S: Collect + Send + Sync + 'static, { #[inline] - fn from(subscriber: S) -> Self { - Dispatch::new(subscriber) + fn from(collector: S) -> Self { + Dispatch::new(collector) } } -struct NoSubscriber; -impl Subscriber for NoSubscriber { +struct NoCollector; +impl Collect for NoCollector { #[inline] - fn register_callsite(&self, _: &'static Metadata<'static>) -> subscriber::Interest { - subscriber::Interest::never() + fn register_callsite(&self, _: &'static Metadata<'static>) -> collect::Interest { + collect::Interest::never() } fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { @@ -848,10 +849,10 @@ impl Registrar { pub(crate) fn upgrade(&self) -> Option { match self.0 { Kind::Global(s) => Some(Dispatch { - subscriber: Kind::Global(s), + collector: Kind::Global(s), }), Kind::Scoped(ref s) => s.upgrade().map(|s| Dispatch { - subscriber: Kind::Scoped(s), + collector: Kind::Scoped(s), }), } } @@ -897,7 +898,7 @@ impl<'a> Entered<'a> { fn current(&self) -> RefMut<'a, Dispatch> { let mut default = self.0.default.borrow_mut(); - if default.is::() { + if default.is::() { // don't redo this call on the next check *default = get_global().clone(); } @@ -924,7 +925,7 @@ impl Drop for DefaultGuard { if let Some(dispatch) = self.0.take() { // Replace the dispatcher and then drop the old one outside // of the thread-local context. Dropping the dispatch may - // lead to the drop of a subscriber which, in the process, + // lead to the drop of a collector which, in the process, // could then also attempt to access the same thread local // state -- causing a clash. let prev = CURRENT_STATE.try_with(|state| state.default.replace(dispatch)); @@ -939,20 +940,20 @@ mod test { use super::*; use crate::{ callsite::Callsite, + collect::Interest, metadata::{Kind, Level, Metadata}, - subscriber::Interest, }; #[test] fn dispatch_is() { - let dispatcher = Dispatch::from_static(&NO_SUBSCRIBER); - assert!(dispatcher.is::()); + let dispatcher = Dispatch::from_static(&NO_COLLECTOR); + assert!(dispatcher.is::()); } #[test] fn dispatch_downcasts() { - let dispatcher = Dispatch::from_static(&NO_SUBSCRIBER); - assert!(dispatcher.downcast_ref::().is_some()); + let dispatcher = Dispatch::from_static(&NoCollector); + assert!(dispatcher.downcast_ref::().is_some()); } struct TestCallsite; @@ -976,10 +977,10 @@ mod test { #[test] #[cfg(feature = "std")] fn events_dont_infinite_loop() { - // This test ensures that an event triggered within a subscriber + // This test ensures that an event triggered within a collector // won't cause an infinite loop of events. - struct TestSubscriber; - impl Subscriber for TestSubscriber { + struct TestCollector; + impl Collect for TestCollector { fn enabled(&self, _: &Metadata<'_>) -> bool { true } @@ -1007,7 +1008,7 @@ mod test { fn exit(&self, _: &span::Id) {} } - with_default(&Dispatch::new(TestSubscriber), || { + with_default(&Dispatch::new(TestCollector), || { Event::dispatch(&TEST_META, &TEST_META.fields().value_set(&[])) }) } @@ -1015,7 +1016,7 @@ mod test { #[test] #[cfg(feature = "std")] fn spans_dont_infinite_loop() { - // This test ensures that a span created within a subscriber + // This test ensures that a span created within a collector // won't cause an infinite loop of new spans. fn mk_span() { @@ -1027,8 +1028,8 @@ mod test { }); } - struct TestSubscriber; - impl Subscriber for TestSubscriber { + struct TestCollector; + impl Collect for TestCollector { fn enabled(&self, _: &Metadata<'_>) -> bool { true } @@ -1055,20 +1056,20 @@ mod test { fn exit(&self, _: &span::Id) {} } - with_default(&Dispatch::new(TestSubscriber), mk_span) + with_default(&Dispatch::new(TestCollector), mk_span) } #[test] - fn default_no_subscriber() { + fn default_no_collector() { let default_dispatcher = Dispatch::default(); - assert!(default_dispatcher.is::()); + assert!(default_dispatcher.is::()); } #[cfg(feature = "std")] #[test] fn default_dispatch() { - struct TestSubscriber; - impl Subscriber for TestSubscriber { + struct TestCollector; + impl Collect for TestCollector { fn enabled(&self, _: &Metadata<'_>) -> bool { true } @@ -1087,12 +1088,12 @@ mod test { fn exit(&self, _: &span::Id) {} } - let guard = set_default(&Dispatch::new(TestSubscriber)); + let guard = set_default(&Dispatch::new(TestCollector)); let default_dispatcher = Dispatch::default(); - assert!(default_dispatcher.is::()); + assert!(default_dispatcher.is::()); drop(guard); let default_dispatcher = Dispatch::default(); - assert!(default_dispatcher.is::()); + assert!(default_dispatcher.is::()); } } diff --git a/tracing-core/src/event.rs b/tracing-core/src/event.rs index b823fa8722..0d68d3a962 100644 --- a/tracing-core/src/event.rs +++ b/tracing-core/src/event.rs @@ -28,10 +28,10 @@ pub struct Event<'a> { impl<'a> Event<'a> { /// Constructs a new `Event` with the specified metadata and set of values, - /// and observes it with the current subscriber. + /// and observes it with the current collector. pub fn dispatch(metadata: &'static Metadata<'static>, fields: &'a field::ValueSet<'_>) { let event = Event::new(metadata, fields); - crate::dispatcher::get_default(|current| { + crate::dispatch::get_default(|current| { current.event(&event); }); } @@ -67,14 +67,14 @@ impl<'a> Event<'a> { } /// Constructs a new `Event` with the specified metadata and set of values, - /// and observes it with the current subscriber and an explicit parent. + /// and observes it with the current collector and an explicit parent. pub fn child_of( parent: impl Into>, metadata: &'static Metadata<'static>, fields: &'a field::ValueSet<'_>, ) { let event = Self::new_child_of(parent, metadata, fields); - crate::dispatcher::get_default(|current| { + crate::dispatch::get_default(|current| { current.event(&event); }); } diff --git a/tracing-core/src/field.rs b/tracing-core/src/field.rs index 4cbdcaa3d7..6cde32d068 100644 --- a/tracing-core/src/field.rs +++ b/tracing-core/src/field.rs @@ -4,20 +4,20 @@ //! 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 +//! # `Value`s and `Collect`s //! -//! `Subscriber`s consume `Value`s as fields attached to [span]s or [`Event`]s. +//! Collectors 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 +//! When a span is created, it provides [`Attributes`] to the collector's //! [`new_span`] method, containing any fields whose values were provided when -//! the span was created; and may call the `Subscriber`'s [`record`] method +//! the span was created; and may call the collector'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 +//! Similarly, the [`Event`] type passed to the collector'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`, `bool`, and `&str`) or using a `fmt::Display` or `fmt::Debug` -//! implementation. `Subscriber`s are provided these primitive value types as +//! implementation. Collectors are provided these primitive value types as //! `dyn Value` trait objects. //! //! These trait objects can be formatted using `fmt::Debug`, but may also be @@ -32,9 +32,9 @@ //! [`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 +//! [`new_span`]: super::collect::Collect::new_span +//! [`record`]: super::collect::Collect::record +//! [`event`]: super::collect::Collect::event use crate::callsite; use core::{ borrow::Borrow, @@ -52,7 +52,7 @@ use self::private::ValidLen; /// 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_, +/// collector 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)] pub struct Field { @@ -97,7 +97,7 @@ pub struct Iter { /// [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 +/// When a [`Collect`] 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 @@ -177,9 +177,9 @@ pub struct Iter { /// /// /// [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 +/// [`Collect`]: super::collect::Collect +/// [records an `Event`]: super::collect::Collect::event +/// [set of `Value`s added to a `Span`]: super::collect::Collect::record /// [`Event`]: super::event::Event pub trait Visit { /// Visit a signed 64-bit integer value. @@ -443,7 +443,7 @@ impl fmt::Debug for dyn Value { struct NullCallsite; static NULL_CALLSITE: NullCallsite = NullCallsite; impl crate::callsite::Callsite for NullCallsite { - fn set_interest(&self, _: crate::subscriber::Interest) { + fn set_interest(&self, _: crate::collect::Interest) { unreachable!("you somehow managed to register the null callsite?") } @@ -841,7 +841,7 @@ mod test { }; impl crate::callsite::Callsite for TestCallsite1 { - fn set_interest(&self, _: crate::subscriber::Interest) { + fn set_interest(&self, _: crate::collect::Interest) { unimplemented!() } @@ -862,7 +862,7 @@ mod test { }; impl crate::callsite::Callsite for TestCallsite2 { - fn set_interest(&self, _: crate::subscriber::Interest) { + fn set_interest(&self, _: crate::collect::Interest) { unimplemented!() } diff --git a/tracing-core/src/lib.rs b/tracing-core/src/lib.rs index ba3ce974f1..86bc06673c 100644 --- a/tracing-core/src/lib.rs +++ b/tracing-core/src/lib.rs @@ -10,7 +10,7 @@ //! //! * [`Event`] represents a single event within a trace. //! -//! * [`Subscriber`], the trait implemented to collect trace data. +//! * [`Collect`], the trait implemented to collect trace data. //! //! * [`Metadata`] and [`Callsite`] provide information describing spans and //! `Event`s. @@ -18,7 +18,7 @@ //! * [`Field`], [`FieldSet`], [`Value`], and [`ValueSet`] represent the //! structured data attached to a span. //! -//! * [`Dispatch`] allows spans and events to be dispatched to `Subscriber`s. +//! * [`Dispatch`] allows spans and events to be dispatched to collectors. //! //! In addition, it defines the global callsite registry and per-thread current //! dispatcher which other components of the tracing system rely on. @@ -34,14 +34,14 @@ //! fully-featured API. However, this crate's API will change very infrequently, //! so it may be used when dependencies must be very stable. //! -//! `Subscriber` implementations may depend on `tracing-core` rather than +//! Collector implementations may depend on `tracing-core` rather than //! `tracing`, as the additional APIs provided by `tracing` are primarily useful //! for instrumenting libraries and applications, and are generally not -//! necessary for `Subscriber` implementations. +//! necessary for collector implementations. //! //! The [`tokio-rs/tracing`] repository contains less stable crates designed to //! be used with the `tracing` ecosystem. It includes a collection of -//! `Subscriber` implementations, as well as utility and adapter crates. +//! collector implementations, as well as utility and adapter crates. //! //! ### `no_std` Support //! @@ -72,9 +72,9 @@ //! require a global memory allocator. //! //! The "alloc" feature is required to enable the [`Dispatch::new`] function, -//! which requires dynamic memory allocation to construct a `Subscriber` trait +//! which requires dynamic memory allocation to construct a collector trait //! object at runtime. When liballoc is disabled, new `Dispatch`s may still be -//! created from `&'static dyn Subscriber` references, using +//! created from `&'static dyn Collect` references, using //! [`Dispatch::from_static`]. //! //! The "std" feature is required to enable the following features: @@ -91,10 +91,10 @@ //! without `std` and `alloc`. //! //! [`libstd`]: https://doc.rust-lang.org/std/index.html -//! [`Dispatch::new`]: crate::dispatcher::Dispatch::new -//! [`Dispatch::from_static`]: crate::dispatcher::Dispatch::from_static -//! [`Dispatch::set_default`]: crate::dispatcher::set_default -//! [`with_default`]: crate::dispatcher::with_default +//! [`Dispatch::new`]: crate::dispatch::Dispatch::new +//! [`Dispatch::from_static`]: crate::dispatch::Dispatch::from_static +//! [`Dispatch::set_default`]: crate::dispatch::set_default +//! [`with_default`]: crate::dispatch::with_default //! [err]: crate::field::Visit::record_error //! //! ### Crate Feature Flags @@ -123,14 +123,14 @@ //! //! [`span::Id`]: span::Id //! [`Event`]: event::Event -//! [`Subscriber`]: subscriber::Subscriber +//! [`Collect`]: collect::Collect //! [`Metadata`]: metadata::Metadata //! [`Callsite`]: callsite::Callsite //! [`Field`]: field::Field //! [`FieldSet`]: field::FieldSet //! [`Value`]: field::Value //! [`ValueSet`]: field::ValueSet -//! [`Dispatch`]: dispatcher::Dispatch +//! [`Dispatch`]: dispatch::Dispatch //! [`tokio-rs/tracing`]: https://github.com/tokio-rs/tracing //! [`tracing`]: https://crates.io/crates/tracing #![doc(html_root_url = "https://docs.rs/tracing-core/0.1.17")] @@ -177,7 +177,7 @@ extern crate alloc; /// # #[macro_use] /// # extern crate tracing_core; /// use tracing_core::callsite; -/// # use tracing_core::{Metadata, subscriber::Interest}; +/// # use tracing_core::{Metadata, collect::Interest}; /// # fn main() { /// pub struct MyCallsite { /// // ... @@ -212,7 +212,7 @@ macro_rules! identify_callsite { /// ```rust /// # #[macro_use] /// # extern crate tracing_core; -/// # use tracing_core::{callsite::Callsite, subscriber::Interest}; +/// # use tracing_core::{callsite::Callsite, collect::Interest}; /// use tracing_core::metadata::{Kind, Level, Metadata}; /// # fn main() { /// # pub struct MyCallsite { } @@ -298,25 +298,25 @@ pub use std::sync::Once; pub(crate) mod spin; pub mod callsite; -pub mod dispatcher; +pub mod collect; +pub mod dispatch; pub mod event; pub mod field; pub mod metadata; mod parent; pub mod span; -pub mod subscriber; #[doc(inline)] pub use self::{ callsite::Callsite, - dispatcher::Dispatch, + collect::Collect, + dispatch::Dispatch, event::Event, field::Field, metadata::{Level, LevelFilter, Metadata}, - subscriber::Subscriber, }; -pub use self::{metadata::Kind, subscriber::Interest}; +pub use self::{collect::Interest, metadata::Kind}; mod sealed { pub trait Sealed {} diff --git a/tracing-core/src/metadata.rs b/tracing-core/src/metadata.rs index a8de8bfa1e..7ff30fb3a8 100644 --- a/tracing-core/src/metadata.rs +++ b/tracing-core/src/metadata.rs @@ -26,7 +26,7 @@ use core::{ /// - The [line number] /// - The [module path] /// -/// Metadata is used by [`Subscriber`]s when filtering spans and events, and it +/// Metadata is used by [collector]s when filtering spans and events, and it /// may also be used as part of their data payload. /// /// When created by the `event!` or `span!` macro, the metadata describing a @@ -58,7 +58,7 @@ use core::{ /// [file name]: Self::file /// [line number]: Self::line /// [module path]: Self::module_path -/// [`Subscriber`]: super::subscriber::Subscriber +/// [collector]: super::collect::Collect /// [callsite identifier]: super::callsite::Identifier pub struct Metadata<'a> { /// The name of the span described by this metadata. @@ -492,12 +492,12 @@ impl LevelFilter { const OFF_USIZE: usize = LevelInner::Error as usize + 1; /// Returns a `LevelFilter` that matches the most verbose [`Level`] that any - /// currently active [`Subscriber`] will enable. + /// currently active [collector] will enable. /// /// User code should treat this as a *hint*. If a given span or event has a /// level *higher* than the returned `LevelFilter`, it will not be enabled. /// However, if the level is less than or equal to this value, the span or - /// event is *not* guaranteed to be enabled; the subscriber will still + /// event is *not* guaranteed to be enabled; the collector will still /// filter each callsite individually. /// /// Therefore, comparing a given span or event's level to the returned @@ -506,7 +506,7 @@ impl LevelFilter { /// *enabled*.` /// /// [`Level`]: super::Level - /// [`Subscriber`]: super::Subscriber + /// [collector]: super::Collect #[inline(always)] pub fn current() -> Self { match MAX_LEVEL.load(Ordering::Relaxed) { diff --git a/tracing-core/src/span.rs b/tracing-core/src/span.rs index 1b6c659e08..5db743226f 100644 --- a/tracing-core/src/span.rs +++ b/tracing-core/src/span.rs @@ -3,18 +3,18 @@ use crate::parent::Parent; use crate::{field, Metadata}; use core::num::NonZeroU64; -/// Identifies a span within the context of a subscriber. +/// Identifies a span within the context of a collector. /// -/// They are generated by [`Subscriber`]s for each span as it is created, by +/// They are generated by [collector]s for each span as it is created, by /// the [`new_span`] trait method. See the documentation for that method for /// more information on span ID generation. /// -/// [`Subscriber`]: super::subscriber::Subscriber -/// [`new_span`]: super::subscriber::Subscriber::new_span +/// [collector]: super::collect::Collect +/// [`new_span`]: super::collect::Collect::new_span #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Id(NonZeroU64); -/// Attributes provided to a `Subscriber` describing a new span when it is +/// Attributes provided to a collector describing a new span when it is /// created. #[derive(Debug)] pub struct Attributes<'a> { @@ -29,15 +29,15 @@ pub struct Record<'a> { values: &'a field::ValueSet<'a>, } -/// Indicates what [the `Subscriber` considers] the "current" span. +/// Indicates what [the collector considers] the "current" span. /// -/// As subscribers may not track a notion of a current span, this has three +/// As collectors may not track a notion of a current span, this has three /// possible states: -/// - "unknown", indicating that the subscriber does not track a current span, +/// - "unknown", indicating that the collector does not track a current span, /// - "none", indicating that the current context is known to not be in a span, /// - "some", with the current span's [`Id`] and [`Metadata`]. /// -/// [the `Subscriber` considers]: super::subscriber::Subscriber::current_span +/// [the `Collector` considers]: super::collect::Collect::current_span /// [`Id`]: Id /// [`Metadata`]: super::metadata::Metadata #[derive(Debug)] @@ -243,7 +243,7 @@ impl Current { } } - /// Constructs a new `Current` that indicates the `Subscriber` does not + /// Constructs a new `Current` that indicates the collector does not /// track a current span. pub(crate) fn unknown() -> Self { Self { @@ -251,13 +251,13 @@ impl Current { } } - /// Returns `true` if the `Subscriber` that constructed this `Current` tracks a + /// Returns `true` if the collector that constructed this `Current` tracks a /// current span. /// /// If this returns `true` and [`id`], [`metadata`], or [`into_inner`] /// return `None`, that indicates that we are currently known to *not* be /// inside a span. If this returns `false`, those methods will also return - /// `None`, but in this case, that is because the subscriber does not keep + /// `None`, but in this case, that is because the collector does not keep /// track of the currently-entered span. /// /// [`id`]: Self::id diff --git a/tracing-core/tests/common/mod.rs b/tracing-core/tests/common/mod.rs index 3420f0b899..2e5d3a46ef 100644 --- a/tracing-core/tests/common/mod.rs +++ b/tracing-core/tests/common/mod.rs @@ -1,7 +1,7 @@ -use tracing_core::{metadata::Metadata, span, subscriber::Subscriber, Event}; +use tracing_core::{collect::Collect, metadata::Metadata, span, Event}; -pub struct TestSubscriberA; -impl Subscriber for TestSubscriberA { +pub struct TestCollectorA; +impl Collect for TestCollectorA { fn enabled(&self, _: &Metadata<'_>) -> bool { true } @@ -14,8 +14,8 @@ impl Subscriber for TestSubscriberA { fn enter(&self, _: &span::Id) {} fn exit(&self, _: &span::Id) {} } -pub struct TestSubscriberB; -impl Subscriber for TestSubscriberB { +pub struct TestCollectorB; +impl Collect for TestCollectorB { fn enabled(&self, _: &Metadata<'_>) -> bool { true } diff --git a/tracing-core/tests/dispatch.rs b/tracing-core/tests/dispatch.rs index 1e91cfebdc..b4981d337d 100644 --- a/tracing-core/tests/dispatch.rs +++ b/tracing-core/tests/dispatch.rs @@ -4,48 +4,38 @@ mod common; #[cfg(feature = "std")] use common::*; #[cfg(feature = "std")] -use tracing_core::dispatcher::*; +use tracing_core::dispatch::*; #[cfg(feature = "std")] #[test] fn set_default_dispatch() { - set_global_default(Dispatch::new(TestSubscriberA)).expect("global dispatch set failed"); - get_default(|current| { - assert!( - current.is::(), - "global dispatch get failed" - ) - }); + set_global_default(Dispatch::new(TestCollectorA)).expect("global dispatch set failed"); + get_default(|current| assert!(current.is::(), "global dispatch get failed")); - let guard = set_default(&Dispatch::new(TestSubscriberB)); - get_default(|current| assert!(current.is::(), "set_default get failed")); + let guard = set_default(&Dispatch::new(TestCollectorB)); + get_default(|current| assert!(current.is::(), "set_default get failed")); // Drop the guard, setting the dispatch back to the global dispatch drop(guard); - get_default(|current| { - assert!( - current.is::(), - "global dispatch get failed" - ) - }); + get_default(|current| assert!(current.is::(), "global dispatch get failed")); } #[cfg(feature = "std")] #[test] fn nested_set_default() { - let _guard = set_default(&Dispatch::new(TestSubscriberA)); + let _guard = set_default(&Dispatch::new(TestCollectorA)); get_default(|current| { assert!( - current.is::(), + current.is::(), "set_default for outer subscriber failed" ) }); - let inner_guard = set_default(&Dispatch::new(TestSubscriberB)); + let inner_guard = set_default(&Dispatch::new(TestCollectorB)); get_default(|current| { assert!( - current.is::(), + current.is::(), "set_default inner subscriber failed" ) }); @@ -53,7 +43,7 @@ fn nested_set_default() { drop(inner_guard); get_default(|current| { assert!( - current.is::(), + current.is::(), "set_default outer subscriber failed" ) }); diff --git a/tracing-core/tests/global_dispatch.rs b/tracing-core/tests/global_dispatch.rs index 7d69ea3976..9d195de6db 100644 --- a/tracing-core/tests/global_dispatch.rs +++ b/tracing-core/tests/global_dispatch.rs @@ -1,23 +1,18 @@ mod common; use common::*; -use tracing_core::dispatcher::*; +use tracing_core::dispatch::*; #[test] fn global_dispatch() { - static TEST: TestSubscriberA = TestSubscriberA; + static TEST: TestCollectorA = TestCollectorA; set_global_default(Dispatch::from_static(&TEST)).expect("global dispatch set failed"); - get_default(|current| { - assert!( - current.is::(), - "global dispatch get failed" - ) - }); + get_default(|current| assert!(current.is::(), "global dispatch get failed")); #[cfg(feature = "std")] - with_default(&Dispatch::new(TestSubscriberB), || { + with_default(&Dispatch::new(TestCollectorB), || { get_default(|current| { assert!( - current.is::(), + current.is::(), "thread-local override of global dispatch failed" ) }); @@ -25,7 +20,7 @@ fn global_dispatch() { get_default(|current| { assert!( - current.is::(), + current.is::(), "reset to global override failed" ) }); diff --git a/tracing-core/tests/macros.rs b/tracing-core/tests/macros.rs index ee9007eeeb..018efbf917 100644 --- a/tracing-core/tests/macros.rs +++ b/tracing-core/tests/macros.rs @@ -1,8 +1,8 @@ use tracing_core::{ callsite::Callsite, + collect::Interest, metadata, metadata::{Kind, Level, Metadata}, - subscriber::Interest, }; #[test] diff --git a/tracing-error/src/backtrace.rs b/tracing-error/src/backtrace.rs index ba1938d0ab..d7e52369b6 100644 --- a/tracing-error/src/backtrace.rs +++ b/tracing-error/src/backtrace.rs @@ -114,7 +114,7 @@ impl SpanTrace { /// [fields]: https://docs.rs/tracing/latest/tracing/field/index.html /// [`Metadata`]: https://docs.rs/tracing/latest/tracing/struct.Metadata.html pub fn with_spans(&self, f: impl FnMut(&'static Metadata<'static>, &str) -> bool) { - self.span.with_subscriber(|(id, s)| { + self.span.with_collector(|(id, s)| { if let Some(getcx) = s.downcast_ref::() { getcx.with_context(s, id, f); } @@ -124,7 +124,7 @@ impl SpanTrace { /// Returns the status of this `SpanTrace`. /// /// The status indicates one of the following: - /// * the current subscriber does not support capturing `SpanTrace`s + /// * the current collector does not support capturing `SpanTrace`s /// * there was no current span, so a trace was not captured /// * a span trace was successfully captured pub fn status(&self) -> SpanTraceStatus { @@ -132,7 +132,7 @@ impl SpanTrace { SpanTraceStatusInner::Empty } else { let mut status = None; - self.span.with_subscriber(|(_, s)| { + self.span.with_collector(|(_, s)| { if s.downcast_ref::().is_some() { status = Some(SpanTraceStatusInner::Captured); } @@ -266,15 +266,15 @@ impl fmt::Debug for SpanTrace { mod tests { use super::*; use crate::ErrorLayer; - use tracing::subscriber::with_default; + use tracing::collect::with_default; use tracing::{span, Level}; use tracing_subscriber::{prelude::*, registry::Registry}; #[test] fn capture_supported() { - let subscriber = Registry::default().with(ErrorLayer::default()); + let collector = Registry::default().with(ErrorLayer::default()); - with_default(subscriber, || { + with_default(collector, || { let span = span!(Level::ERROR, "test span"); let _guard = span.enter(); @@ -288,9 +288,9 @@ mod tests { #[test] fn capture_empty() { - let subscriber = Registry::default().with(ErrorLayer::default()); + let collector = Registry::default().with(ErrorLayer::default()); - with_default(subscriber, || { + with_default(collector, || { let span_trace = SpanTrace::capture(); dbg!(&span_trace); @@ -301,9 +301,9 @@ mod tests { #[test] fn capture_unsupported() { - let subscriber = Registry::default(); + let collector = Registry::default(); - with_default(subscriber, || { + with_default(collector, || { let span = span!(Level::ERROR, "test span"); let _guard = span.enter(); diff --git a/tracing-error/src/layer.rs b/tracing-error/src/layer.rs index 05e50c7d86..60341a15e4 100644 --- a/tracing-error/src/layer.rs +++ b/tracing-error/src/layer.rs @@ -1,21 +1,21 @@ use std::any::{type_name, TypeId}; use std::fmt; use std::marker::PhantomData; -use tracing::{span, Dispatch, Metadata, Subscriber}; +use tracing::{span, Collect, Dispatch, Metadata}; use tracing_subscriber::fmt::format::{DefaultFields, FormatFields}; use tracing_subscriber::{ fmt::FormattedFields, - layer::{self, Layer}, registry::LookupSpan, + subscribe::{self, Subscribe}, }; -/// A subscriber [`Layer`] that enables capturing [`SpanTrace`]s. +/// A [subscriber] that enables capturing [`SpanTrace`]s. /// /// Optionally, this type may be constructed with a [field formatter] to use /// when formatting the fields of each span in a trace. When no formatter is /// provided, the [default format] is used instead. /// -/// [`Layer`]: https://docs.rs/tracing-subscriber/0.2.10/tracing_subscriber/layer/trait.Layer.html +/// [subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/subscriber/trait.Subscribe.html /// [`SpanTrace`]: ../struct.SpanTrace.html /// [field formatter]: https://docs.rs/tracing-subscriber/0.2.10/tracing_subscriber/fmt/trait.FormatFields.html /// [default format]: https://docs.rs/tracing-subscriber/0.2.10/tracing_subscriber/fmt/format/struct.DefaultFields.html @@ -33,14 +33,19 @@ pub(crate) struct WithContext( fn(&Dispatch, &span::Id, f: &mut dyn FnMut(&'static Metadata<'static>, &str) -> bool), ); -impl Layer for ErrorLayer +impl Subscribe for ErrorLayer where - S: Subscriber + for<'span> LookupSpan<'span>, + S: Collect + for<'span> LookupSpan<'span>, F: for<'writer> FormatFields<'writer> + 'static, { /// Notifies this layer that a new span was constructed with the given /// `Attributes` and `Id`. - fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: layer::Context<'_, S>) { + fn new_span( + &self, + attrs: &span::Attributes<'_>, + id: &span::Id, + ctx: subscribe::Context<'_, S>, + ) { let span = ctx.span(id).expect("span must already exist!"); if span.extensions().get::>().is_some() { return; @@ -66,7 +71,7 @@ where impl ErrorLayer where F: for<'writer> FormatFields<'writer> + 'static, - S: Subscriber + for<'span> LookupSpan<'span>, + S: Collect + for<'span> LookupSpan<'span>, { /// Returns a new `ErrorLayer` with the provided [field formatter]. /// @@ -117,7 +122,7 @@ impl WithContext { impl Default for ErrorLayer where - S: Subscriber + for<'span> LookupSpan<'span>, + S: Collect + for<'span> LookupSpan<'span>, { fn default() -> Self { Self::new(DefaultFields::default()) diff --git a/tracing-error/src/lib.rs b/tracing-error/src/lib.rs index 6c46bc4dda..5fb05681e6 100644 --- a/tracing-error/src/lib.rs +++ b/tracing-error/src/lib.rs @@ -139,7 +139,7 @@ //! ``` //! //! Applications that wish to use `tracing-error`-enabled errors should -//! construct an [`ErrorLayer`] and add it to their [`Subscriber`] in order to +//! construct an [`ErrorLayer`] and add it to their [collector` in order to //! enable capturing [`SpanTrace`]s. For example: //! //! ```rust @@ -153,7 +153,7 @@ //! .with(ErrorLayer::default()); //! //! // set the subscriber as the default for the application -//! tracing::subscriber::set_global_default(subscriber); +//! tracing::collect::set_global_default(subscriber); //! } //! ``` //! @@ -166,7 +166,7 @@ //! [`in_current_span()`]: trait.InstrumentResult.html#tymethod.in_current_span //! [span]: https://docs.rs/tracing/latest/tracing/span/index.html //! [events]: https://docs.rs/tracing/latest/tracing/struct.Event.html -//! [`Subscriber`]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html +//! [collector]: https://docs.rs/tracing/latest/tracing/trait.Collect.html //! [subscriber layer]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/trait.Layer.html //! [`tracing`]: https://docs.rs/tracing //! [`std::error::Error`]: https://doc.rust-lang.org/stable/std/error/trait.Error.html diff --git a/tracing-flame/src/lib.rs b/tracing-flame/src/lib.rs index b04d07def3..371dabf34a 100644 --- a/tracing-flame/src/lib.rs +++ b/tracing-flame/src/lib.rs @@ -1,4 +1,4 @@ -//! A Tracing [Layer][`FlameLayer`] for generating a folded stack trace for generating flamegraphs +//! A Tracing [Subscriber][`FlameSubscriber`] for generating a folded stack trace for generating flamegraphs //! and flamecharts with [`inferno`] //! //! # Overview @@ -20,32 +20,32 @@ //! This crate is meant to be used in a two step process: //! //! 1. Capture textual representation of the spans that are entered and exited -//! with [`FlameLayer`]. +//! with [`FlameSubscriber`]. //! 2. Feed the textual representation into `inferno-flamegraph` to generate the //! flamegraph or flamechart. //! -//! *Note*: when using a buffered writer as the writer for a `FlameLayer`, it is necessary to +//! *Note*: when using a buffered writer as the writer for a `FlameSubscriber`, it is necessary to //! ensure that the buffer has been flushed before the data is passed into //! [`inferno-flamegraph`]. For more details on how to flush the internal writer -//! of the `FlameLayer`, see the docs for [`FlushGuard`]. +//! of the `FlameSubscriber`, see the docs for [`FlushGuard`]. //! -//! ## Layer Setup +//! ## Subscriber Setup //! //! ```rust //! use std::{fs::File, io::BufWriter}; -//! use tracing_flame::FlameLayer; +//! use tracing_flame::FlameSubscriber; //! use tracing_subscriber::{registry::Registry, prelude::*, fmt}; //! //! fn setup_global_subscriber() -> impl Drop { -//! let fmt_layer = fmt::Layer::default(); +//! let fmt_subscriber = fmt::Subscriber::default(); //! -//! let (flame_layer, _guard) = FlameLayer::with_file("./tracing.folded").unwrap(); +//! let (flame_subscriber, _guard) = FlameSubscriber::with_file("./tracing.folded").unwrap(); //! -//! let subscriber = Registry::default() -//! .with(fmt_layer) -//! .with(flame_layer); +//! let collector = Registry::default() +//! .with(fmt_subscriber) +//! .with(flame_subscriber); //! -//! tracing::subscriber::set_global_default(subscriber).expect("Could not set global default"); +//! tracing::collect::set_global_default(collector).expect("Could not set global default"); //! _guard //! } //! @@ -53,7 +53,7 @@ //! ``` //! //! As an alternative, you can provide _any_ type that implements `std::io::Write` to -//! `FlameLayer::new`. +//! `FlameSubscriber::new`. //! //! ## Generating the Image //! @@ -154,11 +154,11 @@ use std::sync::Arc; use std::sync::Mutex; use std::time::{Duration, Instant}; use tracing::span; -use tracing::Subscriber; -use tracing_subscriber::layer::Context; +use tracing::Collect; use tracing_subscriber::registry::LookupSpan; use tracing_subscriber::registry::SpanRef; -use tracing_subscriber::Layer; +use tracing_subscriber::subscribe::Context; +use tracing_subscriber::Subscribe; mod error; @@ -180,10 +180,10 @@ thread_local! { }; } -/// A `Layer` that records span open/close events as folded flamegraph stack +/// A `Subscriber` that records span open/close events as folded flamegraph stack /// samples. /// -/// The output of `FlameLayer` emulates the output of commands like `perf` once +/// The output of `FlameSubscriber` emulates the output of commands like `perf` once /// they've been collapsed by `inferno-flamegraph`. The output of this layer /// should look similar to the output of the following commands: /// @@ -201,24 +201,24 @@ thread_local! { /// /// # Dropping and Flushing /// -/// If you use a global subscriber the drop implementations on your various -/// layers will not get called when your program exits. This means that if -/// you're using a buffered writer as the inner writer for the `FlameLayer` +/// If you use a global collector the drop implementations on your various +/// subscribers will not get called when your program exits. This means that if +/// you're using a buffered writer as the inner writer for the `FlameSubscriber` /// you're not guaranteed to see all the events that have been emitted in the /// file by default. /// -/// To ensure all data is flushed when the program exits, `FlameLayer` exposes +/// To ensure all data is flushed when the program exits, `FlameSubscriber` exposes /// the [`flush_on_drop`] function, which returns a [`FlushGuard`]. The `FlushGuard` /// will flush the writer when it is dropped. If necessary, it can also be used to manually /// flush the writer. /// -/// [`flush_on_drop`]: struct.FlameLayer.html#method.flush_on_drop +/// [`flush_on_drop`]: struct.FlameSubscriber.html#method.flush_on_drop /// [`FlushGuard`]: struct.FlushGuard.html #[derive(Debug)] -pub struct FlameLayer { +pub struct FlameSubscriber { out: Arc>, config: Config, - _inner: PhantomData, + _inner: PhantomData, } #[derive(Debug)] @@ -254,12 +254,12 @@ where out: Arc>, } -impl FlameLayer +impl FlameSubscriber where - S: Subscriber + for<'span> LookupSpan<'span>, + C: Collect + for<'span> LookupSpan<'span>, W: Write + 'static, { - /// Returns a new `FlameLayer` that outputs all folded stack samples to the + /// Returns a new `FlameSubscriber` that outputs all folded stack samples to the /// provided writer. pub fn new(writer: W) -> Self { // Initialize the start used by all threads when initializing the @@ -272,7 +272,7 @@ where } } - /// Returns a `FlushGuard` which will flush the `FlameLayer`'s writer when + /// Returns a `FlushGuard` which will flush the `FlameSubscriber`'s writer when /// it is dropped, or when `flush` is manually invoked on the guard. pub fn flush_on_drop(&self) -> FlushGuard { FlushGuard { @@ -318,7 +318,7 @@ impl FlushGuard where W: Write + 'static, { - /// Flush the internal writer of the `FlameLayer`, ensuring that all + /// Flush the internal writer of the `FlameSubscriber`, ensuring that all /// intermediately buffered contents reach their destination. pub fn flush(&self) -> Result<(), Error> { let mut guard = match self.out.lock() { @@ -348,11 +348,11 @@ where } } -impl FlameLayer> +impl FlameSubscriber> where - S: Subscriber + for<'span> LookupSpan<'span>, + C: Collect + for<'span> LookupSpan<'span>, { - /// Constructs a `FlameLayer` that outputs to a `BufWriter` to the given path, and a + /// Constructs a `FlameSubscriber` that outputs to a `BufWriter` to the given path, and a /// `FlushGuard` to ensure the writer is flushed. pub fn with_file(path: impl AsRef) -> Result<(Self, FlushGuard>), Error> { let path = path.as_ref(); @@ -369,12 +369,12 @@ where } } -impl Layer for FlameLayer +impl Subscribe for FlameSubscriber where - S: Subscriber + for<'span> LookupSpan<'span>, + C: Collect + for<'span> LookupSpan<'span>, W: Write + 'static, { - fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) { + fn on_enter(&self, id: &span::Id, ctx: Context<'_, C>) { let samples = self.time_since_last_event(); let first = ctx.span(id).expect("expected: span id exists in registry"); @@ -404,7 +404,7 @@ where let _ = writeln!(*self.out.lock().unwrap(), "{}", stack); } - fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) { + fn on_exit(&self, id: &span::Id, ctx: Context<'_, C>) { let panicking = std::thread::panicking(); macro_rules! expect { ($e:expr, $msg:literal) => { @@ -456,9 +456,9 @@ where } } -impl FlameLayer +impl FlameSubscriber where - S: Subscriber + for<'span> LookupSpan<'span>, + C: Collect + for<'span> LookupSpan<'span>, W: Write + 'static, { fn time_since_last_event(&self) -> Duration { @@ -474,9 +474,9 @@ where } } -fn write(dest: &mut String, span: SpanRef<'_, S>) -> fmt::Result +fn write(dest: &mut String, span: SpanRef<'_, C>) -> fmt::Result where - S: Subscriber + for<'span> LookupSpan<'span>, + C: Collect + for<'span> LookupSpan<'span>, { if let Some(module_path) = span.metadata().module_path() { write!(dest, "{}::", module_path)?; diff --git a/tracing-flame/tests/collapsed.rs b/tracing-flame/tests/collapsed.rs index 575aa3b6a0..e06ddff8d4 100644 --- a/tracing-flame/tests/collapsed.rs +++ b/tracing-flame/tests/collapsed.rs @@ -2,7 +2,7 @@ use std::thread::sleep; use std::time::Duration; use tempdir::TempDir; use tracing::{span, Level}; -use tracing_flame::FlameLayer; +use tracing_flame::FlameSubscriber; use tracing_subscriber::{prelude::*, registry::Registry}; #[test] @@ -10,11 +10,11 @@ fn capture_supported() { { let tmp_dir = TempDir::new("flamegraphs").unwrap(); let (flame_layer, _guard) = - FlameLayer::with_file(tmp_dir.path().join("tracing.folded")).unwrap(); + FlameSubscriber::with_file(tmp_dir.path().join("tracing.folded")).unwrap(); let subscriber = Registry::default().with(flame_layer); - tracing::subscriber::set_global_default(subscriber).expect("Could not set global default"); + tracing::collect::set_global_default(subscriber).expect("Could not set global default"); { let span = span!(Level::ERROR, "outer"); diff --git a/tracing-flame/tests/concurrent.rs b/tracing-flame/tests/concurrent.rs index 272ad0f1ba..1eaa401ea3 100644 --- a/tracing-flame/tests/concurrent.rs +++ b/tracing-flame/tests/concurrent.rs @@ -2,18 +2,18 @@ use std::thread::sleep; use std::time::Duration; use tempdir::TempDir; use tracing::{span, Level}; -use tracing_flame::FlameLayer; +use tracing_flame::FlameSubscriber; use tracing_subscriber::{prelude::*, registry::Registry}; #[test] fn capture_supported() { let tmp_dir = TempDir::new("flamegraphs").unwrap(); let path = tmp_dir.path().join("tracing.folded"); - let (flame_layer, flame_guard) = FlameLayer::with_file(&path).unwrap(); + let (flame_layer, flame_guard) = FlameSubscriber::with_file(&path).unwrap(); let subscriber = Registry::default().with(flame_layer); - tracing::subscriber::set_global_default(subscriber).expect("Could not set global default"); + tracing::collect::set_global_default(subscriber).expect("Could not set global default"); let span = span!(Level::ERROR, "main"); let _guard = span.enter(); diff --git a/tracing-futures/src/lib.rs b/tracing-futures/src/lib.rs index 53d0710c3f..4b8134776f 100644 --- a/tracing-futures/src/lib.rs +++ b/tracing-futures/src/lib.rs @@ -12,7 +12,7 @@ //! * [`Instrument`] allows a `tracing` [span] to be attached to a future, sink, //! stream, or executor. //! -//! * [`WithSubscriber`] allows a `tracing` [`Subscriber`] to be attached to a +//! * [`WithCollector`] allows a `tracing` [collector] to be attached to a //! future, sink, stream, or executor. //! //! *Compiler support: [requires `rustc` 1.42+][msrv]* @@ -25,11 +25,11 @@ //! features with other crates in the asynchronous ecosystem: //! //! - `tokio`: Enables compatibility with the `tokio` crate, including -//! [`Instrument`] and [`WithSubscriber`] implementations for +//! [`Instrument`] and [`WithCollector`] implementations for //! `tokio::executor::Executor`, `tokio::runtime::Runtime`, and //! `tokio::runtime::current_thread`. Enabled by default. //! - `tokio-executor`: Enables compatibility with the `tokio-executor` -//! crate, including [`Instrument`] and [`WithSubscriber`] +//! crate, including [`Instrument`] and [`WithCollector`] //! implementations for types implementing `tokio_executor::Executor`. //! This is intended primarily for use in crates which depend on //! `tokio-executor` rather than `tokio`; in general the `tokio` feature @@ -54,9 +54,9 @@ //! //! [`tracing`]: https://crates.io/crates/tracing //! [span]: https://docs.rs/tracing/latest/tracing/span/index.html -//! [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/index.html +//! [collector]: https://docs.rs/tracing/latest/tracing/collect/index.html //! [`Instrument`]: trait.Instrument.html -//! [`WithSubscriber`]: trait.WithSubscriber.html +//! [`WithCollector`]: trait.WithCollector.html //! [`futures`]: https://crates.io/crates/futures //! //! ## Supported Rust Versions @@ -110,7 +110,7 @@ use pin_project::pin_project; use core::{pin::Pin, task::Context}; #[cfg(feature = "std")] -use tracing::{dispatcher, Dispatch}; +use tracing::{dispatch, Dispatch}; use tracing::Span; @@ -193,13 +193,13 @@ pub trait Instrument: Sized { } /// Extension trait allowing futures, streams, and sinks to be instrumented with -/// a `tracing` [`Subscriber`]. +/// a `tracing` [collector]. /// -/// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/trait.Subscriber.html +/// [collector]: https://docs.rs/tracing/latest/tracing/collect/trait.Collect.html #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] -pub trait WithSubscriber: Sized { - /// Attaches the provided [`Subscriber`] to this type, returning a +pub trait WithCollector: Sized { + /// Attaches the provided [collector] to this type, returning a /// `WithDispatch` wrapper. /// /// When the wrapped type is a future, stream, or sink, the attached @@ -207,19 +207,19 @@ pub trait WithSubscriber: Sized { /// When the wrapped type is an executor, the subscriber will be set as the /// default for any futures spawned on that executor. /// - /// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/trait.Subscriber.html + /// [collector]: https://docs.rs/tracing/latest/tracing/collect/trait.Collect.html /// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber - fn with_subscriber(self, subscriber: S) -> WithDispatch + fn with_collector(self, collector: S) -> WithDispatch where S: Into, { WithDispatch { inner: self, - dispatch: subscriber.into(), + dispatch: collector.into(), } } - /// Attaches the current [default] [`Subscriber`] to this type, returning a + /// Attaches the current [default] [collector] to this type, returning a /// `WithDispatch` wrapper. /// /// When the wrapped type is a future, stream, or sink, the attached @@ -230,13 +230,13 @@ pub trait WithSubscriber: Sized { /// This can be used to propagate the current dispatcher context when /// spawning a new future. /// - /// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/trait.Subscriber.html + /// [collector]: https://docs.rs/tracing/latest/tracing/collect/trait.Collect.html /// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber #[inline] - fn with_current_subscriber(self) -> WithDispatch { + fn with_current_collector(self) -> WithDispatch { WithDispatch { inner: self, - dispatch: dispatcher::get_default(|default| default.clone()), + dispatch: dispatch::get_default(|default| default.clone()), } } } @@ -428,7 +428,7 @@ impl Instrumented { } #[cfg(feature = "std")] -impl WithSubscriber for T {} +impl WithCollector for T {} #[cfg(all(feature = "futures-01", feature = "std"))] #[cfg_attr(docsrs, doc(cfg(all(feature = "futures-01", feature = "std"))))] @@ -438,7 +438,7 @@ impl futures_01::Future for WithDispatch { fn poll(&mut self) -> futures_01::Poll { let inner = &mut self.inner; - dispatcher::with_default(&self.dispatch, || inner.poll()) + dispatch::with_default(&self.dispatch, || inner.poll()) } } @@ -451,7 +451,7 @@ impl core::future::Future for WithDispatch { let this = self.project(); let dispatch = this.dispatch; let future = this.inner; - dispatcher::with_default(dispatch, || future.poll(cx)) + dispatch::with_default(dispatch, || future.poll(cx)) } } @@ -515,7 +515,7 @@ mod tests { #[cfg(feature = "futures-01")] mod futures_01_tests { use futures_01::{future, stream, task, Async, Future, Stream}; - use tracing::subscriber::with_default; + use tracing::collect::with_default; use super::*; @@ -562,7 +562,7 @@ mod tests { #[test] fn future_enter_exit_is_reasonable() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -570,7 +570,7 @@ mod tests { .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { PollN::new_ok(2) .instrument(tracing::trace_span!("foo")) .wait() @@ -581,7 +581,7 @@ mod tests { #[test] fn future_error_ends_span() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -589,7 +589,7 @@ mod tests { .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { PollN::new_err(2) .instrument(tracing::trace_span!("foo")) .wait() @@ -601,7 +601,7 @@ mod tests { #[test] fn stream_enter_exit_is_reasonable() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -612,7 +612,7 @@ mod tests { .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { stream::iter_ok::<_, ()>(&[1, 2, 3]) .instrument(tracing::trace_span!("foo")) .for_each(|_| future::ok(())) @@ -624,7 +624,7 @@ mod tests { #[test] fn span_follows_future_onto_threadpool() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("a")) .enter(span::mock().named("b")) .exit(span::mock().named("b")) @@ -636,7 +636,7 @@ mod tests { .done() .run_with_handle(); let mut runtime = tokio::runtime::Runtime::new().unwrap(); - with_default(subscriber, || { + with_default(collector, || { tracing::trace_span!("a").in_scope(|| { let future = PollN::new_ok(2) .instrument(tracing::trace_span!("b")) @@ -656,13 +656,13 @@ mod tests { #[cfg(all(feature = "futures-03", feature = "std-future"))] mod futures_03_tests { use futures::{future, sink, stream, FutureExt, SinkExt, StreamExt}; - use tracing::subscriber::with_default; + use tracing::collect::with_default; use super::*; #[test] fn stream_enter_exit_is_reasonable() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -673,7 +673,7 @@ mod tests { .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { Instrument::instrument(stream::iter(&[1, 2, 3]), tracing::trace_span!("foo")) .for_each(|_| future::ready(())) .now_or_never() @@ -684,7 +684,7 @@ mod tests { #[test] fn sink_enter_exit_is_reasonable() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -693,7 +693,7 @@ mod tests { .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { Instrument::instrument(sink::drain(), tracing::trace_span!("foo")) .send(1u8) .now_or_never() diff --git a/tracing-futures/tests/std_future.rs b/tracing-futures/tests/std_future.rs index a5431d37da..8757b88d13 100644 --- a/tracing-futures/tests/std_future.rs +++ b/tracing-futures/tests/std_future.rs @@ -2,11 +2,11 @@ mod support; use support::*; use tracing::Instrument; -use tracing::{subscriber::with_default, Level}; +use tracing::{collect::with_default, Level}; #[test] fn enter_exit_is_reasonable() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -14,7 +14,7 @@ fn enter_exit_is_reasonable() { .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let future = PollN::new_ok(2).instrument(tracing::span!(Level::TRACE, "foo")); block_on_future(future).unwrap(); }); @@ -23,7 +23,7 @@ fn enter_exit_is_reasonable() { #[test] fn error_ends_span() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -31,7 +31,7 @@ fn error_ends_span() { .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let future = PollN::new_err(2).instrument(tracing::span!(Level::TRACE, "foo")); block_on_future(future).unwrap_err(); }); diff --git a/tracing-journald/src/lib.rs b/tracing-journald/src/lib.rs index 978884fcd2..9109b346ce 100644 --- a/tracing-journald/src/lib.rs +++ b/tracing-journald/src/lib.rs @@ -7,7 +7,7 @@ //! //! [`tracing`] is a framework for instrumenting Rust programs to collect //! scoped, structured, and async-aware diagnostics. `tracing-journald` provides a -//! [`tracing-subscriber::Layer`][layer] implementation for logging `tracing` spans +//! [`tracing-subscriber::Subscriber`][subscriber] implementation for logging `tracing` spans //! and events to [`systemd-journald`][journald], on Linux distributions that //! use `systemd`. //! @@ -15,7 +15,7 @@ //! //! [msrv]: #supported-rust-versions //! [`tracing`]: https://crates.io/crates/tracing -//! [layer]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/trait.Layer.html +//! [subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/subscriber/trait.Subscriber.html //! [journald]: https://www.freedesktop.org/software/systemd/man/systemd-journald.service.html //! //! ## Supported Rust Versions @@ -46,14 +46,14 @@ use tracing_core::{ event::Event, field::Visit, span::{Attributes, Id, Record}, - Field, Level, Metadata, Subscriber, + Collect, Field, Level, Metadata, }; -use tracing_subscriber::{layer::Context, registry::LookupSpan}; +use tracing_subscriber::{registry::LookupSpan, subscribe::Context}; /// Sends events and their fields to journald /// /// [journald conventions] for structured field names differ from typical tracing idioms, and journald -/// discards fields which violate its conventions. Hence, this layer automatically sanitizes field +/// discards fields which violate its conventions. Hence, this subscriber automatically sanitizes field /// names by translating `.`s into `_`s, stripping leading `_`s and non-ascii-alphanumeric /// characters other than `_`, and upcasing. /// @@ -76,14 +76,14 @@ use tracing_subscriber::{layer::Context, registry::LookupSpan}; /// prevent collision with standard fields. /// /// [journald conventions]: https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html -pub struct Layer { +pub struct Subscriber { #[cfg(unix)] socket: UnixDatagram, field_prefix: Option, } -impl Layer { - /// Construct a journald layer +impl Subscriber { + /// Construct a journald subscriber /// /// Fails if the journald socket couldn't be opened. Returns a `NotFound` error unconditionally /// in non-Unix environments. @@ -112,18 +112,18 @@ impl Layer { } } -/// Construct a journald layer +/// Construct a journald subscriber /// /// Fails if the journald socket couldn't be opened. -pub fn layer() -> io::Result { - Layer::new() +pub fn subscriber() -> io::Result { + Subscriber::new() } -impl tracing_subscriber::Layer for Layer +impl tracing_subscriber::Subscribe for Subscriber where - S: Subscriber + for<'span> LookupSpan<'span>, + C: Collect + for<'span> LookupSpan<'span>, { - fn new_span(&self, attrs: &Attributes, id: &Id, ctx: Context) { + fn new_span(&self, attrs: &Attributes, id: &Id, ctx: Context) { let span = ctx.span(id).expect("unknown span"); let mut buf = Vec::with_capacity(256); @@ -142,7 +142,7 @@ where span.extensions_mut().insert(SpanFields(buf)); } - fn on_record(&self, id: &Id, values: &Record, ctx: Context) { + fn on_record(&self, id: &Id, values: &Record, ctx: Context) { let span = ctx.span(id).expect("unknown span"); let depth = span.parents().count(); let mut exts = span.extensions_mut(); @@ -154,7 +154,7 @@ where }); } - fn on_event(&self, event: &Event, ctx: Context) { + fn on_event(&self, event: &Event, ctx: Context) { let mut buf = Vec::with_capacity(256); // Record span fields diff --git a/tracing-log/src/lib.rs b/tracing-log/src/lib.rs index 1401dca838..b94592c50e 100644 --- a/tracing-log/src/lib.rs +++ b/tracing-log/src/lib.rs @@ -58,10 +58,10 @@ //! ## Caution: Mixing both conversions //! //! Note that logger implementations that convert log records to trace events -//! should not be used with `Subscriber`s that convert trace events _back_ into -//! log records, as doing so will result in the event recursing between the -//! subscriber and the logger forever (or, in real life, probably overflowing -//! the call stack). +//! should not be used with `Collector`s that convert trace events _back_ into +//! log records (such as the `TraceLogger`), as doing so will result in the +//! event recursing between the collector and the logger forever (or, in real +//! life, probably overflowing the call stack). //! //! If the logging of trace events generated from log records produced by the //! `log` crate is desired, either the `log` crate should not be used to @@ -98,8 +98,8 @@ //! [`env_logger` crate]: https://crates.io/crates/env-logger //! [`log::Log`]: https://docs.rs/log/latest/log/trait.Log.html //! [`log::Record`]: https://docs.rs/log/latest/log/struct.Record.html -//! [`tracing::Subscriber`]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html -//! [`Subscriber`]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html +//! [`tracing::Collector`]: https://docs.rs/tracing/latest/tracing/trait.Collect.html +//! [`Collect`]: https://docs.rs/tracing/latest/tracing/trait.Collect.html //! [`tracing::Event`]: https://docs.rs/tracing/latest/tracing/struct.Event.html //! [flags]: https://docs.rs/tracing/latest/tracing/#crate-feature-flags #![doc(html_root_url = "https://docs.rs/tracing-log/0.1.1")] @@ -137,11 +137,11 @@ use std::{fmt, io}; use tracing_core::{ callsite::{self, Callsite}, - dispatcher, + collect, dispatch, field::{self, Field, Visit}, identify_callsite, metadata::{Kind, Level}, - subscriber, Event, Metadata, + Event, Metadata, }; #[cfg(feature = "log-tracer")] @@ -162,7 +162,7 @@ pub use log; /// Format a log record as a trace event in the current span. pub fn format_trace(record: &log::Record<'_>) -> io::Result<()> { let filter_meta = record.as_trace(); - if !dispatcher::get_default(|dispatch| dispatch.enabled(&filter_meta)) { + if !dispatch::get_default(|dispatch| dispatch.enabled(&filter_meta)) { return Ok(()); }; @@ -270,7 +270,7 @@ macro_rules! log_cs { ); impl callsite::Callsite for Callsite { - fn set_interest(&self, _: subscriber::Interest) {} + fn set_interest(&self, _: collect::Interest) {} fn metadata(&self) -> &'static Metadata<'static> { &META } @@ -375,7 +375,7 @@ impl AsTrace for log::Level { /// that only lives as long as its source `Event`, but provides complete /// data. /// -/// It can typically be used by `Subscriber`s when processing an `Event`, +/// It can typically be used by collectors when processing an `Event`, /// to allow accessing its complete metadata in a consistent way, /// regardless of the source of its source. /// diff --git a/tracing-log/src/log_tracer.rs b/tracing-log/src/log_tracer.rs index a62f2639d0..fe9316aba0 100644 --- a/tracing-log/src/log_tracer.rs +++ b/tracing-log/src/log_tracer.rs @@ -2,7 +2,7 @@ //! //! This module provides the [`LogTracer`] type which implements `log`'s [logger //! interface] by recording log records as `tracing` `Event`s. This is intended for -//! use in conjunction with a `tracing` `Subscriber` to consume events from +//! use in conjunction with a `tracing` `Collector` to consume events from //! dependencies that emit [`log`] records within a trace context. //! //! # Usage @@ -10,7 +10,7 @@ //! To create and initialize a `LogTracer` with the default configurations, use: //! //! * [`init`] if you want to convert all logs, regardless of log level, -//! allowing the tracing `Subscriber` to perform any filtering +//! allowing the tracing `Collector` to perform any filtering //! * [`init_with_filter`] to convert all logs up to a specified log level //! //! In addition, a [builder] is available for cases where more advanced @@ -28,7 +28,7 @@ //! [ignore]: struct.Builder.html#method.ignore_crate use crate::{format_trace, AsTrace}; pub use log::SetLoggerError; -use tracing_core::dispatcher; +use tracing_core::dispatch; /// A simple "logger" that converts all log records into `tracing` `Event`s. #[derive(Debug)] @@ -134,7 +134,7 @@ impl LogTracer { /// # } /// ``` /// - /// This will forward all logs to `tracing` and lets the current `Subscriber` + /// This will forward all logs to `tracing` and lets the current `Collector` /// determine if they are enabled. /// /// The [`builder`] function can be used to customize the `LogTracer` before @@ -174,7 +174,7 @@ impl log::Log for LogTracer { } fn log(&self, record: &log::Record<'_>) { - let enabled = dispatcher::get_default(|dispatch| { + let enabled = dispatch::get_default(|dispatch| { // TODO: can we cache this for each log record, so we can get // similar to the callsite cache? dispatch.enabled(&record.as_trace()) diff --git a/tracing-log/tests/log_tracer.rs b/tracing-log/tests/log_tracer.rs index c8589e83b1..2c5832e275 100644 --- a/tracing-log/tests/log_tracer.rs +++ b/tracing-log/tests/log_tracer.rs @@ -1,7 +1,7 @@ use std::sync::{Arc, Mutex}; -use tracing::subscriber::with_default; +use tracing::collect::with_default; use tracing_core::span::{Attributes, Record}; -use tracing_core::{span, Event, Level, Metadata, Subscriber}; +use tracing_core::{span, Collect, Event, Level, Metadata}; use tracing_log::{LogTracer, NormalizeEvent}; struct State { @@ -20,7 +20,7 @@ struct OwnedMetadata { struct TestSubscriber(Arc); -impl Subscriber for TestSubscriber { +impl Collect for TestSubscriber { fn enabled(&self, _: &Metadata<'_>) -> bool { true } diff --git a/tracing-opentelemetry/src/layer.rs b/tracing-opentelemetry/src/layer.rs index 85000b7b3d..5e16aca920 100644 --- a/tracing-opentelemetry/src/layer.rs +++ b/tracing-opentelemetry/src/layer.rs @@ -5,12 +5,12 @@ use std::fmt; use std::marker; use std::time::SystemTime; use tracing_core::span::{self, Attributes, Id, Record}; -use tracing_core::{field, Event, Subscriber}; +use tracing_core::{field, Collect, Event}; #[cfg(feature = "tracing-log")] use tracing_log::NormalizeEvent; -use tracing_subscriber::layer::Context; use tracing_subscriber::registry::LookupSpan; -use tracing_subscriber::Layer; +use tracing_subscriber::subscribe::Context; +use tracing_subscriber::Subscribe; static SPAN_NAME_FIELD: &str = "otel.name"; static SPAN_KIND_FIELD: &str = "otel.kind"; @@ -29,7 +29,7 @@ pub struct OpenTelemetryLayer { impl Default for OpenTelemetryLayer where - S: Subscriber + for<'span> LookupSpan<'span>, + S: Collect + for<'span> LookupSpan<'span>, { fn default() -> Self { OpenTelemetryLayer::new(api::NoopTracer {}) @@ -43,7 +43,7 @@ where /// # Examples /// /// ```rust,no_run -/// use tracing_subscriber::layer::SubscriberExt; +/// use tracing_subscriber::subscribe::CollectorExt; /// use tracing_subscriber::Registry; /// /// // Use the tracing subscriber `Registry`, or any other subscriber @@ -53,7 +53,7 @@ where /// ``` pub fn layer() -> OpenTelemetryLayer where - S: Subscriber + for<'span> LookupSpan<'span>, + S: Collect + for<'span> LookupSpan<'span>, { OpenTelemetryLayer::default() } @@ -261,7 +261,7 @@ impl<'a> field::Visit for SpanAttributeVisitor<'a> { impl OpenTelemetryLayer where - S: Subscriber + for<'span> LookupSpan<'span>, + S: Collect + for<'span> LookupSpan<'span>, T: api::Tracer + PreSampledTracer + 'static, { /// Set the [`Tracer`] that this layer will use to produce and track @@ -275,7 +275,7 @@ where /// ```rust,no_run /// use opentelemetry::{api::Provider, sdk}; /// use tracing_opentelemetry::OpenTelemetryLayer; - /// use tracing_subscriber::layer::SubscriberExt; + /// use tracing_subscriber::subscribe::CollectorExt; /// use tracing_subscriber::Registry; /// /// // Create a jaeger exporter for a `trace-demo` service. @@ -325,7 +325,7 @@ where /// /// ```rust,no_run /// use opentelemetry::{api::Provider, sdk}; - /// use tracing_subscriber::layer::SubscriberExt; + /// use tracing_subscriber::subscribe::CollectorExt; /// use tracing_subscriber::Registry; /// /// // Create a jaeger exporter for a `trace-demo` service. @@ -424,9 +424,9 @@ where } } -impl Layer for OpenTelemetryLayer +impl Subscribe for OpenTelemetryLayer where - S: Subscriber + for<'span> LookupSpan<'span>, + S: Collect + for<'span> LookupSpan<'span>, T: api::Tracer + PreSampledTracer + 'static, { /// Creates an [OpenTelemetry `Span`] for the corresponding [tracing `Span`]. @@ -627,7 +627,7 @@ mod tests { let tracer = TestTracer(Arc::new(Mutex::new(None))); let subscriber = tracing_subscriber::registry().with(layer().with_tracer(tracer.clone())); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { tracing::debug_span!("static_name", otel.name = dynamic_name.as_str()); }); @@ -640,7 +640,7 @@ mod tests { let tracer = TestTracer(Arc::new(Mutex::new(None))); let subscriber = tracing_subscriber::registry().with(layer().with_tracer(tracer.clone())); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { tracing::debug_span!("request", otel.kind = "Server"); }); @@ -661,7 +661,7 @@ mod tests { ))); let _g = existing_cx.attach(); - tracing::subscriber::with_default(subscriber, || { + tracing::collect::with_default(subscriber, || { tracing::debug_span!("request", otel.kind = "Server"); }); diff --git a/tracing-opentelemetry/src/lib.rs b/tracing-opentelemetry/src/lib.rs index 81aa096973..0ad074ecbf 100644 --- a/tracing-opentelemetry/src/lib.rs +++ b/tracing-opentelemetry/src/lib.rs @@ -53,7 +53,7 @@ //! ``` //! use opentelemetry::{api::Provider, sdk}; //! use tracing::{error, span}; -//! use tracing_subscriber::layer::SubscriberExt; +//! use tracing_subscriber::subscribe::CollectorExt; //! use tracing_subscriber::Registry; //! //! // Create a new tracer @@ -65,7 +65,7 @@ //! let subscriber = Registry::default().with(telemetry); //! //! // Trace executed code -//! tracing::subscriber::with_default(subscriber, || { +//! tracing::collect::with_default(subscriber, || { //! // Spans will be sent to the configured OpenTelemetry exporter //! let root = span!(tracing::Level::TRACE, "app_start", work_units = 2); //! let _enter = root.enter(); @@ -98,7 +98,7 @@ )] #![cfg_attr(docsrs, deny(broken_intra_doc_links))] -/// Implementation of the trace::Layer as a source of OpenTelemetry data. +/// Implementation of the trace::Subscriber as a source of OpenTelemetry data. mod layer; /// Span extension which enables OpenTelemetry context management. mod span_ext; diff --git a/tracing-opentelemetry/src/span_ext.rs b/tracing-opentelemetry/src/span_ext.rs index c0da7aef82..389da6d067 100644 --- a/tracing-opentelemetry/src/span_ext.rs +++ b/tracing-opentelemetry/src/span_ext.rs @@ -74,9 +74,9 @@ pub trait OpenTelemetrySpanExt { impl OpenTelemetrySpanExt for tracing::Span { fn set_parent(&self, parent_context: &api::Context) { - self.with_subscriber(move |(id, subscriber)| { - if let Some(get_context) = subscriber.downcast_ref::() { - get_context.with_context(subscriber, id, move |builder, _tracer| { + self.with_collector(move |(id, collector)| { + if let Some(get_context) = collector.downcast_ref::() { + get_context.with_context(collector, id, move |builder, _tracer| { builder.parent_context = parent_context.remote_span_context().cloned() }); } @@ -85,9 +85,9 @@ impl OpenTelemetrySpanExt for tracing::Span { fn context(&self) -> api::Context { let mut span_context = None; - self.with_subscriber(|(id, subscriber)| { - if let Some(get_context) = subscriber.downcast_ref::() { - get_context.with_context(subscriber, id, |builder, tracer| { + self.with_collector(|(id, collector)| { + if let Some(get_context) = collector.downcast_ref::() { + get_context.with_context(collector, id, |builder, tracer| { span_context = Some(tracer.sampled_span_context(builder)); }) } diff --git a/tracing-serde/src/lib.rs b/tracing-serde/src/lib.rs index 266725e66d..3f293b85bf 100644 --- a/tracing-serde/src/lib.rs +++ b/tracing-serde/src/lib.rs @@ -20,7 +20,7 @@ //! `tracing` gives us machine-readable structured diagnostic //! information. This lets us interact with diagnostic data //! programmatically. With `tracing-serde`, you can implement a -//! `Subscriber` to serialize your `tracing` types and make use of the +//! `Collector` to serialize your `tracing` types and make use of the //! existing ecosystem of `serde` serializers to talk with distributed //! tracing systems. //! @@ -61,11 +61,11 @@ //! //! For the full example, please see the [examples](../examples) folder. //! -//! Implement a `Subscriber` to format the serialization of `tracing` +//! Implement a `Collector` to format the serialization of `tracing` //! types how you'd like. //! //! ```rust -//! # use tracing_core::{Subscriber, Metadata, Event}; +//! # use tracing_core::{Collect, Metadata, Event}; //! # use tracing_core::span::{Attributes, Id, Record}; //! # use std::sync::atomic::{AtomicUsize, Ordering}; //! use tracing_serde::AsSerde; @@ -75,7 +75,7 @@ //! next_id: AtomicUsize, // you need to assign span IDs, so you need a counter //! } //! -//! impl Subscriber for JsonSubscriber { +//! impl Collect for JsonSubscriber { //! //! fn new_span(&self, attrs: &Attributes<'_>) -> Id { //! let id = self.next_id.fetch_add(1, Ordering::Relaxed); @@ -105,7 +105,7 @@ //! } //! ``` //! -//! After you implement your `Subscriber`, you can use your `tracing` +//! After you implement your `Collector`, you can use your `tracing` //! subscriber (`JsonSubscriber` in the above example) to record serialized //! trace data. //! diff --git a/tracing-subscriber/Cargo.toml b/tracing-subscriber/Cargo.toml index e79ca3d17a..e5c93916e2 100644 --- a/tracing-subscriber/Cargo.toml +++ b/tracing-subscriber/Cargo.toml @@ -54,7 +54,7 @@ tracing-serde = { path = "../tracing-serde", version = "0.2", optional = true } parking_lot = { version = ">= 0.7, <= 0.11", optional = true } # registry -sharded-slab = { version = "^0.0.9", optional = true } +sharded-slab = { version = "0.1.0", optional = true } thread_local = { version = "1.0.1", optional = true } [dev-dependencies] diff --git a/tracing-subscriber/benches/filter.rs b/tracing-subscriber/benches/filter.rs index 91ab9c91d2..a5ed1c6bf5 100644 --- a/tracing-subscriber/benches/filter.rs +++ b/tracing-subscriber/benches/filter.rs @@ -1,6 +1,6 @@ use criterion::{criterion_group, criterion_main, Criterion}; use std::time::Duration; -use tracing::{dispatcher::Dispatch, span, Event, Id, Metadata}; +use tracing::{dispatch::Dispatch, span, Event, Id, Metadata}; use tracing_subscriber::{prelude::*, EnvFilter}; mod support; @@ -9,7 +9,7 @@ use support::MultithreadedBench; /// A subscriber that is enabled but otherwise does nothing. struct EnabledSubscriber; -impl tracing::Subscriber for EnabledSubscriber { +impl tracing::Collect for EnabledSubscriber { fn new_span(&self, span: &span::Attributes<'_>) -> Id { let _ = span; Id::from_u64(0xDEAD_FACE) @@ -45,7 +45,7 @@ fn bench_static(c: &mut Criterion) { let mut group = c.benchmark_group("static"); group.bench_function("baseline_single_threaded", |b| { - tracing::subscriber::with_default(EnabledSubscriber, || { + tracing::collect::with_default(EnabledSubscriber, || { b.iter(|| { tracing::info!(target: "static_filter", "hi"); tracing::debug!(target: "static_filter", "hi"); @@ -58,7 +58,7 @@ fn bench_static(c: &mut Criterion) { let filter = "static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info!(target: "static_filter", "hi"); tracing::debug!(target: "static_filter", "hi"); @@ -71,7 +71,7 @@ fn bench_static(c: &mut Criterion) { let filter = "static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info!(target: "static_filter", "hi"); }) @@ -81,7 +81,7 @@ fn bench_static(c: &mut Criterion) { let filter = "foo=debug,bar=trace,baz=error,quux=warn,static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info!(target: "static_filter", "hi"); }) @@ -91,7 +91,7 @@ fn bench_static(c: &mut Criterion) { let filter = "static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::debug!(target: "static_filter", "hi"); }) @@ -101,7 +101,7 @@ fn bench_static(c: &mut Criterion) { let filter = "foo=debug,bar=info,baz=error,quux=warn,static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::trace!(target: "static_filter", "hi"); }) @@ -109,7 +109,7 @@ fn bench_static(c: &mut Criterion) { }); group.bench_function("disabled_one", |b| { let filter = "foo=info".parse::().expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info!(target: "static_filter", "hi"); }) @@ -119,7 +119,7 @@ fn bench_static(c: &mut Criterion) { let filter = "foo=debug,bar=trace,baz=error,quux=warn,whibble=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info!(target: "static_filter", "hi"); }) @@ -185,7 +185,7 @@ fn bench_dynamic(c: &mut Criterion) { let mut group = c.benchmark_group("dynamic"); group.bench_function("baseline_single_threaded", |b| { - tracing::subscriber::with_default(EnabledSubscriber, || { + tracing::collect::with_default(EnabledSubscriber, || { b.iter(|| { tracing::info_span!("foo").in_scope(|| { tracing::info!("hi"); @@ -200,7 +200,7 @@ fn bench_dynamic(c: &mut Criterion) { }); group.bench_function("single_threaded", |b| { let filter = "[foo]=trace".parse::().expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info_span!("foo").in_scope(|| { tracing::info!("hi"); @@ -286,7 +286,7 @@ fn bench_mixed(c: &mut Criterion) { let filter = "[foo]=trace,bar[quux]=debug,[{baz}]=debug,asdf=warn,wibble=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info!(target: "static_filter", "hi"); }) @@ -296,7 +296,7 @@ fn bench_mixed(c: &mut Criterion) { let filter = "[foo]=info,bar[quux]=debug,asdf=warn,static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::trace!(target: "static_filter", "hi"); }) diff --git a/tracing-subscriber/benches/filter_log.rs b/tracing-subscriber/benches/filter_log.rs index 4dcf3b4ec0..903c4f80aa 100644 --- a/tracing-subscriber/benches/filter_log.rs +++ b/tracing-subscriber/benches/filter_log.rs @@ -1,6 +1,6 @@ use criterion::{criterion_group, criterion_main, Criterion}; use std::time::Duration; -use tracing::{dispatcher::Dispatch, span, Event, Id, Metadata}; +use tracing::{dispatch::Dispatch, span, Event, Id, Metadata}; use tracing_subscriber::{prelude::*, EnvFilter}; mod support; @@ -9,7 +9,7 @@ use support::MultithreadedBench; /// A subscriber that is enabled but otherwise does nothing. struct EnabledSubscriber; -impl tracing::Subscriber for EnabledSubscriber { +impl tracing::Collect for EnabledSubscriber { fn new_span(&self, span: &span::Attributes<'_>) -> Id { let _ = span; Id::from_u64(0xDEAD_FACE) @@ -47,7 +47,7 @@ fn bench_static(c: &mut Criterion) { let mut group = c.benchmark_group("log/static"); group.bench_function("baseline_single_threaded", |b| { - tracing::subscriber::with_default(EnabledSubscriber, || { + tracing::collect::with_default(EnabledSubscriber, || { b.iter(|| { log::info!(target: "static_filter", "hi"); log::debug!(target: "static_filter", "hi"); @@ -60,7 +60,7 @@ fn bench_static(c: &mut Criterion) { let filter = "static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::info!(target: "static_filter", "hi"); log::debug!(target: "static_filter", "hi"); @@ -73,7 +73,7 @@ fn bench_static(c: &mut Criterion) { let filter = "static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::info!(target: "static_filter", "hi"); }) @@ -83,7 +83,7 @@ fn bench_static(c: &mut Criterion) { let filter = "foo=debug,bar=trace,baz=error,quux=warn,static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::info!(target: "static_filter", "hi"); }) @@ -93,7 +93,7 @@ fn bench_static(c: &mut Criterion) { let filter = "static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::debug!(target: "static_filter", "hi"); }) @@ -103,7 +103,7 @@ fn bench_static(c: &mut Criterion) { let filter = "foo=debug,bar=info,baz=error,quux=warn,static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::trace!(target: "static_filter", "hi"); }) @@ -111,7 +111,7 @@ fn bench_static(c: &mut Criterion) { }); group.bench_function("disabled_one", |b| { let filter = "foo=info".parse::().expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::info!(target: "static_filter", "hi"); }) @@ -121,7 +121,7 @@ fn bench_static(c: &mut Criterion) { let filter = "foo=debug,bar=trace,baz=error,quux=warn,whibble=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::info!(target: "static_filter", "hi"); }) @@ -189,7 +189,7 @@ fn bench_dynamic(c: &mut Criterion) { let mut group = c.benchmark_group("log/dynamic"); group.bench_function("baseline_single_threaded", |b| { - tracing::subscriber::with_default(EnabledSubscriber, || { + tracing::collect::with_default(EnabledSubscriber, || { b.iter(|| { tracing::info_span!("foo").in_scope(|| { log::info!("hi"); @@ -204,7 +204,7 @@ fn bench_dynamic(c: &mut Criterion) { }); group.bench_function("single_threaded", |b| { let filter = "[foo]=trace".parse::().expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { tracing::info_span!("foo").in_scope(|| { log::info!("hi"); @@ -293,7 +293,7 @@ fn bench_mixed(c: &mut Criterion) { let filter = "[foo]=trace,bar[quux]=debug,[{baz}]=debug,asdf=warn,wibble=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::info!(target: "static_filter", "hi"); }) @@ -303,7 +303,7 @@ fn bench_mixed(c: &mut Criterion) { let filter = "[foo]=info,bar[quux]=debug,asdf=warn,static_filter=info" .parse::() .expect("should parse"); - tracing::subscriber::with_default(EnabledSubscriber.with(filter), || { + tracing::collect::with_default(EnabledSubscriber.with(filter), || { b.iter(|| { log::trace!(target: "static_filter", "hi"); }) diff --git a/tracing-subscriber/benches/fmt.rs b/tracing-subscriber/benches/fmt.rs index 754401a9f9..390b19a249 100644 --- a/tracing-subscriber/benches/fmt.rs +++ b/tracing-subscriber/benches/fmt.rs @@ -6,9 +6,9 @@ use support::MultithreadedBench; /// A fake writer that doesn't actually do anything. /// -/// We want to measure the subscriber's overhead, *not* the performance of +/// We want to measure the collectors's overhead, *not* the performance of /// stdout/file writers. Using a no-op Write implementation lets us only measure -/// the subscriber's overhead. +/// the collectors's overhead. struct NoWriter; impl io::Write for NoWriter { @@ -30,7 +30,7 @@ impl NoWriter { fn bench_new_span(c: &mut Criterion) { bench_thrpt(c, "new_span", |group, i| { group.bench_with_input(BenchmarkId::new("single_thread", i), i, |b, &i| { - tracing::dispatcher::with_default(&mk_dispatch(), || { + tracing::dispatch::with_default(&mk_dispatch(), || { b.iter(|| { for n in 0..i { let _span = tracing::info_span!("span", n); @@ -41,8 +41,9 @@ fn bench_new_span(c: &mut Criterion) { group.bench_with_input(BenchmarkId::new("multithreaded", i), i, |b, &i| { b.iter_custom(|iters| { let mut total = Duration::from_secs(0); + let dispatch = mk_dispatch(); for _ in 0..iters { - let bench = MultithreadedBench::new(mk_dispatch()); + let bench = MultithreadedBench::new(dispatch.clone()); let elapsed = bench .thread(move || { for n in 0..i { @@ -86,16 +87,17 @@ fn bench_thrpt(c: &mut Criterion, name: &'static str, mut f: impl FnMut(&mut Gro } fn mk_dispatch() -> tracing::Dispatch { - let subscriber = tracing_subscriber::FmtSubscriber::builder() + let collector = tracing_subscriber::fmt::Collector::builder() .with_writer(NoWriter::new) .finish(); - tracing::Dispatch::new(subscriber) + tracing::Dispatch::new(collector) } fn bench_event(c: &mut Criterion) { bench_thrpt(c, "event", |group, i| { group.bench_with_input(BenchmarkId::new("root/single_threaded", i), i, |b, &i| { - tracing::dispatcher::with_default(&mk_dispatch(), || { + let dispatch = mk_dispatch(); + tracing::dispatch::with_default(&dispatch, || { b.iter(|| { for n in 0..i { tracing::info!(n); @@ -106,8 +108,9 @@ fn bench_event(c: &mut Criterion) { group.bench_with_input(BenchmarkId::new("root/multithreaded", i), i, |b, &i| { b.iter_custom(|iters| { let mut total = Duration::from_secs(0); + let dispatch = mk_dispatch(); for _ in 0..iters { - let bench = MultithreadedBench::new(mk_dispatch()); + let bench = MultithreadedBench::new(dispatch.clone()); let elapsed = bench .thread(move || { for n in 0..i { @@ -139,7 +142,7 @@ fn bench_event(c: &mut Criterion) { BenchmarkId::new("unique_parent/single_threaded", i), i, |b, &i| { - tracing::dispatcher::with_default(&mk_dispatch(), || { + tracing::dispatch::with_default(&mk_dispatch(), || { let span = tracing::info_span!("unique_parent", foo = false); let _guard = span.enter(); b.iter(|| { @@ -156,8 +159,9 @@ fn bench_event(c: &mut Criterion) { |b, &i| { b.iter_custom(|iters| { let mut total = Duration::from_secs(0); + let dispatch = mk_dispatch(); for _ in 0..iters { - let bench = MultithreadedBench::new(mk_dispatch()); + let bench = MultithreadedBench::new(dispatch.clone()); let elapsed = bench .thread_with_setup(move |start| { let span = tracing::info_span!("unique_parent", foo = false); @@ -203,13 +207,13 @@ fn bench_event(c: &mut Criterion) { i, |b, &i| { b.iter_custom(|iters| { + let dispatch = mk_dispatch(); let mut total = Duration::from_secs(0); for _ in 0..iters { - let dispatch = mk_dispatch(); - let parent = tracing::dispatcher::with_default(&dispatch, || { + let parent = tracing::dispatch::with_default(&dispatch, || { tracing::info_span!("shared_parent", foo = "hello world") }); - let bench = MultithreadedBench::new(dispatch); + let bench = MultithreadedBench::new(dispatch.clone()); let parent2 = parent.clone(); bench.thread_with_setup(move |start| { let _guard = parent2.enter(); @@ -249,6 +253,77 @@ fn bench_event(c: &mut Criterion) { }) }, ); + group.bench_with_input( + BenchmarkId::new("multi-parent/multithreaded", i), + i, + |b, &i| { + b.iter_custom(|iters| { + let dispatch = mk_dispatch(); + let mut total = Duration::from_secs(0); + for _ in 0..iters { + let parent = tracing::dispatch::with_default(&dispatch, || { + tracing::info_span!("multiparent", foo = "hello world") + }); + let bench = MultithreadedBench::new(dispatch.clone()); + let parent2 = parent.clone(); + bench.thread_with_setup(move |start| { + let _guard = parent2.enter(); + start.wait(); + let mut span = tracing::info_span!("parent"); + for n in 0..i { + let s = tracing::info_span!(parent: &span, "parent2", n, i); + s.in_scope(|| { + tracing::info!(n); + }); + span = s; + } + }); + let parent2 = parent.clone(); + bench.thread_with_setup(move |start| { + let _guard = parent2.enter(); + start.wait(); + let mut span = tracing::info_span!("parent"); + for n in 0..i { + let s = tracing::info_span!(parent: &span, "parent2", n, i); + s.in_scope(|| { + tracing::info!(n); + }); + span = s; + } + }); + let parent2 = parent.clone(); + bench.thread_with_setup(move |start| { + let _guard = parent2.enter(); + start.wait(); + let mut span = tracing::info_span!("parent"); + for n in 0..i { + let s = tracing::info_span!(parent: &span, "parent2", n, i); + s.in_scope(|| { + tracing::info!(n); + }); + span = s; + } + }); + let parent2 = parent.clone(); + bench.thread_with_setup(move |start| { + let _guard = parent2.enter(); + start.wait(); + let mut span = tracing::info_span!("parent"); + for n in 0..i { + let s = tracing::info_span!(parent: &span, "parent2", n, i); + s.in_scope(|| { + tracing::info!(n); + }); + span = s; + } + }); + let elapsed = bench.run(); + total += elapsed; + } + total + }) + }, + ); }); } diff --git a/tracing-subscriber/benches/support/mod.rs b/tracing-subscriber/benches/support/mod.rs index 25e9e7e229..57fd0727c9 100644 --- a/tracing-subscriber/benches/support/mod.rs +++ b/tracing-subscriber/benches/support/mod.rs @@ -3,7 +3,7 @@ use std::{ thread, time::{Duration, Instant}, }; -use tracing::dispatcher::Dispatch; +use tracing::dispatch::Dispatch; #[derive(Clone)] pub(super) struct MultithreadedBench { @@ -32,7 +32,7 @@ impl MultithreadedBench { let this = self.clone(); thread::spawn(move || { let dispatch = this.dispatch.clone(); - tracing::dispatcher::with_default(&dispatch, move || { + tracing::dispatch::with_default(&dispatch, move || { f(&*this.start); this.end.wait(); }) diff --git a/tracing-subscriber/src/field/mod.rs b/tracing-subscriber/src/field/mod.rs index 0caebb6fca..4970b277ce 100644 --- a/tracing-subscriber/src/field/mod.rs +++ b/tracing-subscriber/src/field/mod.rs @@ -309,7 +309,7 @@ pub(in crate::field) mod test_util { }; impl Callsite for TestCallsite1 { - fn set_interest(&self, _: tracing_core::subscriber::Interest) { + fn set_interest(&self, _: tracing_core::collect::Interest) { unimplemented!() } diff --git a/tracing-subscriber/src/filter/env/mod.rs b/tracing-subscriber/src/filter/env/mod.rs index f1c71416e0..82db5fe1b6 100644 --- a/tracing-subscriber/src/filter/env/mod.rs +++ b/tracing-subscriber/src/filter/env/mod.rs @@ -1,4 +1,4 @@ -//! A `Layer` that enables or disables spans and events based on a set of +//! A `Subscriber` that enables or disables spans and events based on a set of //! filtering directives. // these are publicly re-exported, but the compiler doesn't realize @@ -13,19 +13,18 @@ mod field; use crate::{ filter::LevelFilter, - layer::{Context, Layer}, + subscribe::{Context, Subscribe}, sync::RwLock, }; use std::{cell::RefCell, collections::HashMap, env, error::Error, fmt, str::FromStr}; use tracing_core::{ callsite, + collect::{Collect, Interest}, field::Field, - span, - subscriber::{Interest, Subscriber}, - Metadata, + span, Metadata, }; -/// A [`Layer`] which filters spans and events based on a set of filter +/// A [`Subscriber`] which filters spans and events based on a set of filter /// directives. /// /// # Directives @@ -88,7 +87,7 @@ use tracing_core::{ /// - which has a field named `name` with value `bob`, /// - at _any_ level. /// -/// [`Layer`]: ../layer/trait.Layer.html +/// [`Subscriber`]: ../layer/trait.Subscriber.html /// [`env_logger`]: https://docs.rs/env_logger/0.7.1/env_logger/#enabling-logging /// [`Span`]: https://docs.rs/tracing-core/latest/tracing_core/span/index.html /// [fields]: https://docs.rs/tracing-core/latest/tracing_core/struct.Field.html @@ -367,7 +366,7 @@ impl EnvFilter { } } -impl Layer for EnvFilter { +impl Subscribe for EnvFilter { fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest { if self.has_dynamics && metadata.is_span() { // If this metadata describes a span, first, check if there is a @@ -576,11 +575,11 @@ mod tests { use tracing_core::field::FieldSet; use tracing_core::*; - struct NoSubscriber; - impl Subscriber for NoSubscriber { + struct NoCollector; + impl Collect for NoCollector { #[inline] - fn register_callsite(&self, _: &'static Metadata<'static>) -> subscriber::Interest { - subscriber::Interest::always() + fn register_callsite(&self, _: &'static Metadata<'static>) -> collect::Interest { + collect::Interest::always() } fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { span::Id::from_u64(0xDEAD) @@ -607,7 +606,7 @@ mod tests { #[test] fn callsite_enabled_no_span_directive() { - let filter = EnvFilter::new("app=debug").with_subscriber(NoSubscriber); + let filter = EnvFilter::new("app=debug").with_collector(NoCollector); static META: &Metadata<'static> = &Metadata::new( "mySpan", "app", @@ -625,7 +624,7 @@ mod tests { #[test] fn callsite_off() { - let filter = EnvFilter::new("app=off").with_subscriber(NoSubscriber); + let filter = EnvFilter::new("app=off").with_collector(NoCollector); static META: &Metadata<'static> = &Metadata::new( "mySpan", "app", @@ -643,7 +642,7 @@ mod tests { #[test] fn callsite_enabled_includes_span_directive() { - let filter = EnvFilter::new("app[mySpan]=debug").with_subscriber(NoSubscriber); + let filter = EnvFilter::new("app[mySpan]=debug").with_collector(NoCollector); static META: &Metadata<'static> = &Metadata::new( "mySpan", "app", @@ -662,7 +661,7 @@ mod tests { #[test] fn callsite_enabled_includes_span_directive_field() { let filter = - EnvFilter::new("app[mySpan{field=\"value\"}]=debug").with_subscriber(NoSubscriber); + EnvFilter::new("app[mySpan{field=\"value\"}]=debug").with_collector(NoCollector); static META: &Metadata<'static> = &Metadata::new( "mySpan", "app", @@ -681,7 +680,7 @@ mod tests { #[test] fn callsite_enabled_includes_span_directive_multiple_fields() { let filter = EnvFilter::new("app[mySpan{field=\"value\",field2=2}]=debug") - .with_subscriber(NoSubscriber); + .with_collector(NoCollector); static META: &Metadata<'static> = &Metadata::new( "mySpan", "app", diff --git a/tracing-subscriber/src/filter/level.rs b/tracing-subscriber/src/filter/level.rs index 0c981f3475..4cd679d1ae 100644 --- a/tracing-subscriber/src/filter/level.rs +++ b/tracing-subscriber/src/filter/level.rs @@ -1,5 +1,5 @@ use tracing_core::{ - subscriber::{Interest, Subscriber}, + collect::{Collect, Interest}, Metadata, }; @@ -8,7 +8,7 @@ pub use tracing_core::metadata::{LevelFilter, ParseLevelFilterError as ParseErro // === impl LevelFilter === -impl crate::Layer for LevelFilter { +impl crate::Subscribe for LevelFilter { fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest { if self >= metadata.level() { Interest::always() @@ -17,7 +17,7 @@ impl crate::Layer for LevelFilter { } } - fn enabled(&self, metadata: &Metadata<'_>, _: crate::layer::Context<'_, S>) -> bool { + fn enabled(&self, metadata: &Metadata<'_>, _: crate::subscribe::Context<'_, S>) -> bool { self >= metadata.level() } diff --git a/tracing-subscriber/src/filter/mod.rs b/tracing-subscriber/src/filter/mod.rs index 5bffe8b893..345f640c1e 100644 --- a/tracing-subscriber/src/filter/mod.rs +++ b/tracing-subscriber/src/filter/mod.rs @@ -1,7 +1,7 @@ -//! [`Layer`]s that control which spans and events are enabled by the wrapped +//! [`Subscriber`]s that control which spans and events are enabled by the wrapped //! subscriber. //! -//! [`Layer`]: ../layer/trait.Layer.html +//! [`Subscriber`]: ../layer/trait.Subscriber.html #[cfg(feature = "env-filter")] mod env; mod level; diff --git a/tracing-subscriber/src/fmt/fmt_layer.rs b/tracing-subscriber/src/fmt/fmt_subscriber.rs similarity index 80% rename from tracing-subscriber/src/fmt/fmt_layer.rs rename to tracing-subscriber/src/fmt/fmt_subscriber.rs index 0b48ca1da8..27f2dc245b 100644 --- a/tracing-subscriber/src/fmt/fmt_layer.rs +++ b/tracing-subscriber/src/fmt/fmt_subscriber.rs @@ -1,45 +1,45 @@ use crate::{ field::RecordFields, fmt::{format, FormatEvent, FormatFields, MakeWriter, TestWriter}, - layer::{self, Context, Scope}, registry::{LookupSpan, SpanRef}, + subscribe::{self, Context, Scope}, }; use format::{FmtSpan, TimingDisplay}; use std::{any::TypeId, cell::RefCell, fmt, io, marker::PhantomData, ops::Deref, time::Instant}; use tracing_core::{ field, span::{Attributes, Id, Record}, - Event, Metadata, Subscriber, + Collect, Event, Metadata, }; -/// A [`Layer`] that logs formatted representations of `tracing` events. +/// A [`Subscriber`] that logs formatted representations of `tracing` events. /// /// ## Examples /// -/// Constructing a layer with the default configuration: +/// Constructing a subscriber with the default configuration: /// /// ```rust /// use tracing_subscriber::{fmt, Registry}; /// use tracing_subscriber::prelude::*; /// -/// let subscriber = Registry::default() -/// .with(fmt::Layer::default()); +/// let collector = Registry::default() +/// .with(fmt::Subscriber::default()); /// -/// tracing::subscriber::set_global_default(subscriber).unwrap(); +/// tracing::collect::set_global_default(collector).unwrap(); /// ``` /// -/// Overriding the layer's behavior: +/// Overriding the subscriber's behavior: /// /// ```rust /// use tracing_subscriber::{fmt, Registry}; /// use tracing_subscriber::prelude::*; /// -/// let fmt_layer = fmt::layer() +/// let fmt_subscriber = fmt::subscriber() /// .with_target(false) // don't include event targets when logging /// .with_level(false); // don't include event levels when logging /// -/// let subscriber = Registry::default().with(fmt_layer); -/// # tracing::subscriber::set_global_default(subscriber).unwrap(); +/// let collector = Registry::default().with(fmt_subscriber); +/// # tracing::collect::set_global_default(collector).unwrap(); /// ``` /// /// Setting a custom event formatter: @@ -49,16 +49,16 @@ use tracing_core::{ /// use tracing_subscriber::prelude::*; /// /// let fmt = format().with_timer(time::Uptime::default()); -/// let fmt_layer = fmt::layer() +/// let fmt_layer = fmt::subscriber() /// .event_format(fmt) /// .with_target(false); -/// # let subscriber = fmt_layer.with_subscriber(tracing_subscriber::registry::Registry::default()); -/// # tracing::subscriber::set_global_default(subscriber).unwrap(); +/// # let subscriber = fmt_layer.with_collector(tracing_subscriber::registry::Registry::default()); +/// # tracing::collect::set_global_default(subscriber).unwrap(); /// ``` /// -/// [`Layer`]: ../layer/trait.Layer.html +/// [`Subscriber`]: ../layer/trait.Subscriber.html #[derive(Debug)] -pub struct Layer< +pub struct Subscriber< S, N = format::DefaultFields, E = format::Format, @@ -71,44 +71,17 @@ pub struct Layer< _inner: PhantomData, } -/// A builder for [`Layer`](struct.Layer.html) that logs formatted representations of `tracing` -/// events and spans. -/// -/// **Note**: As of `tracing-subscriber` 0.2.4, the separate builder type is now -/// deprecated, as the `Layer` type itself supports all the builder's -/// configuration methods. This is now an alias for `Layer`. -#[deprecated( - since = "0.2.4", - note = "a separate layer builder type is not necessary, `Layer`s now support configuration" -)] -pub type LayerBuilder< - S, - N = format::DefaultFields, - E = format::Format, - W = fn() -> io::Stdout, -> = Layer; - -impl Layer { - /// Returns a new [`LayerBuilder`](type.LayerBuilder.html) for configuring a `Layer`. - #[deprecated( - since = "0.2.4", - note = "a separate layer builder is not necessary, use `Layer::new`/`Layer::default` instead" - )] - #[allow(deprecated)] - pub fn builder() -> LayerBuilder { - Layer::default() - } - - /// Returns a new [`Layer`](struct.Layer.html) with the default configuration. +impl Subscriber { + /// Returns a new [`Subscriber`](struct.Subscriber.html) with the default configuration. pub fn new() -> Self { Self::default() } } // This needs to be a seperate impl block because they place different bounds on the type parameters. -impl Layer +impl Subscriber where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, N: for<'writer> FormatFields<'writer> + 'static, W: MakeWriter + 'static, { @@ -125,20 +98,20 @@ where /// ```rust /// use tracing_subscriber::fmt::{self, format}; /// - /// let layer = fmt::layer() + /// let layer = fmt::subscriber() /// .event_format(format().compact()); /// # // this is necessary for type inference. - /// # use tracing_subscriber::Layer as _; - /// # let _ = layer.with_subscriber(tracing_subscriber::registry::Registry::default()); + /// # use tracing_subscriber::Subscribe as _; + /// # let _ = layer.with_collector(tracing_subscriber::registry::Registry::default()); /// ``` /// [`FormatEvent`]: ./format/trait.FormatEvent.html /// [`FmtContext`]: ./struct.FmtContext.html /// [`Event`]: https://docs.rs/tracing/latest/tracing/struct.Event.html - pub fn event_format(self, e: E2) -> Layer + pub fn event_format(self, e: E2) -> Subscriber where E2: FormatEvent + 'static, { - Layer { + Subscriber { fmt_fields: self.fmt_fields, fmt_event: e, fmt_span: self.fmt_span, @@ -149,8 +122,8 @@ where } // This needs to be a seperate impl block because they place different bounds on the type parameters. -impl Layer { - /// Sets the [`MakeWriter`] that the [`Layer`] being built will use to write events. +impl Subscriber { + /// Sets the [`MakeWriter`] that the [`Subscriber`] being built will use to write events. /// /// # Examples /// @@ -160,20 +133,20 @@ impl Layer { /// use std::io; /// use tracing_subscriber::fmt; /// - /// let layer = fmt::layer() + /// let layer = fmt::subscriber() /// .with_writer(io::stderr); /// # // this is necessary for type inference. - /// # use tracing_subscriber::Layer as _; - /// # let _ = layer.with_subscriber(tracing_subscriber::registry::Registry::default()); + /// # use tracing_subscriber::Subscribe as _; + /// # let _ = layer.with_collector(tracing_subscriber::registry::Registry::default()); /// ``` /// /// [`MakeWriter`]: ../fmt/trait.MakeWriter.html - /// [`Layer`]: ../layer/trait.Layer.html - pub fn with_writer(self, make_writer: W2) -> Layer + /// [`Subscriber`]: ../layer/trait.Subscriber.html + pub fn with_writer(self, make_writer: W2) -> Subscriber where W2: MakeWriter + 'static, { - Layer { + Subscriber { fmt_fields: self.fmt_fields, fmt_event: self.fmt_event, fmt_span: self.fmt_span, @@ -195,17 +168,17 @@ impl Layer { /// use std::io; /// use tracing_subscriber::fmt; /// - /// let layer = fmt::layer() + /// let layer = fmt::subscriber() /// .with_test_writer(); /// # // this is necessary for type inference. - /// # use tracing_subscriber::Layer as _; - /// # let _ = layer.with_subscriber(tracing_subscriber::registry::Registry::default()); + /// # use tracing_subscriber::Subscribe as _; + /// # let _ = layer.with_collector(tracing_subscriber::registry::Registry::default()); /// ``` /// [capturing]: /// https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output /// [`TestWriter`]: writer/struct.TestWriter.html - pub fn with_test_writer(self) -> Layer { - Layer { + pub fn with_test_writer(self) -> Subscriber { + Subscriber { fmt_fields: self.fmt_fields, fmt_event: self.fmt_event, fmt_span: self.fmt_span, @@ -215,7 +188,7 @@ impl Layer { } } -impl Layer, W> +impl Subscriber, W> where N: for<'writer> FormatFields<'writer> + 'static, { @@ -230,8 +203,8 @@ where /// [`timer`]: ./time/trait.FormatTime.html /// [`ChronoUtc`]: ./time/struct.ChronoUtc.html /// [`ChronoLocal`]: ./time/struct.ChronoLocal.html - pub fn with_timer(self, timer: T2) -> Layer, W> { - Layer { + pub fn with_timer(self, timer: T2) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_timer(timer), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span, @@ -241,8 +214,8 @@ where } /// Do not emit timestamps with spans and event. - pub fn without_time(self) -> Layer, W> { - Layer { + pub fn without_time(self) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.without_time(), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span.without_time(), @@ -272,13 +245,13 @@ where /// described above. /// /// Note that the generated events will only be part of the log output by - /// this formatter; they will not be recorded by other `Subscriber`s or by - /// `Layer`s added to this subscriber. + /// this formatter; they will not be recorded by other `Collector`s or by + /// `Subscriber`s added to this subscriber. /// /// [lifecycle]: https://docs.rs/tracing/latest/tracing/span/index.html#the-span-lifecycle /// [time]: #method.without_time pub fn with_span_events(self, kind: FmtSpan) -> Self { - Layer { + Subscriber { fmt_event: self.fmt_event, fmt_fields: self.fmt_fields, fmt_span: self.fmt_span.with_kind(kind), @@ -290,8 +263,8 @@ where /// Enable ANSI encoding for formatted events. #[cfg(feature = "ansi")] #[cfg_attr(docsrs, doc(cfg(feature = "ansi")))] - pub fn with_ansi(self, ansi: bool) -> Layer, W> { - Layer { + pub fn with_ansi(self, ansi: bool) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_ansi(ansi), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span, @@ -301,8 +274,8 @@ where } /// Sets whether or not an event's target is displayed. - pub fn with_target(self, display_target: bool) -> Layer, W> { - Layer { + pub fn with_target(self, display_target: bool) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_target(display_target), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span, @@ -312,8 +285,8 @@ where } /// Sets whether or not an event's level is displayed. - pub fn with_level(self, display_level: bool) -> Layer, W> { - Layer { + pub fn with_level(self, display_level: bool) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_level(display_level), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span, @@ -326,8 +299,11 @@ where /// when formatting events /// /// [thread ID]: https://doc.rust-lang.org/stable/std/thread/struct.ThreadId.html - pub fn with_thread_ids(self, display_thread_ids: bool) -> Layer, W> { - Layer { + pub fn with_thread_ids( + self, + display_thread_ids: bool, + ) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_thread_ids(display_thread_ids), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span, @@ -343,8 +319,8 @@ where pub fn with_thread_names( self, display_thread_names: bool, - ) -> Layer, W> { - Layer { + ) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_thread_names(display_thread_names), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span, @@ -353,12 +329,12 @@ where } } - /// Sets the layer being built to use a [less verbose formatter](../fmt/format/struct.Compact.html). - pub fn compact(self) -> Layer, W> + /// Sets the subscriber being built to use a [less verbose formatter](../fmt/format/struct.Compact.html). + pub fn compact(self) -> Subscriber, W> where N: for<'writer> FormatFields<'writer> + 'static, { - Layer { + Subscriber { fmt_event: self.fmt_event.compact(), fmt_fields: self.fmt_fields, fmt_span: self.fmt_span, @@ -367,7 +343,7 @@ where } } - /// Sets the layer being built to use a [JSON formatter](../fmt/format/struct.Json.html). + /// Sets the subscriber being built to use a [JSON formatter](../fmt/format/struct.Json.html). /// /// The full format includes fields from all entered spans. /// @@ -379,14 +355,14 @@ where /// /// # Options /// - /// - [`Layer::flatten_event`] can be used to enable flattening event fields into the root + /// - [`Subscriber::flatten_event`] can be used to enable flattening event fields into the root /// object. /// - /// [`Layer::flatten_event`]: #method.flatten_event + /// [`Subscriber::flatten_event`]: #method.flatten_event #[cfg(feature = "json")] #[cfg_attr(docsrs, doc(cfg(feature = "json")))] - pub fn json(self) -> Layer, W> { - Layer { + pub fn json(self) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.json(), fmt_fields: format::JsonFields::new(), fmt_span: self.fmt_span, @@ -398,15 +374,15 @@ where #[cfg(feature = "json")] #[cfg_attr(docsrs, doc(cfg(feature = "json")))] -impl Layer, W> { +impl Subscriber, W> { /// Sets the JSON layer being built to flatten event metadata. /// /// See [`format::Json`](../fmt/format/struct.Json.html) pub fn flatten_event( self, flatten_event: bool, - ) -> Layer, W> { - Layer { + ) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.flatten_event(flatten_event), fmt_fields: format::JsonFields::new(), fmt_span: self.fmt_span, @@ -422,8 +398,8 @@ impl Layer, W> { pub fn with_current_span( self, display_current_span: bool, - ) -> Layer, W> { - Layer { + ) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_current_span(display_current_span), fmt_fields: format::JsonFields::new(), fmt_span: self.fmt_span, @@ -439,8 +415,8 @@ impl Layer, W> { pub fn with_span_list( self, display_span_list: bool, - ) -> Layer, W> { - Layer { + ) -> Subscriber, W> { + Subscriber { fmt_event: self.fmt_event.with_span_list(display_span_list), fmt_fields: format::JsonFields::new(), fmt_span: self.fmt_span, @@ -450,14 +426,14 @@ impl Layer, W> { } } -impl Layer { +impl Subscriber { /// Sets the field formatter that the layer being built will use to record /// fields. - pub fn fmt_fields(self, fmt_fields: N2) -> Layer + pub fn fmt_fields(self, fmt_fields: N2) -> Subscriber where N2: for<'writer> FormatFields<'writer> + 'static, { - Layer { + Subscriber { fmt_event: self.fmt_event, fmt_fields, fmt_span: self.fmt_span, @@ -467,29 +443,9 @@ impl Layer { } } -#[allow(deprecated)] -impl LayerBuilder -where - S: Subscriber + for<'a> LookupSpan<'a>, - N: for<'writer> FormatFields<'writer> + 'static, - E: FormatEvent + 'static, - W: MakeWriter + 'static, -{ - /// Builds a [`Layer`] with the provided configuration. - /// - /// [`Layer`]: struct.Layer.html - #[deprecated( - since = "0.2.4", - note = "`LayerBuilder` is no longer a separate type; this method is not necessary" - )] - pub fn finish(self) -> Layer { - self - } -} - -impl Default for Layer { +impl Default for Subscriber { fn default() -> Self { - Layer { + Subscriber { fmt_fields: format::DefaultFields::default(), fmt_event: format::Format::default(), fmt_span: format::FmtSpanConfig::default(), @@ -499,9 +455,9 @@ impl Default for Layer { } } -impl Layer +impl Subscriber where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, N: for<'writer> FormatFields<'writer> + 'static, E: FormatEvent + 'static, W: MakeWriter + 'static, @@ -580,9 +536,9 @@ macro_rules! with_event_from_span { }; } -impl layer::Layer for Layer +impl subscribe::Subscribe for Subscriber where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, N: for<'writer> FormatFields<'writer> + 'static, E: FormatEvent + 'static, W: MakeWriter + 'static, @@ -773,7 +729,7 @@ impl<'a, S, N> fmt::Debug for FmtContext<'a, S, N> { impl<'a, S, N> FormatFields<'a> for FmtContext<'a, S, N> where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { fn format_fields( @@ -787,7 +743,7 @@ where impl<'a, S, N> FmtContext<'a, S, N> where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { /// Visits every span in the current context with a closure. @@ -889,7 +845,7 @@ mod test { use crate::fmt::{ self, format::{self, test::MockTime, Format}, - layer::Layer as _, + subscribe::Subscribe as _, test::MockWriter, time, }; @@ -898,42 +854,44 @@ mod test { use lazy_static::lazy_static; use regex::Regex; use std::sync::Mutex; - use tracing::subscriber::with_default; - use tracing_core::dispatcher::Dispatch; + use tracing::collect::with_default; + use tracing_core::dispatch::Dispatch; #[test] fn impls() { let f = Format::default().with_timer(time::Uptime::default()); - let fmt = fmt::Layer::default().event_format(f); - let subscriber = fmt.with_subscriber(Registry::default()); + let fmt = fmt::Subscriber::default().event_format(f); + let subscriber = fmt.with_collector(Registry::default()); let _dispatch = Dispatch::new(subscriber); let f = format::Format::default(); - let fmt = fmt::Layer::default().event_format(f); - let subscriber = fmt.with_subscriber(Registry::default()); + let fmt = fmt::Subscriber::default().event_format(f); + let subscriber = fmt.with_collector(Registry::default()); let _dispatch = Dispatch::new(subscriber); let f = format::Format::default().compact(); - let fmt = fmt::Layer::default().event_format(f); - let subscriber = fmt.with_subscriber(Registry::default()); + let fmt = fmt::Subscriber::default().event_format(f); + let subscriber = fmt.with_collector(Registry::default()); let _dispatch = Dispatch::new(subscriber); } #[test] fn fmt_layer_downcasts() { let f = format::Format::default(); - let fmt = fmt::Layer::default().event_format(f); - let subscriber = fmt.with_subscriber(Registry::default()); + let fmt = fmt::Subscriber::default().event_format(f); + let subscriber = fmt.with_collector(Registry::default()); let dispatch = Dispatch::new(subscriber); - assert!(dispatch.downcast_ref::>().is_some()); + assert!(dispatch + .downcast_ref::>() + .is_some()); } #[test] fn fmt_layer_downcasts_to_parts() { let f = format::Format::default(); - let fmt = fmt::Layer::default().event_format(f); - let subscriber = fmt.with_subscriber(Registry::default()); + let fmt = fmt::Subscriber::default().event_format(f); + let subscriber = fmt.with_collector(Registry::default()); let dispatch = Dispatch::new(subscriber); assert!(dispatch.downcast_ref::().is_some()); assert!(dispatch.downcast_ref::().is_some()) @@ -942,8 +900,8 @@ mod test { #[test] fn is_lookup_span() { fn assert_lookup_span crate::registry::LookupSpan<'a>>(_: T) {} - let fmt = fmt::Layer::default(); - let subscriber = fmt.with_subscriber(Registry::default()); + let fmt = fmt::Subscriber::default(); + let subscriber = fmt.with_collector(Registry::default()); assert_lookup_span(subscriber) } @@ -959,7 +917,7 @@ mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) @@ -982,7 +940,7 @@ mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) @@ -996,8 +954,8 @@ mod test { }); let actual = sanitize_timings(String::from_utf8(BUF.try_lock().unwrap().to_vec()).unwrap()); assert_eq!( - "fake time span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: enter\n\ - fake time span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: exit\n", + "fake time span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: enter\n\ + fake time span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: exit\n", actual.as_str() ); } @@ -1009,7 +967,7 @@ mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) @@ -1023,7 +981,7 @@ mod test { }); let actual = sanitize_timings(String::from_utf8(BUF.try_lock().unwrap().to_vec()).unwrap()); assert_eq!( - "fake time span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: close timing timing\n", + "fake time span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: close timing timing\n", actual.as_str() ); } @@ -1035,7 +993,7 @@ mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) @@ -1050,7 +1008,7 @@ mod test { }); let actual = sanitize_timings(String::from_utf8(BUF.try_lock().unwrap().to_vec()).unwrap()); assert_eq!( - " span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: close\n", + " span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: close\n", actual.as_str() ); } @@ -1062,7 +1020,7 @@ mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) @@ -1076,10 +1034,10 @@ mod test { }); let actual = sanitize_timings(String::from_utf8(BUF.try_lock().unwrap().to_vec()).unwrap()); assert_eq!( - "fake time span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: new\n\ - fake time span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: enter\n\ - fake time span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: exit\n\ - fake time span1{x=42}: tracing_subscriber::fmt::fmt_layer::test: close timing timing\n", + "fake time span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: new\n\ + fake time span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: enter\n\ + fake time span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: exit\n\ + fake time span1{x=42}: tracing_subscriber::fmt::fmt_subscriber::test: close timing timing\n", actual.as_str() ); } diff --git a/tracing-subscriber/src/fmt/format/json.rs b/tracing-subscriber/src/fmt/format/json.rs index 9a5761e59c..1cf0d7a772 100644 --- a/tracing-subscriber/src/fmt/format/json.rs +++ b/tracing-subscriber/src/fmt/format/json.rs @@ -1,7 +1,7 @@ use super::{Format, FormatEvent, FormatFields, FormatTime}; use crate::{ field::{RecordFields, VisitOutput}, - fmt::fmt_layer::{FmtContext, FormattedFields}, + fmt::fmt_subscriber::{FmtContext, FormattedFields}, registry::LookupSpan, }; use serde::ser::{SerializeMap, Serializer as _}; @@ -14,7 +14,7 @@ use std::{ use tracing_core::{ field::{self, Field}, span::Record, - Event, Subscriber, + Collect, Event, }; use tracing_serde::AsSerde; @@ -27,7 +27,7 @@ use tracing_log::NormalizeEvent; /// /// # Example Output /// -/// ```ignore,json +/// ```json /// { /// "timestamp":"Feb 20 11:28:15.096", /// "level":"INFO", @@ -79,16 +79,16 @@ impl Json { } struct SerializableContext<'a, 'b, Span, N>( - &'b crate::layer::Context<'a, Span>, + &'b crate::subscribe::Context<'a, Span>, std::marker::PhantomData, ) where - Span: Subscriber + for<'lookup> crate::registry::LookupSpan<'lookup>, + Span: Collect + for<'lookup> crate::registry::LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static; impl<'a, 'b, Span, N> serde::ser::Serialize for SerializableContext<'a, 'b, Span, N> where - Span: Subscriber + for<'lookup> crate::registry::LookupSpan<'lookup>, + Span: Collect + for<'lookup> crate::registry::LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { fn serialize(&self, serializer_o: Ser) -> Result @@ -177,7 +177,7 @@ where impl FormatEvent for Format where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, T: FormatTime, { @@ -188,7 +188,7 @@ where event: &Event<'_>, ) -> fmt::Result where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, { let mut timestamp = String::new(); self.timer.format_time(&mut timestamp)?; @@ -503,7 +503,7 @@ impl<'a> fmt::Debug for WriteAdaptor<'a> { mod test { use crate::fmt::{test::MockWriter, time::FormatTime}; use lazy_static::lazy_static; - use tracing::{self, subscriber::with_default}; + use tracing::{self, collect::with_default}; use std::{fmt, sync::Mutex}; @@ -684,7 +684,7 @@ mod test { ) where T: crate::fmt::MakeWriter + Send + Sync + 'static, { - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .json() .flatten_event(flatten_event) .with_current_span(display_current_span) diff --git a/tracing-subscriber/src/fmt/format/mod.rs b/tracing-subscriber/src/fmt/format/mod.rs index 5f57711cb5..d6f1759222 100644 --- a/tracing-subscriber/src/fmt/format/mod.rs +++ b/tracing-subscriber/src/fmt/format/mod.rs @@ -2,8 +2,8 @@ use super::time::{self, FormatTime, SystemTime}; use crate::{ field::{MakeOutput, MakeVisitor, RecordFields, VisitFmt, VisitOutput}, - fmt::fmt_layer::FmtContext, - fmt::fmt_layer::FormattedFields, + fmt::fmt_subscriber::FmtContext, + fmt::fmt_subscriber::FormattedFields, registry::LookupSpan, }; @@ -13,7 +13,7 @@ use std::{ }; use tracing_core::{ field::{self, Field, Visit}, - span, Event, Level, Subscriber, + span, Collect, Event, Level, }; #[cfg(feature = "tracing-log")] @@ -32,18 +32,18 @@ pub use json::*; /// A type that can format a tracing `Event` for a `fmt::Write`. /// -/// `FormatEvent` is primarily used in the context of [`fmt::Subscriber`] or [`fmt::Layer`]. Each time an event is -/// dispatched to [`fmt::Subscriber`] or [`fmt::Layer`], the subscriber or layer forwards it to +/// `FormatEvent` is primarily used in the context of [`fmt::Collector`] or [`fmt::Subscriber`]. Each time an event is +/// dispatched to [`fmt::Collector`] or [`fmt::Subscriber`], the subscriber or layer forwards it to /// its associated `FormatEvent` to emit a log message. /// /// This trait is already implemented for function pointers with the same /// signature as `format_event`. /// +/// [`fmt::Collector`]: ../struct.Collector.html /// [`fmt::Subscriber`]: ../struct.Subscriber.html -/// [`fmt::Layer`]: ../struct.Layer.html pub trait FormatEvent where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, N: for<'a> FormatFields<'a> + 'static, { /// Write a log message for `Event` in `Context` to the given `Write`. @@ -58,7 +58,7 @@ where impl FormatEvent for fn(ctx: &FmtContext<'_, S, N>, &mut dyn fmt::Write, &Event<'_>) -> fmt::Result where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, N: for<'a> FormatFields<'a> + 'static, { fn format_event( @@ -77,7 +77,7 @@ where /// those fields with its associated `FormatFields` implementation. /// /// [set of fields]: ../field/trait.RecordFields.html -/// [`FmtSubscriber`]: ../fmt/struct.Subscriber.html +/// [`FmtSubscriber`]: ../fmt/struct.Collector.html pub trait FormatFields<'writer> { /// Format the provided `fields` to the provided `writer`, returning a result. fn format_fields( @@ -367,7 +367,7 @@ impl Format { impl FormatEvent for Format where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, N: for<'a> FormatFields<'a> + 'static, T: FormatTime, { @@ -442,7 +442,7 @@ where impl FormatEvent for Format where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, N: for<'a> FormatFields<'a> + 'static, T: FormatTime, { @@ -679,7 +679,7 @@ struct FmtCtx<'a, S, N> { impl<'a, S, N: 'a> FmtCtx<'a, S, N> where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { #[cfg(feature = "ansi")] @@ -710,7 +710,7 @@ where impl<'a, S, N: 'a> fmt::Display for FmtCtx<'a, S, N> where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -740,7 +740,7 @@ where struct FullCtx<'a, S, N> where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { ctx: &'a FmtContext<'a, S, N>, @@ -751,7 +751,7 @@ where impl<'a, S, N: 'a> FullCtx<'a, S, N> where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { #[cfg(feature = "ansi")] @@ -782,7 +782,7 @@ where impl<'a, S, N> fmt::Display for FullCtx<'a, S, N> where - S: Subscriber + for<'lookup> LookupSpan<'lookup>, + S: Collect + for<'lookup> LookupSpan<'lookup>, N: for<'writer> FormatFields<'writer> + 'static, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -1101,7 +1101,7 @@ pub(super) mod test { use crate::fmt::{test::MockWriter, time::FormatTime}; use lazy_static::lazy_static; - use tracing::{self, subscriber::with_default}; + use tracing::{self, collect::with_default}; use super::TimingDisplay; use std::{fmt, sync::Mutex}; @@ -1147,7 +1147,7 @@ pub(super) mod test { let make_writer = || MockWriter::new(&BUF); let expected = "fake time INFO tracing_subscriber::fmt::format::test: some ansi test\n"; - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_timer(MockTime) .finish(); @@ -1165,7 +1165,7 @@ pub(super) mod test { where T: crate::fmt::MakeWriter + Send + Sync + 'static, { - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_ansi(is_ansi) .with_timer(MockTime) @@ -1186,7 +1186,7 @@ pub(super) mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) @@ -1210,7 +1210,7 @@ pub(super) mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) @@ -1236,7 +1236,7 @@ pub(super) mod test { } let make_writer = || MockWriter::new(&BUF); - let subscriber = crate::fmt::Subscriber::builder() + let subscriber = crate::fmt::Collector::builder() .with_writer(make_writer) .with_level(false) .with_ansi(false) diff --git a/tracing-subscriber/src/fmt/mod.rs b/tracing-subscriber/src/fmt/mod.rs index 541f4c372a..fdba6b93a8 100644 --- a/tracing-subscriber/src/fmt/mod.rs +++ b/tracing-subscriber/src/fmt/mod.rs @@ -1,10 +1,10 @@ -//! A `Subscriber` for formatting and logging `tracing` data. +//! A Collector for formatting and logging `tracing` data. //! //! ## Overview //! //! [`tracing`] is a framework for instrumenting Rust programs with context-aware, //! structured, event-based diagnostic information. This crate provides an -//! implementation of the [`Subscriber`] trait that records `tracing`'s `Event`s +//! implementation of the [`Collect`] trait that records `tracing`'s `Event`s //! and `Span`s by formatting them as text and logging them to stdout. //! //! ## Usage @@ -18,7 +18,7 @@ //! //! *Compiler support: requires rustc 1.39+* //! -//! Add the following to your executable to initialize the default subscriber: +//! Add the following to your executable to initialize the default collector: //! ```rust //! use tracing_subscriber; //! @@ -43,12 +43,12 @@ //! //! ## Configuration //! -//! You can configure a subscriber instead of using the defaults with +//! You can configure a collector instead of using the defaults with //! the following functions: //! -//! ### Subscriber +//! ### Collector //! -//! The [`FmtSubscriber`] formats and records `tracing` events as line-oriented logs. +//! The [`FmtCollector`] formats and records `tracing` events as line-oriented logs. //! You can create one by calling: //! //! ```rust @@ -57,7 +57,7 @@ //! .finish(); //! ``` //! -//! You can find the configuration methods for [`FmtSubscriber`] in [`fmtBuilder`]. +//! You can find the configuration methods for [`FmtCollector`] in [`fmtBuilder`]. //! //! ### Filters //! @@ -75,19 +75,19 @@ //! //! You can find the other available [`filter`]s in the documentation. //! -//! ### Using Your Subscriber +//! ### Using Your Collector //! -//! Finally, once you have configured your `Subscriber`, you need to +//! Finally, once you have configured your `Collector`, you need to //! configure your executable to use it. //! -//! A subscriber can be installed globally using: +//! A collector can be installed globally using: //! ```rust //! use tracing; -//! use tracing_subscriber::FmtSubscriber; +//! use tracing_subscriber::fmt; //! -//! let subscriber = FmtSubscriber::new(); +//! let subscriber = fmt::Collector::new(); //! -//! tracing::subscriber::set_global_default(subscriber) +//! tracing::collect::set_global_default(subscriber) //! .map_err(|_err| eprintln!("Unable to set global default subscriber")); //! // Note this will only fail if you try to set the global default //! // subscriber multiple times @@ -95,13 +95,13 @@ //! //! ### Composing Layers //! -//! Composing an [`EnvFilter`] `Layer` and a [format `Layer`](../fmt/struct.Layer.html): +//! Composing an [`EnvFilter`] `Subscriber` and a [format `Subscriber`](../fmt/struct.Subscriber.html): //! //! ```rust //! use tracing_subscriber::{fmt, EnvFilter}; //! use tracing_subscriber::prelude::*; //! -//! let fmt_layer = fmt::layer() +//! let fmt_layer = fmt::subscriber() //! .with_target(false); //! let filter_layer = EnvFilter::try_from_default_env() //! .or_else(|_| EnvFilter::try_new("info")) @@ -116,28 +116,25 @@ //! [`EnvFilter`]: ../filter/struct.EnvFilter.html //! [`env_logger`]: https://docs.rs/env_logger/ //! [`filter`]: ../filter/index.html -//! [`fmtBuilder`]: ./struct.SubscriberBuilder.html -//! [`FmtSubscriber`]: ./struct.Subscriber.html -//! [`Subscriber`]: -//! https://docs.rs/tracing/latest/tracing/trait.Subscriber.html +//! [`fmtBuilder`]: ./struct.CollectorBuilder.html +//! [`FmtCollector`]: ./struct.Collector.html +//! [`Collect`]: +//! https://docs.rs/tracing/latest/tracing/trait.Collect.html //! [`tracing`]: https://crates.io/crates/tracing use std::{any::TypeId, error::Error, io}; -use tracing_core::{span, subscriber::Interest, Event, Metadata}; +use tracing_core::{collect::Interest, span, Event, Metadata}; -mod fmt_layer; +mod fmt_subscriber; pub mod format; pub mod time; pub mod writer; -#[allow(deprecated)] -pub use fmt_layer::LayerBuilder; -pub use fmt_layer::{FmtContext, FormattedFields, Layer}; +pub use fmt_subscriber::{FmtContext, FormattedFields, Subscriber}; -use crate::layer::Layer as _; +use crate::subscribe::Subscribe as _; use crate::{ filter::LevelFilter, - layer, registry::{LookupSpan, Registry}, - reload, + reload, subscribe, }; #[doc(inline)] @@ -147,46 +144,46 @@ pub use self::{ writer::{MakeWriter, TestWriter}, }; -/// A `Subscriber` that logs formatted representations of `tracing` events. +/// A `Collector` that logs formatted representations of `tracing` events. /// /// This consists of an inner `Formatter` wrapped in a layer that performs filtering. #[derive(Debug)] -pub struct Subscriber< +pub struct Collector< N = format::DefaultFields, E = format::Format, F = LevelFilter, W = fn() -> io::Stdout, > { - inner: layer::Layered>, + inner: subscribe::Layered>, } -/// A `Subscriber` that logs formatted representations of `tracing` events. +/// A collector that logs formatted representations of `tracing` events. /// This type only logs formatted events; it does not perform any filtering. pub type Formatter< N = format::DefaultFields, E = format::Format, W = fn() -> io::Stdout, -> = layer::Layered, Registry>; +> = subscribe::Layered, Registry>; -/// Configures and constructs `Subscriber`s. +/// Configures and constructs `Collector`s. #[derive(Debug)] -pub struct SubscriberBuilder< +pub struct CollectorBuilder< N = format::DefaultFields, E = format::Format, F = LevelFilter, W = fn() -> io::Stdout, > { filter: F, - inner: Layer, + inner: Subscriber, } -/// Returns a new [`SubscriberBuilder`] for configuring a [formatting subscriber]. +/// Returns a new [`CollectorBuilder`] for configuring a [formatting collector]. /// -/// This is essentially shorthand for [`SubscriberBuilder::default()]`. +/// This is essentially shorthand for [`CollectorBuilder::default()]`. /// /// # Examples /// -/// Using [`init`] to set the default subscriber: +/// Using [`init`] to set the default collector: /// /// ```rust /// tracing_subscriber::fmt().init(); @@ -205,7 +202,7 @@ pub struct SubscriberBuilder< /// .init(); /// ``` /// -/// [`try_init`] returns an error if the default subscriber could not be set: +/// [`try_init`] returns an error if the default collector could not be set: /// /// ```rust /// use std::error::Error; @@ -224,55 +221,55 @@ pub struct SubscriberBuilder< /// ``` /// /// Rather than setting the subscriber as the default, [`finish`] _returns_ the -/// constructed subscriber, which may then be passed to other functions: +/// constructed collector, which may then be passed to other functions: /// /// ```rust -/// let subscriber = tracing_subscriber::fmt() +/// let collector = tracing_subscriber::fmt() /// .with_max_level(tracing::Level::DEBUG) /// .compact() /// .finish(); /// -/// tracing::subscriber::with_default(subscriber, || { -/// // the subscriber will only be set as the default +/// tracing::collect::with_default(collector, || { +/// // the collector will only be set as the default /// // inside this closure... /// }) /// ``` /// -/// [`SubscriberBuilder`]: struct.SubscriberBuilder.html -/// [formatting subscriber]: struct.Subscriber.html -/// [`SubscriberBuilder::default()`]: struct.SubscriberBuilder.html#method.default -/// [`init`]: struct.SubscriberBuilder.html#method.init -/// [`try_init`]: struct.SubscriberBuilder.html#method.try_init -/// [`finish`]: struct.SubscriberBuilder.html#method.finish -pub fn fmt() -> SubscriberBuilder { - SubscriberBuilder::default() +/// [`CollectorBuilder`]: struct.CollectorBuilder.html +/// [formatting collector]: struct.Collector.html +/// [`CollectorBuilder::default()`]: struct.CollectorBuilder.html#method.default +/// [`init`]: struct.CollectorBuilder.html#method.init +/// [`try_init`]: struct.CollectorBuilder.html#method.try_init +/// [`finish`]: struct.CollectorBuilder.html#method.finish +pub fn fmt() -> CollectorBuilder { + CollectorBuilder::default() } -/// Returns a new [formatting layer] that can be [composed] with other layers to -/// construct a [`Subscriber`]. +/// Returns a new [formatting subscriber] that can be [composed] with other subscribers to +/// construct a collector. /// -/// This is a shorthand for the equivalent [`Layer::default`] function. +/// This is a shorthand for the equivalent [`Subscriber::default`] function. /// -/// [formatting layer]: struct.Layer.html +/// [formatting subscriber]: struct.Subscriber.html /// [composed]: ../layer/index.html -/// [`Layer::default`]: struct.Layer.html#method.default -pub fn layer() -> Layer { - Layer::default() +/// [`Subscriber::default`]: struct.Subscriber.html#method.default +pub fn subscriber() -> Subscriber { + Subscriber::default() } -impl Subscriber { - /// The maximum [verbosity level] that is enabled by a `Subscriber` by +impl Collector { + /// The maximum [verbosity level] that is enabled by a `Collector` by /// default. /// - /// This can be overridden with the [`SubscriberBuilder::with_max_level`] method. + /// This can be overridden with the [`CollectorBuilder::with_max_level`] method. /// /// [verbosity level]: https://docs.rs/tracing-core/0.1.5/tracing_core/struct.Level.html - /// [`SubscriberBuilder::with_max_level`]: struct.SubscriberBuilder.html#method.with_max_level + /// [`CollectorBuilder::with_max_level`]: struct.CollectorBuilder.html#method.with_max_level pub const DEFAULT_MAX_LEVEL: LevelFilter = LevelFilter::INFO; - /// Returns a new `SubscriberBuilder` for configuring a format subscriber. - pub fn builder() -> SubscriberBuilder { - SubscriberBuilder::default() + /// Returns a new `CollectorBuilder` for configuring a format subscriber. + pub fn builder() -> CollectorBuilder { + CollectorBuilder::default() } /// Returns a new format subscriber with the default configuration. @@ -281,22 +278,22 @@ impl Subscriber { } } -impl Default for Subscriber { +impl Default for Collector { fn default() -> Self { - SubscriberBuilder::default().finish() + CollectorBuilder::default().finish() } } -// === impl Subscriber === +// === impl Collector === -impl tracing_core::Subscriber for Subscriber +impl tracing_core::Collect for Collector where N: for<'writer> FormatFields<'writer> + 'static, E: FormatEvent + 'static, - F: layer::Layer> + 'static, + F: subscribe::Subscribe> + 'static, W: MakeWriter + 'static, - layer::Layered>: tracing_core::Subscriber, - fmt_layer::Layer: layer::Layer, + subscribe::Layered>: tracing_core::Collect, + fmt_subscriber::Subscriber: subscribe::Subscribe, { #[inline] fn register_callsite(&self, meta: &'static Metadata<'static>) -> Interest { @@ -363,45 +360,46 @@ where } } -impl<'a, N, E, F, W> LookupSpan<'a> for Subscriber +impl<'a, N, E, F, W> LookupSpan<'a> for Collector where - layer::Layered>: LookupSpan<'a>, + subscribe::Layered>: LookupSpan<'a>, { - type Data = > as LookupSpan<'a>>::Data; + type Data = > as LookupSpan<'a>>::Data; fn span_data(&'a self, id: &span::Id) -> Option { self.inner.span_data(id) } } -// ===== impl SubscriberBuilder ===== +// ===== impl CollectorBuilder ===== -impl Default for SubscriberBuilder { +impl Default for CollectorBuilder { fn default() -> Self { - SubscriberBuilder { - filter: Subscriber::DEFAULT_MAX_LEVEL, + CollectorBuilder { + filter: Collector::DEFAULT_MAX_LEVEL, inner: Default::default(), } } } -impl SubscriberBuilder +impl CollectorBuilder where N: for<'writer> FormatFields<'writer> + 'static, E: FormatEvent + 'static, W: MakeWriter + 'static, - F: layer::Layer> + Send + Sync + 'static, - fmt_layer::Layer: layer::Layer + Send + Sync + 'static, + F: subscribe::Subscribe> + Send + Sync + 'static, + fmt_subscriber::Subscriber: + subscribe::Subscribe + Send + Sync + 'static, { - /// Finish the builder, returning a new `FmtSubscriber`. - pub fn finish(self) -> Subscriber { - let subscriber = self.inner.with_subscriber(Registry::default()); - Subscriber { - inner: self.filter.with_subscriber(subscriber), + /// Finish the builder, returning a new `FmtCollector`. + pub fn finish(self) -> Collector { + let collector = self.inner.with_collector(Registry::default()); + Collector { + inner: self.filter.with_collector(collector), } } - /// Install this Subscriber as the global default if one is + /// Install this collector as the global default if one is /// not already set. /// /// If the `tracing-log` feature is enabled, this will also install @@ -409,46 +407,46 @@ where /// /// # Errors /// Returns an Error if the initialization was unsuccessful, likely - /// because a global subscriber was already installed by another + /// because a global collector was already installed by another /// call to `try_init`. pub fn try_init(self) -> Result<(), Box> { #[cfg(feature = "tracing-log")] tracing_log::LogTracer::init().map_err(Box::new)?; - tracing_core::dispatcher::set_global_default(tracing_core::dispatcher::Dispatch::new( + tracing_core::dispatch::set_global_default(tracing_core::dispatch::Dispatch::new( self.finish(), ))?; Ok(()) } - /// Install this Subscriber as the global default. + /// Install this collector as the global default. /// /// If the `tracing-log` feature is enabled, this will also install /// the LogTracer to convert `Log` records into `tracing` `Event`s. /// /// # Panics /// Panics if the initialization was unsuccessful, likely because a - /// global subscriber was already installed by another call to `try_init`. + /// global collector was already installed by another call to `try_init`. pub fn init(self) { - self.try_init() - .expect("Unable to install global subscriber") + self.try_init().expect("Unable to install global collector") } } -impl Into for SubscriberBuilder +impl Into for CollectorBuilder where N: for<'writer> FormatFields<'writer> + 'static, E: FormatEvent + 'static, W: MakeWriter + 'static, - F: layer::Layer> + Send + Sync + 'static, - fmt_layer::Layer: layer::Layer + Send + Sync + 'static, + F: subscribe::Subscribe> + Send + Sync + 'static, + fmt_subscriber::Subscriber: + subscribe::Subscribe + Send + Sync + 'static, { fn into(self) -> tracing_core::Dispatch { tracing_core::Dispatch::new(self.finish()) } } -impl SubscriberBuilder, F, W> +impl CollectorBuilder, F, W> where N: for<'writer> FormatFields<'writer> + 'static, { @@ -463,16 +461,16 @@ where /// [`timer`]: ./time/trait.FormatTime.html /// [`ChronoUtc`]: ./time/struct.ChronoUtc.html /// [`ChronoLocal`]: ./time/struct.ChronoLocal.html - pub fn with_timer(self, timer: T2) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + pub fn with_timer(self, timer: T2) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_timer(timer), } } /// Do not emit timestamps with log messages. - pub fn without_time(self) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + pub fn without_time(self) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.without_time(), } @@ -499,13 +497,13 @@ where /// described above. /// /// Note that the generated events will only be part of the log output by - /// this formatter; they will not be recorded by other `Subscriber`s or by - /// `Layer`s added to this subscriber. + /// this formatter; they will not be recorded by other `Collector`s or by + /// `Subscriber`s added to this subscriber. /// /// [lifecycle]: https://docs.rs/tracing/latest/tracing/span/index.html#the-span-lifecycle /// [time]: #method.without_time pub fn with_span_events(self, kind: format::FmtSpan) -> Self { - SubscriberBuilder { + CollectorBuilder { filter: self.filter, inner: self.inner.with_span_events(kind), } @@ -514,8 +512,8 @@ where /// Enable ANSI encoding for formatted events. #[cfg(feature = "ansi")] #[cfg_attr(docsrs, doc(cfg(feature = "ansi")))] - pub fn with_ansi(self, ansi: bool) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + pub fn with_ansi(self, ansi: bool) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_ansi(ansi), } @@ -525,8 +523,8 @@ where pub fn with_target( self, display_target: bool, - ) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + ) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_target(display_target), } @@ -536,8 +534,8 @@ where pub fn with_level( self, display_level: bool, - ) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + ) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_level(display_level), } @@ -550,8 +548,8 @@ where pub fn with_thread_names( self, display_thread_names: bool, - ) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + ) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_thread_names(display_thread_names), } @@ -564,38 +562,36 @@ where pub fn with_thread_ids( self, display_thread_ids: bool, - ) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + ) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_thread_ids(display_thread_ids), } } - /// Sets the subscriber being built to use a less verbose formatter. + /// Sets the collector being built to use a less verbose formatter. /// /// See [`format::Compact`](../fmt/format/struct.Compact.html). - pub fn compact(self) -> SubscriberBuilder, F, W> + pub fn compact(self) -> CollectorBuilder, F, W> where N: for<'writer> FormatFields<'writer> + 'static, { - SubscriberBuilder { + CollectorBuilder { filter: self.filter, inner: self.inner.compact(), } } - /// Sets the subscriber being built to use a JSON formatter. + /// Sets the collector being built to use a JSON formatter. /// /// See [`format::Json`](../fmt/format/struct.Json.html) #[cfg(feature = "json")] #[cfg_attr(docsrs, doc(cfg(feature = "json")))] - pub fn json( - self, - ) -> SubscriberBuilder, F, W> + pub fn json(self) -> CollectorBuilder, F, W> where N: for<'writer> FormatFields<'writer> + 'static, { - SubscriberBuilder { + CollectorBuilder { filter: self.filter, inner: self.inner.json(), } @@ -604,15 +600,15 @@ where #[cfg(feature = "json")] #[cfg_attr(docsrs, doc(cfg(feature = "json")))] -impl SubscriberBuilder, F, W> { - /// Sets the json subscriber being built to flatten event metadata. +impl CollectorBuilder, F, W> { + /// Sets the json collector being built to flatten event metadata. /// /// See [`format::Json`](../fmt/format/struct.Json.html) pub fn flatten_event( self, flatten_event: bool, - ) -> SubscriberBuilder, F, W> { - SubscriberBuilder { + ) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.flatten_event(flatten_event), } @@ -625,8 +621,8 @@ impl SubscriberBuilder SubscriberBuilder, F, W> { - SubscriberBuilder { + ) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_current_span(display_current_span), } @@ -639,27 +635,27 @@ impl SubscriberBuilder SubscriberBuilder, F, W> { - SubscriberBuilder { + ) -> CollectorBuilder, F, W> { + CollectorBuilder { filter: self.filter, inner: self.inner.with_span_list(display_span_list), } } } -impl SubscriberBuilder, W> +impl CollectorBuilder, W> where - Formatter: tracing_core::Subscriber + 'static, + Formatter: tracing_core::Collect + 'static, { - /// Returns a `Handle` that may be used to reload the constructed subscriber's + /// Returns a `Handle` that may be used to reload the constructed collector's /// filter. pub fn reload_handle(&self) -> reload::Handle { self.filter.handle() } } -impl SubscriberBuilder { - /// Sets the Visitor that the subscriber being built will use to record +impl CollectorBuilder { + /// Sets the Visitor that the collector being built will use to record /// fields. /// /// For example: @@ -674,22 +670,22 @@ impl SubscriberBuilder { /// // formatter so that a delimiter is added between fields. /// .delimited(", "); /// - /// let subscriber = tracing_subscriber::fmt() + /// let collector = tracing_subscriber::fmt() /// .fmt_fields(formatter) /// .finish(); - /// # drop(subscriber) + /// # drop(collector) /// ``` - pub fn fmt_fields(self, fmt_fields: N2) -> SubscriberBuilder + pub fn fmt_fields(self, fmt_fields: N2) -> CollectorBuilder where N2: for<'writer> FormatFields<'writer> + 'static, { - SubscriberBuilder { + CollectorBuilder { filter: self.filter, inner: self.inner.fmt_fields(fmt_fields), } } - /// Sets the [`EnvFilter`] that the subscriber will use to determine if + /// Sets the [`EnvFilter`] that the collector will use to determine if /// a span or event is enabled. /// /// Note that this method requires the "env-filter" feature flag to be enabled. @@ -742,19 +738,19 @@ impl SubscriberBuilder { pub fn with_env_filter( self, filter: impl Into, - ) -> SubscriberBuilder + ) -> CollectorBuilder where - Formatter: tracing_core::Subscriber + 'static, + Formatter: tracing_core::Collect + 'static, { let filter = filter.into(); - SubscriberBuilder { + CollectorBuilder { filter, inner: self.inner, } } /// Sets the maximum [verbosity level] that will be enabled by the - /// subscriber. + /// collector. /// /// If the max level has already been set, or a [`EnvFilter`] was added by /// [`with_filter`], this replaces that configuration with the new @@ -771,7 +767,7 @@ impl SubscriberBuilder { /// .with_max_level(Level::DEBUG) /// .init(); /// ``` - /// This subscriber won't record any spans or events! + /// This collector won't record any spans or events! /// ```rust /// use tracing_subscriber::{fmt, filter::LevelFilter}; /// @@ -785,15 +781,15 @@ impl SubscriberBuilder { pub fn with_max_level( self, filter: impl Into, - ) -> SubscriberBuilder { + ) -> CollectorBuilder { let filter = filter.into(); - SubscriberBuilder { + CollectorBuilder { filter, inner: self.inner, } } - /// Configures the subscriber being built to allow filter reloading at + /// Configures the collector being built to allow filter reloading at /// runtime. /// /// The returned builder will have a [`reload_handle`] method, which returns @@ -806,73 +802,53 @@ impl SubscriberBuilder { /// use tracing_subscriber::prelude::*; /// /// let builder = tracing_subscriber::fmt() - /// // Set a max level filter on the subscriber + /// // Set a max level filter on the collector /// .with_max_level(Level::INFO) /// .with_filter_reloading(); /// - /// // Get a handle for modifying the subscriber's max level filter. + /// // Get a handle for modifying the collector's max level filter. /// let handle = builder.reload_handle(); /// - /// // Finish building the subscriber, and set it as the default. + /// // Finish building the collector, and set it as the default. /// builder.finish().init(); /// /// // Currently, the max level is INFO, so this event will be disabled. /// tracing::debug!("this is not recorded!"); /// /// // Use the handle to set a new max level filter. - /// // (this returns an error if the subscriber has been dropped, which shouldn't + /// // (this returns an error if the collector has been dropped, which shouldn't /// // happen in this example.) - /// handle.reload(Level::DEBUG).expect("the subscriber should still exist"); + /// handle.reload(Level::DEBUG).expect("the collector should still exist"); /// /// // Now, the max level is INFO, so this event will be recorded. /// tracing::debug!("this is recorded!"); /// ``` /// - /// [`reload_handle`]: SubscriberBuilder::reload_handle + /// [`reload_handle`]: CollectorBuilder::reload_handle /// [`reload::Handle`]: crate::reload::Handle - pub fn with_filter_reloading(self) -> SubscriberBuilder, W> { - let (filter, _) = reload::Layer::new(self.filter); - SubscriberBuilder { + pub fn with_filter_reloading(self) -> CollectorBuilder, W> { + let (filter, _) = reload::Subscriber::new(self.filter); + CollectorBuilder { filter, inner: self.inner, } } - /// Sets the function that the subscriber being built should use to format + /// Sets the function that the collector being built should use to format /// events that occur. - pub fn event_format(self, fmt_event: E2) -> SubscriberBuilder + pub fn event_format(self, fmt_event: E2) -> CollectorBuilder where E2: FormatEvent + 'static, N: for<'writer> FormatFields<'writer> + 'static, W: MakeWriter + 'static, { - SubscriberBuilder { + CollectorBuilder { filter: self.filter, inner: self.inner.event_format(fmt_event), } } - /// Sets whether or not spans inherit their parents' field values (disabled - /// by default). - #[deprecated(since = "0.2.0", note = "this no longer does anything")] - pub fn inherit_fields(self, inherit_fields: bool) -> Self { - let _ = inherit_fields; - self - } - - /// Sets the function that the subscriber being built should use to format - /// events that occur. - #[deprecated(since = "0.2.0", note = "renamed to `event_format`.")] - pub fn on_event(self, fmt_event: E2) -> SubscriberBuilder - where - E2: FormatEvent + 'static, - N: for<'writer> FormatFields<'writer> + 'static, - W: MakeWriter + 'static, - { - self.event_format(fmt_event) - } - - /// Sets the [`MakeWriter`] that the subscriber being built will use to write events. + /// Sets the [`MakeWriter`] that the collector being built will use to write events. /// /// # Examples /// @@ -888,17 +864,17 @@ impl SubscriberBuilder { /// ``` /// /// [`MakeWriter`]: trait.MakeWriter.html - pub fn with_writer(self, make_writer: W2) -> SubscriberBuilder + pub fn with_writer(self, make_writer: W2) -> CollectorBuilder where W2: MakeWriter + 'static, { - SubscriberBuilder { + CollectorBuilder { filter: self.filter, inner: self.inner.with_writer(make_writer), } } - /// Configures the subscriber to support [`libtest`'s output capturing][capturing] when used in + /// Configures the collector to support [`libtest`'s output capturing][capturing] when used in /// unit tests. /// /// See [`TestWriter`] for additional details. @@ -910,9 +886,9 @@ impl SubscriberBuilder { /// /// ```rust /// use tracing_subscriber::fmt; - /// use tracing::subscriber; + /// use tracing::collect; /// - /// subscriber::set_default( + /// collect::set_default( /// fmt() /// .with_test_writer() /// .finish() @@ -922,15 +898,15 @@ impl SubscriberBuilder { /// [capturing]: /// https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output /// [`TestWriter`]: writer/struct.TestWriter.html - pub fn with_test_writer(self) -> SubscriberBuilder { - SubscriberBuilder { + pub fn with_test_writer(self) -> CollectorBuilder { + CollectorBuilder { filter: self.filter, inner: self.inner.with_writer(TestWriter::default()), } } } -/// Install a global tracing subscriber that listens for events and +/// Install a global tracing collector that listens for events and /// filters based on the value of the [`RUST_LOG` environment variable], /// if one is not already set. /// @@ -949,7 +925,7 @@ impl SubscriberBuilder { /// # Errors /// /// Returns an Error if the initialization was unsuccessful, -/// likely because a global subscriber was already installed by another +/// likely because a global collector was already installed by another /// call to `try_init`. /// /// [`LogTracer`]: @@ -957,7 +933,7 @@ impl SubscriberBuilder { /// [`RUST_LOG` environment variable]: /// ../filter/struct.EnvFilter.html#associatedconstant.DEFAULT_ENV pub fn try_init() -> Result<(), Box> { - let builder = Subscriber::builder(); + let builder = Collector::builder(); #[cfg(feature = "env-filter")] let builder = builder.with_env_filter(crate::EnvFilter::from_default_env()); @@ -965,7 +941,7 @@ pub fn try_init() -> Result<(), Box> { builder.try_init() } -/// Install a global tracing subscriber that listens for events and +/// Install a global tracing collector that listens for events and /// filters based on the value of the [`RUST_LOG` environment variable]. /// /// If the `tracing-log` feature is enabled, this will also install @@ -979,12 +955,12 @@ pub fn try_init() -> Result<(), Box> { /// /// # Panics /// Panics if the initialization was unsuccessful, likely because a -/// global subscriber was already installed by another call to `try_init`. +/// global collector was already installed by another call to `try_init`. /// /// [`RUST_LOG` environment variable]: /// ../filter/struct.EnvFilter.html#associatedconstant.DEFAULT_ENV pub fn init() { - try_init().expect("Unable to install global subscriber") + try_init().expect("Unable to install global collector") } #[cfg(test)] @@ -995,14 +971,14 @@ mod test { format::{self, Format}, time, writer::MakeWriter, - Subscriber, + Collector, }, }; use std::{ io, sync::{Mutex, MutexGuard, TryLockError}, }; - use tracing_core::dispatcher::Dispatch; + use tracing_core::dispatch::Dispatch; pub(crate) struct MockWriter<'a> { buf: &'a Mutex>, @@ -1056,28 +1032,28 @@ mod test { #[test] fn impls() { let f = Format::default().with_timer(time::Uptime::default()); - let subscriber = Subscriber::builder().event_format(f).finish(); + let subscriber = Collector::builder().event_format(f).finish(); let _dispatch = Dispatch::new(subscriber); let f = format::Format::default(); - let subscriber = Subscriber::builder().event_format(f).finish(); + let subscriber = Collector::builder().event_format(f).finish(); let _dispatch = Dispatch::new(subscriber); let f = format::Format::default().compact(); - let subscriber = Subscriber::builder().event_format(f).finish(); + let subscriber = Collector::builder().event_format(f).finish(); let _dispatch = Dispatch::new(subscriber); } #[test] fn subscriber_downcasts() { - let subscriber = Subscriber::builder().finish(); + let subscriber = Collector::builder().finish(); let dispatch = Dispatch::new(subscriber); - assert!(dispatch.downcast_ref::().is_some()); + assert!(dispatch.downcast_ref::().is_some()); } #[test] fn subscriber_downcasts_to_parts() { - let subscriber = Subscriber::new(); + let subscriber = Collector::new(); let dispatch = Dispatch::new(subscriber); assert!(dispatch.downcast_ref::().is_some()); assert!(dispatch.downcast_ref::().is_some()); @@ -1087,7 +1063,7 @@ mod test { #[test] fn is_lookup_span() { fn assert_lookup_span crate::registry::LookupSpan<'a>>(_: T) {} - let subscriber = Subscriber::new(); + let subscriber = Collector::new(); assert_lookup_span(subscriber) } } diff --git a/tracing-subscriber/src/fmt/writer.rs b/tracing-subscriber/src/fmt/writer.rs index d437e5f5dc..9db6be7888 100644 --- a/tracing-subscriber/src/fmt/writer.rs +++ b/tracing-subscriber/src/fmt/writer.rs @@ -7,15 +7,15 @@ use std::{fmt::Debug, io}; /// A type that can create [`io::Write`] instances. /// -/// `MakeWriter` is used by [`fmt::Subscriber`] or [`fmt::Layer`] to print formatted text representations of +/// `MakeWriter` is used by [`fmt::Collector`] or [`fmt::Subscriber`] to print formatted text representations of /// [`Event`]s. /// /// This trait is already implemented for function pointers and immutably-borrowing closures that /// return an instance of [`io::Write`], such as [`io::stdout`] and [`io::stderr`]. /// /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +/// [`fmt::Collector`]: ../../fmt/struct.Collector.html /// [`fmt::Subscriber`]: ../../fmt/struct.Subscriber.html -/// [`fmt::Layer`]: ../../fmt/struct.Layer.html /// [`Event`]: https://docs.rs/tracing-core/0.1.5/tracing_core/event/struct.Event.html /// [`io::stdout`]: https://doc.rust-lang.org/std/io/fn.stdout.html /// [`io::stderr`]: https://doc.rust-lang.org/std/io/fn.stderr.html @@ -30,14 +30,14 @@ pub trait MakeWriter { /// /// # Implementer notes /// - /// [`fmt::Layer`] or [`fmt::Subscriber`] will call this method each time an event is recorded. Ensure any state + /// [`fmt::Subscriber`] or [`fmt::Collector`] will call this method each time an event is recorded. Ensure any state /// that must be saved across writes is not lost when the [`Writer`] instance is dropped. If /// creating a [`io::Write`] instance is expensive, be sure to cache it when implementing /// [`MakeWriter`] to improve performance. /// /// [`Writer`]: #associatedtype.Writer - /// [`fmt::Layer`]: ../../fmt/struct.Layer.html /// [`fmt::Subscriber`]: ../../fmt/struct.Subscriber.html + /// [`fmt::Collector`]: ../../fmt/struct.Collector.html /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html /// [`MakeWriter`]: trait.MakeWriter.html fn make_writer(&self) -> Self::Writer; @@ -57,7 +57,7 @@ where /// A writer intended to support [`libtest`'s output capturing][capturing] for use in unit tests. /// -/// `TestWriter` is used by [`fmt::Subscriber`] or [`fmt::Layer`] to enable capturing support. +/// `TestWriter` is used by [`fmt::Collector`] or [`fmt::Subscriber`] to enable capturing support. /// /// `cargo test` can only capture output from the standard library's [`print!`] macro. See /// [`libtest`'s output capturing][capturing] for more details about output capturing. @@ -65,8 +65,8 @@ where /// Writing to [`io::stdout`] and [`io::stderr`] produces the same results as using /// [`libtest`'s `--nocapture` option][nocapture] which may make the results look unreadable. /// +/// [`fmt::Collector`]: ../struct.Collector.html /// [`fmt::Subscriber`]: ../struct.Subscriber.html -/// [`fmt::Layer`]: ../struct.Layer.html /// [capturing]: https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output /// [nocapture]: https://doc.rust-lang.org/cargo/commands/cargo-test.html /// [`io::stdout`]: https://doc.rust-lang.org/std/io/fn.stdout.html @@ -111,13 +111,13 @@ impl MakeWriter for TestWriter { /// /// # Examples /// -/// A function that returns a [`Subscriber`] that will write to either stdout or stderr: +/// A function that returns a [`Collect`] that will write to either stdout or stderr: /// /// ```rust -/// # use tracing::Subscriber; +/// # use tracing::Collect; /// # use tracing_subscriber::fmt::writer::BoxMakeWriter; /// -/// fn dynamic_writer(use_stderr: bool) -> impl Subscriber { +/// fn dynamic_writer(use_stderr: bool) -> impl Collect { /// let writer = if use_stderr { /// BoxMakeWriter::new(std::io::stderr) /// } else { @@ -129,7 +129,7 @@ impl MakeWriter for TestWriter { /// ``` /// /// [`MakeWriter`]: trait.MakeWriter.html -/// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html +/// [`Collect`]: https://docs.rs/tracing/latest/tracing/trait.Collect.html /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html pub struct BoxMakeWriter { inner: Box> + Send + Sync>, @@ -183,11 +183,11 @@ mod test { use super::MakeWriter; use crate::fmt::format::Format; use crate::fmt::test::{MockMakeWriter, MockWriter}; - use crate::fmt::Subscriber; + use crate::fmt::Collector; use lazy_static::lazy_static; use std::sync::Mutex; use tracing::error; - use tracing_core::dispatcher::{self, Dispatch}; + use tracing_core::dispatch::{self, Dispatch}; fn test_writer(make_writer: T, msg: &str, buf: &Mutex>) where @@ -197,7 +197,7 @@ mod test { #[cfg(feature = "ansi")] { let f = Format::default().without_time().with_ansi(false); - Subscriber::builder() + Collector::builder() .event_format(f) .with_writer(make_writer) .finish() @@ -205,7 +205,7 @@ mod test { #[cfg(not(feature = "ansi"))] { let f = Format::default().without_time(); - Subscriber::builder() + Collector::builder() .event_format(f) .with_writer(make_writer) .finish() @@ -213,7 +213,7 @@ mod test { }; let dispatch = Dispatch::from(subscriber); - dispatcher::with_default(&dispatch, || { + dispatch::with_default(&dispatch, || { error!("{}", msg); }); diff --git a/tracing-subscriber/src/lib.rs b/tracing-subscriber/src/lib.rs index b44493f1fc..c062062348 100644 --- a/tracing-subscriber/src/lib.rs +++ b/tracing-subscriber/src/lib.rs @@ -1,13 +1,13 @@ //! Utilities for implementing and composing [`tracing`] subscribers. //! //! [`tracing`] is a framework for instrumenting Rust programs to collect -//! scoped, structured, and async-aware diagnostics. The [`Subscriber`] trait +//! scoped, structured, and async-aware diagnostics. The [`Collect`] trait //! represents the functionality necessary to collect this trace data. This //! crate contains tools for composing subscribers out of smaller units of //! behaviour, and batteries-included implementations of common subscriber //! functionality. //! -//! `tracing-subscriber` is intended for use by both `Subscriber` authors and +//! `tracing-subscriber` is intended for use by both `Collector` authors and //! application authors using `tracing` to instrument their applications. //! //! *Compiler support: [requires `rustc` 1.42+][msrv]* @@ -16,7 +16,7 @@ //! //! ## Included Subscribers //! -//! The following `Subscriber`s are provided for application authors: +//! The following `Collector`s are provided for application authors: //! //! - [`fmt`] - Formats and logs tracing data (requires the `fmt` feature flag) //! @@ -58,7 +58,7 @@ //! long as doing so complies with this policy. //! //! [`tracing`]: https://docs.rs/tracing/latest/tracing/ -//! [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html +//! [`Collect`]: https://docs.rs/tracing-core/latest/tracing_core/collect/trait.Collect.html //! [`EnvFilter`]: filter/struct.EnvFilter.html //! [`fmt`]: fmt/index.html //! [`tracing-log`]: https://crates.io/crates/tracing-log @@ -103,10 +103,13 @@ mod macros; pub mod field; pub mod filter; -pub mod layer; +#[cfg(feature = "fmt")] +#[cfg_attr(docsrs, doc(cfg(feature = "fmt")))] +pub mod fmt; pub mod prelude; pub mod registry; pub mod reload; +pub mod subscribe; pub(crate) mod sync; pub(crate) mod thread; pub mod util; @@ -115,10 +118,9 @@ pub mod util; #[cfg_attr(docsrs, doc(cfg(feature = "env-filter")))] pub use filter::EnvFilter; -pub use layer::Layer; +pub use subscribe::Subscribe; cfg_feature!("fmt", { - pub mod fmt; pub use fmt::fmt; pub use fmt::Subscriber as FmtSubscriber; }); diff --git a/tracing-subscriber/src/prelude.rs b/tracing-subscriber/src/prelude.rs index 0264c2d508..a854cac8b1 100644 --- a/tracing-subscriber/src/prelude.rs +++ b/tracing-subscriber/src/prelude.rs @@ -7,8 +7,8 @@ pub use crate::field::{ MakeExt as __tracing_subscriber_field_MakeExt, RecordFields as __tracing_subscriber_field_RecordFields, }; -pub use crate::layer::{ - Layer as __tracing_subscriber_Layer, SubscriberExt as __tracing_subscriber_SubscriberExt, +pub use crate::subscribe::{ + CollectorExt as __tracing_subscriber_SubscriberExt, Subscribe as __tracing_subscriber_Layer, }; pub use crate::util::SubscriberInitExt as _; diff --git a/tracing-subscriber/src/registry/extensions.rs b/tracing-subscriber/src/registry/extensions.rs index 31e453a70b..87ec8edee8 100644 --- a/tracing-subscriber/src/registry/extensions.rs +++ b/tracing-subscriber/src/registry/extensions.rs @@ -64,9 +64,9 @@ impl<'a> ExtensionsMut<'a> { /// Insert a type into this `Extensions`. /// /// Note that extensions are _not_ - /// `Layer`-specific—they are _span_-specific. This means that + /// `Subscriber`-specific—they are _span_-specific. This means that /// other layers can access and mutate extensions that - /// a different Layer recorded. For example, an application might + /// a different Subscriber recorded. For example, an application might /// have a layer that records execution timings, alongside a layer /// that reports spans and events to a distributed /// tracing system that requires timestamps for spans. @@ -75,7 +75,7 @@ impl<'a> ExtensionsMut<'a> { /// /// Therefore, extensions should generally be newtypes, rather than common /// types like [`String`](https://doc.rust-lang.org/std/string/struct.String.html), to avoid accidental - /// cross-`Layer` clobbering. + /// cross-`Subscriber` clobbering. /// /// ## Panics /// @@ -107,20 +107,20 @@ impl<'a> ExtensionsMut<'a> { /// A type map of span extensions. /// /// [ExtensionsInner] is used by [Data] to store and -/// span-specific data. A given [Layer] can read and write +/// span-specific data. A given [Subscriber] can read and write /// data that it is interested in recording and emitting. #[derive(Default)] pub(crate) struct ExtensionsInner { - // If extensions are never used, no need to carry around an empty HashMap. - // That's 3 words. Instead, this is only 1 word. - map: Option>, + map: AnyMap, } impl ExtensionsInner { /// Create an empty `Extensions`. #[inline] pub(crate) fn new() -> ExtensionsInner { - ExtensionsInner { map: None } + ExtensionsInner { + map: AnyMap::default(), + } } /// Insert a type into this `Extensions`. @@ -129,7 +129,6 @@ impl ExtensionsInner { /// be returned. pub(crate) fn insert(&mut self, val: T) -> Option { self.map - .get_or_insert_with(|| Box::new(HashMap::default())) .insert(TypeId::of::(), Box::new(val)) .and_then(|boxed| { #[allow(warnings)] @@ -145,16 +144,14 @@ impl ExtensionsInner { /// Get a reference to a type previously inserted on this `Extensions`. pub(crate) fn get(&self) -> Option<&T> { self.map - .as_ref() - .and_then(|map| map.get(&TypeId::of::())) + .get(&TypeId::of::()) .and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref()) } /// Get a mutable reference to a type previously inserted on this `Extensions`. pub(crate) fn get_mut(&mut self) -> Option<&mut T> { self.map - .as_mut() - .and_then(|map| map.get_mut(&TypeId::of::())) + .get_mut(&TypeId::of::()) .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut()) } @@ -162,43 +159,109 @@ impl ExtensionsInner { /// /// If a extension of this type existed, it will be returned. pub(crate) fn remove(&mut self) -> Option { - self.map - .as_mut() - .and_then(|map| map.remove(&TypeId::of::())) - .and_then(|boxed| { - #[allow(warnings)] - { - (boxed as Box) - .downcast() - .ok() - .map(|boxed| *boxed) - } - }) + self.map.remove(&TypeId::of::()).and_then(|boxed| { + #[allow(warnings)] + { + (boxed as Box) + .downcast() + .ok() + .map(|boxed| *boxed) + } + }) + } + + /// Clear the `ExtensionsInner` in-place, dropping any elements in the map but + /// retaining allocated capacity. + /// + /// This permits the hash map allocation to be pooled by the registry so + /// that future spans will not need to allocate new hashmaps. + pub(crate) fn clear(&mut self) { + self.map.clear(); } } impl fmt::Debug for ExtensionsInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Extensions").finish() + f.debug_struct("Extensions") + .field("len", &self.map.len()) + .field("capacity", &self.map.capacity()) + .finish() } } -#[test] -fn test_extensions() { +#[cfg(test)] +mod tests { + use super::*; + #[derive(Debug, PartialEq)] struct MyType(i32); - let mut extensions = ExtensionsInner::new(); + #[test] + fn test_extensions() { + let mut extensions = ExtensionsInner::new(); + + extensions.insert(5i32); + extensions.insert(MyType(10)); + + assert_eq!(extensions.get(), Some(&5i32)); + assert_eq!(extensions.get_mut(), Some(&mut 5i32)); + + assert_eq!(extensions.remove::(), Some(5i32)); + assert!(extensions.get::().is_none()); + + assert_eq!(extensions.get::(), None); + assert_eq!(extensions.get(), Some(&MyType(10))); + } + + #[test] + fn clear_retains_capacity() { + let mut extensions = ExtensionsInner::new(); + extensions.insert(5i32); + extensions.insert(MyType(10)); + extensions.insert(true); + + assert_eq!(extensions.map.len(), 3); + let prev_capacity = extensions.map.capacity(); + extensions.clear(); + + assert_eq!( + extensions.map.len(), + 0, + "after clear(), extensions map should have length 0" + ); + assert_eq!( + extensions.map.capacity(), + prev_capacity, + "after clear(), extensions map should retain prior capacity" + ); + } + + #[test] + fn clear_drops_elements() { + use std::sync::Arc; + struct DropMePlease(Arc<()>); + struct DropMeTooPlease(Arc<()>); - extensions.insert(5i32); - extensions.insert(MyType(10)); + let mut extensions = ExtensionsInner::new(); + let val1 = DropMePlease(Arc::new(())); + let val2 = DropMeTooPlease(Arc::new(())); - assert_eq!(extensions.get(), Some(&5i32)); - assert_eq!(extensions.get_mut(), Some(&mut 5i32)); + let val1_dropped = Arc::downgrade(&val1.0); + let val2_dropped = Arc::downgrade(&val2.0); + extensions.insert(val1); + extensions.insert(val2); - assert_eq!(extensions.remove::(), Some(5i32)); - assert!(extensions.get::().is_none()); + assert!(val1_dropped.upgrade().is_some()); + assert!(val2_dropped.upgrade().is_some()); - assert_eq!(extensions.get::(), None); - assert_eq!(extensions.get(), Some(&MyType(10))); + extensions.clear(); + assert!( + val1_dropped.upgrade().is_none(), + "after clear(), val1 should be dropped" + ); + assert!( + val2_dropped.upgrade().is_none(), + "after clear(), val2 should be dropped" + ); + } } diff --git a/tracing-subscriber/src/registry/mod.rs b/tracing-subscriber/src/registry/mod.rs index f1fe72a434..f8a98465e0 100644 --- a/tracing-subscriber/src/registry/mod.rs +++ b/tracing-subscriber/src/registry/mod.rs @@ -1,24 +1,24 @@ -//! Storage for span data shared by multiple [`Layer`]s. +//! Storage for span data shared by multiple [`Subscribe`]s. //! //! ## Using the Span Registry //! -//! This module provides the [`Registry`] type, a [`Subscriber`] implementation -//! which tracks per-span data and exposes it to [`Layer`]s. When a `Registry` -//! is used as the base `Subscriber` of a `Layer` stack, the -//! [`layer::Context`][ctx] type will provide methods allowing `Layer`s to +//! This module provides the [`Registry`] type, a [`Collect`] implementation +//! which tracks per-span data and exposes it to subscribers. When a `Registry` +//! is used as the base `Collect` of a `Subscribe` stack, the +//! [`layer::Context`][ctx] type will provide methods allowing subscribers to //! [look up span data][lookup] stored in the registry. While [`Registry`] is a //! reasonable default for storing spans and events, other stores that implement -//! [`LookupSpan`] and [`Subscriber`] themselves (with [`SpanData`] implemented +//! [`LookupSpan`] and [`Collect`] themselves (with [`SpanData`] implemented //! by the per-span data they store) can be used as a drop-in replacement. //! -//! For example, we might create a `Registry` and add multiple `Layer`s like so: +//! For example, we might create a `Registry` and add multiple `Subscriber`s like so: //! ```rust -//! use tracing_subscriber::{registry::Registry, Layer, prelude::*}; -//! # use tracing_core::Subscriber; +//! use tracing_subscriber::{registry::Registry, Subscribe, prelude::*}; +//! # use tracing_core::Collect; //! # pub struct FooLayer {} //! # pub struct BarLayer {} -//! # impl Layer for FooLayer {} -//! # impl Layer for BarLayer {} +//! # impl Subscribe for FooLayer {} +//! # impl Subscribe for BarLayer {} //! # impl FooLayer { //! # fn new() -> Self { Self {} } //! # } @@ -31,32 +31,32 @@ //! .with(BarLayer::new()); //! ``` //! -//! If a type implementing `Layer` depends on the functionality of a `Registry` -//! implementation, it should bound its `Subscriber` type parameter with the +//! If a type implementing `Subscribe` depends on the functionality of a `Registry` +//! implementation, it should bound its `Collect` type parameter with the //! [`LookupSpan`] trait, like so: //! //! ```rust -//! use tracing_subscriber::{registry, Layer}; -//! use tracing_core::Subscriber; +//! use tracing_subscriber::{registry, Subscribe}; +//! use tracing_core::Collect; //! //! pub struct MyLayer { //! // ... //! } //! -//! impl Layer for MyLayer +//! impl Subscribe for MyLayer //! where -//! S: Subscriber + for<'a> registry::LookupSpan<'a>, +//! S: Collect + for<'a> registry::LookupSpan<'a>, //! { //! // ... //! } //! ``` -//! When this bound is added, the `Layer` implementation will be guaranteed +//! When this bound is added, the subscriber implementation will be guaranteed //! access to the [`Context`][ctx] methods, such as [`Context::span`][lookup], that -//! require the root subscriber to be a registry. +//! require the root collector to be a registry. //! -//! [`Layer`]: ../layer/trait.Layer.html -//! [`Subscriber`]: -//! https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html +//! [`Subscribe`]: ../layer/trait.serSubscribe.html +//! [`Collect`]: +//! https://docs.rs/tracing-core/latest/tracing_core/collect/trait.Collect.html //! [`Registry`]: struct.Registry.html //! [ctx]: ../layer/struct.Context.html //! [lookup]: ../layer/struct.Context.html#method.span @@ -82,10 +82,10 @@ pub use sharded::Registry; /// Provides access to stored span data. /// /// Subscribers which store span data and associate it with span IDs should -/// implement this trait; if they do, any [`Layer`]s wrapping them can look up +/// implement this trait; if they do, any [`Subscriber`]s wrapping them can look up /// metadata via the [`Context`] type's [`span()`] method. /// -/// [`Layer`]: ../layer/trait.Layer.html +/// [`Subscriber`]: ../layer/trait.Subscriber.html /// [`Context`]: ../layer/struct.Context.html /// [`span()`]: ../layer/struct.Context.html#method.span pub trait LookupSpan<'a> { @@ -146,13 +146,13 @@ pub trait SpanData<'a> { /// Returns a reference to this span's `Extensions`. /// - /// The extensions may be used by `Layer`s to store additional data + /// The extensions may be used by `Subscriber`s to store additional data /// describing the span. fn extensions(&self) -> Extensions<'_>; /// Returns a mutable reference to this span's `Extensions`. /// - /// The extensions may be used by `Layer`s to store additional data + /// The extensions may be used by `Subscriber`s to store additional data /// describing the span. fn extensions_mut(&self) -> ExtensionsMut<'_>; } @@ -279,7 +279,7 @@ where /// Returns a reference to this span's `Extensions`. /// - /// The extensions may be used by `Layer`s to store additional data + /// The extensions may be used by `Subscriber`s to store additional data /// describing the span. pub fn extensions(&self) -> Extensions<'_> { self.data.extensions() @@ -287,7 +287,7 @@ where /// Returns a mutable reference to this span's `Extensions`. /// - /// The extensions may be used by `Layer`s to store additional data + /// The extensions may be used by `Subscriber`s to store additional data /// describing the span. pub fn extensions_mut(&self) -> ExtensionsMut<'_> { self.data.extensions_mut() diff --git a/tracing-subscriber/src/registry/sharded.rs b/tracing-subscriber/src/registry/sharded.rs index 941d8b922b..4a457f6136 100644 --- a/tracing-subscriber/src/registry/sharded.rs +++ b/tracing-subscriber/src/registry/sharded.rs @@ -1,4 +1,4 @@ -use sharded_slab::{Guard, Slab}; +use sharded_slab::{pool::Ref, Clear, Pool}; use thread_local::ThreadLocal; use super::stack::SpanStack; @@ -14,40 +14,40 @@ use std::{ sync::atomic::{fence, AtomicUsize, Ordering}, }; use tracing_core::{ - dispatcher::{self, Dispatch}, + dispatch::{self, Dispatch}, span::{self, Current, Id}, - Event, Interest, Metadata, Subscriber, + Collect, Event, Interest, Metadata, }; /// A shared, reusable store for spans. /// -/// A `Registry` is a [`Subscriber`] around which multiple [`Layer`]s +/// A `Registry` is a [`Collect`] around which multiple subscribers /// implementing various behaviors may be [added]. Unlike other types -/// implementing `Subscriber` `Registry` does not actually record traces itself: -/// instead, it collects and stores span data that is exposed to any `Layer`s +/// implementing `Collect`, `Registry` does not actually record traces itself: +/// instead, it collects and stores span data that is exposed to any `Subscriber`s /// wrapping it through implementations of the [`LookupSpan`] trait. /// The `Registry` is responsible for storing span metadata, recording /// relationships between spans, and tracking which spans are active and whicb -/// are closed. In addition, it provides a mechanism for `Layer`s to store +/// are closed. In addition, it provides a mechanism for `Subscriber`s to store /// user-defined per-span data, called [extensions], in the registry. This -/// allows `Layer`-specific data to benefit from the `Registry`'s +/// allows `Subscriber`-specific data to benefit from the `Registry`'s /// high-performance concurrent storage. /// /// This registry is implemented using a [lock-free sharded slab][slab], and is /// highly optimized for concurrent access. /// /// [slab]: https://docs.rs/crate/sharded-slab/ -/// [`Subscriber`]: -/// https://docs.rs/crate/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html -/// [`Layer`]: ../trait.Layer.html -/// [added]: ../trait.Layer.html#method.with_subscriber +/// [`Collect`]: +/// https://docs.rs/crate/tracing-core/latest/tracing_core/collect/trait.Collect.html +/// [`Subscriber`]: ../trait.Subscriber.html +/// [added]: ../trait.Subscriber.html#method.with_subscriber /// [`LookupSpan`]: trait.LookupSpan.html /// [extensions]: extensions/index.html #[cfg(feature = "registry")] #[cfg_attr(docsrs, doc(cfg(feature = "registry")))] #[derive(Debug)] pub struct Registry { - spans: Slab, + spans: Pool, current_spans: ThreadLocal>, } @@ -55,24 +55,33 @@ pub struct Registry { /// /// The registry stores well-known data defined by tracing: span relationships, /// metadata and reference counts. Additional user-defined data provided by -/// [`Layer`s], such as formatted fields, metrics, or distributed traces should +/// [`Subscriber`s], such as formatted fields, metrics, or distributed traces should /// be stored in the [extensions] typemap. /// /// [`Registry`]: struct.Registry.html -/// [`Layer`s]: ../layer/trait.Layer.html +/// [`Subscriber`s]: ../layer/trait.Subscriber.html /// [extensions]: struct.Extensions.html #[cfg(feature = "registry")] #[cfg_attr(docsrs, doc(cfg(feature = "registry")))] #[derive(Debug)] pub struct Data<'a> { - inner: Guard<'a, DataInner>, + /// Immutable reference to the pooled `DataInner` entry. + inner: Ref<'a, DataInner>, } +/// Stored data associated with a span. +/// +/// This type is pooled using `sharded_slab::Pool`; when a span is dropped, the +/// `DataInner` entry at that span's slab index is cleared in place and reused +/// by a future span. Thus, the `Default` and `sharded_slab::Clear` +/// implementations for this type are load-bearing. #[derive(Debug)] struct DataInner { metadata: &'static Metadata<'static>, parent: Option, ref_count: AtomicUsize, + // The span's `Extensions` typemap. Allocations for the `HashMap` backing + // this are pooled and reused in place. pub(crate) extensions: RwLock, } @@ -81,7 +90,7 @@ struct DataInner { impl Default for Registry { fn default() -> Self { Self { - spans: Slab::new(), + spans: Pool::new(), current_spans: ThreadLocal::new(), } } @@ -97,20 +106,20 @@ fn id_to_idx(id: &Id) -> usize { id.into_u64() as usize - 1 } -/// A guard that tracks how many [`Registry`]-backed `Layer`s have +/// A guard that tracks how many [`Registry`]-backed `Subscriber`s have /// processed an `on_close` event. /// -/// This is needed to enable a [`Registry`]-backed Layer to access span -/// data after the `Layer` has recieved the `on_close` callback. +/// This is needed to enable a [`Registry`]-backed Subscriber to access span +/// data after the `Subscriber` has recieved the `on_close` callback. /// -/// Once all `Layer`s have processed this event, the [`Registry`] knows +/// Once all `Subscriber`s have processed this event, the [`Registry`] knows /// that is able to safely remove the span tracked by `id`. `CloseGuard` /// accomplishes this through a two-step process: -/// 1. Whenever a [`Registry`]-backed `Layer::on_close` method is +/// 1. Whenever a [`Registry`]-backed `Subscriber::on_close` method is /// called, `Registry::start_close` is closed. /// `Registry::start_close` increments a thread-local `CLOSE_COUNT` /// by 1 and returns a `CloseGuard`. -/// 2. The `CloseGuard` is dropped at the end of `Layer::on_close`. On +/// 2. The `CloseGuard` is dropped at the end of `Subscriber::on_close`. On /// drop, `CloseGuard` checks thread-local `CLOSE_COUNT`. If /// `CLOSE_COUNT` is 0, the `CloseGuard` removes the span with the /// `id` from the registry, as all `Layers` that might have seen the @@ -126,15 +135,11 @@ pub(crate) struct CloseGuard<'a> { } impl Registry { - fn insert(&self, s: DataInner) -> Option { - self.spans.insert(s) - } - - fn get(&self, id: &Id) -> Option> { + fn get(&self, id: &Id) -> Option> { self.spans.get(id_to_idx(id)) } - /// Returns a guard which tracks how many `Layer`s have + /// Returns a guard which tracks how many `Subscriber`s have /// processed an `on_close` notification via the `CLOSE_COUNT` thread-local. /// For additional details, see [`CloseGuard`]. /// @@ -161,7 +166,7 @@ thread_local! { static CLOSE_COUNT: Cell = Cell::new(0); } -impl Subscriber for Registry { +impl Collect for Registry { fn register_callsite(&self, _: &'static Metadata<'static>) -> Interest { Interest::always() } @@ -180,13 +185,20 @@ impl Subscriber for Registry { attrs.parent().map(|id| self.clone_span(id)) }; - let s = DataInner { - metadata: attrs.metadata(), - parent, - ref_count: AtomicUsize::new(1), - extensions: RwLock::new(ExtensionsInner::new()), - }; - let id = self.insert(s).expect("Unable to allocate another span"); + let id = self + .spans + // Check out a `DataInner` entry from the pool for the new span. If + // there are free entries already allocated in the pool, this will + // preferentially reuse one; otherwise, a new `DataInner` is + // allocated and added to the pool. + .create_with(|data| { + data.metadata = attrs.metadata(); + data.parent = parent; + let refs = data.ref_count.get_mut(); + debug_assert_eq!(*refs, 0); + *refs = 1; + }) + .expect("Unable to allocate another span"); idx_to_id(id) } @@ -215,7 +227,7 @@ impl Subscriber for Registry { fn exit(&self, id: &span::Id) { if let Some(spans) = self.current_spans.get() { if spans.borrow_mut().pop(id) { - dispatcher::get_default(|dispatch| dispatch.try_close(id.clone())); + dispatch::get_default(|dispatch| dispatch.try_close(id.clone())); } } } @@ -230,7 +242,11 @@ impl Subscriber for Registry { // calls to `try_close`: we have to ensure that all threads have // dropped their refs to the span before the span is closed. let refs = span.ref_count.fetch_add(1, Ordering::Relaxed); - assert!(refs != 0, "tried to clone a span that already closed"); + assert!( + refs != 0, + "tried to clone a span ({:?}) that already closed", + id + ); id.clone() } @@ -282,34 +298,7 @@ impl<'a> LookupSpan<'a> for Registry { } } -// === impl DataInner === - -impl Drop for DataInner { - // A span is not considered closed until all of its children have closed. - // Therefore, each span's `DataInner` holds a "reference" to the parent - // span, keeping the parent span open until all its children have closed. - // When we close a span, we must then decrement the parent's ref count - // (potentially, allowing it to close, if this child is the last reference - // to that span). - fn drop(&mut self) { - // We have to actually unpack the option inside the `get_default` - // closure, since it is a `FnMut`, but testing that there _is_ a value - // here lets us avoid the thread-local access if we don't need the - // dispatcher at all. - if self.parent.is_some() { - // Note that --- because `Layered::try_close` works by calling - // `try_close` on the inner subscriber and using the return value to - // determine whether to call the `Layer`'s `on_close` callback --- - // we must call `try_close` on the entire subscriber stack, rather - // than just on the registry. If the registry called `try_close` on - // itself directly, the layers wouldn't see the close notification. - let subscriber = dispatcher::get_default(Dispatch::clone); - if let Some(parent) = self.parent.take() { - let _ = subscriber.try_close(parent); - } - } - } -} +// === impl CloseGuard === impl<'a> CloseGuard<'a> { pub(crate) fn is_closing(&mut self) { @@ -336,7 +325,7 @@ impl<'a> Drop for CloseGuard<'a> { // `on_close` call. If the span is closing, it's okay to remove the // span. if c == 1 && self.is_closing { - self.registry.spans.remove(id_to_idx(&self.id)); + self.registry.spans.clear(id_to_idx(&self.id)); } }); } @@ -366,27 +355,111 @@ impl<'a> SpanData<'a> for Data<'a> { } } +// === impl DataInner === + +impl Default for DataInner { + fn default() -> Self { + // Since `DataInner` owns a `&'static Callsite` pointer, we need + // something to use as the initial default value for that callsite. + // Since we can't access a `DataInner` until it has had actual span data + // inserted into it, the null metadata will never actually be accessed. + struct NullCallsite; + impl tracing_core::callsite::Callsite for NullCallsite { + fn set_interest(&self, _: Interest) { + unreachable!( + "/!\\ Tried to register the null callsite /!\\\n \ + This should never have happened and is definitely a bug. \ + A `tracing` bug report would be appreciated." + ) + } + + fn metadata(&self) -> &Metadata<'_> { + unreachable!( + "/!\\ Tried to access the null callsite's metadata /!\\\n \ + This should never have happened and is definitely a bug. \ + A `tracing` bug report would be appreciated." + ) + } + } + + static NULL_CALLSITE: NullCallsite = NullCallsite; + static NULL_METADATA: Metadata<'static> = tracing_core::metadata! { + name: "", + target: "", + level: tracing_core::Level::TRACE, + fields: &[], + callsite: &NULL_CALLSITE, + kind: tracing_core::metadata::Kind::SPAN, + }; + + Self { + metadata: &NULL_METADATA, + parent: None, + ref_count: AtomicUsize::new(0), + extensions: RwLock::new(ExtensionsInner::new()), + } + } +} + +impl Clear for DataInner { + /// Clears the span's data in place, dropping the parent's reference count. + fn clear(&mut self) { + // A span is not considered closed until all of its children have closed. + // Therefore, each span's `DataInner` holds a "reference" to the parent + // span, keeping the parent span open until all its children have closed. + // When we close a span, we must then decrement the parent's ref count + // (potentially, allowing it to close, if this child is the last reference + // to that span). + // We have to actually unpack the option inside the `get_default` + // closure, since it is a `FnMut`, but testing that there _is_ a value + // here lets us avoid the thread-local access if we don't need the + // dispatcher at all. + if self.parent.is_some() { + // Note that --- because `Layered::try_close` works by calling + // `try_close` on the inner subscriber and using the return value to + // determine whether to call the `Layer`'s `on_close` callback --- + // we must call `try_close` on the entire subscriber stack, rather + // than just on the registry. If the registry called `try_close` on + // itself directly, the layers wouldn't see the close notification. + let subscriber = dispatch::get_default(Dispatch::clone); + if let Some(parent) = self.parent.take() { + let _ = subscriber.try_close(parent); + } + } + + // Clear (but do not deallocate!) the pooled `HashMap` for the span's extensions. + self.extensions + .get_mut() + .unwrap_or_else(|l| { + // This function can be called in a `Drop` impl, such as while + // panicking, so ignore lock poisoning. + l.into_inner() + }) + .clear(); + } +} + #[cfg(test)] mod tests { use super::Registry; - use crate::{layer::Context, registry::LookupSpan, Layer}; + use crate::{registry::LookupSpan, subscribe::Context, Subscribe}; use std::{ collections::HashMap, sync::{Arc, Mutex, Weak}, }; - use tracing::{self, subscriber::with_default}; + use tracing::{self, collect::with_default}; use tracing_core::{ - dispatcher, + dispatch, span::{Attributes, Id}, - Subscriber, + Collect, }; - struct AssertionLayer; - impl Layer for AssertionLayer + struct AssertionSubscriber; + impl Subscribe for AssertionSubscriber where - S: Subscriber + for<'a> LookupSpan<'a>, + C: Collect + for<'a> LookupSpan<'a>, { - fn on_close(&self, id: Id, ctx: Context<'_, S>) { + fn on_close(&self, id: Id, ctx: Context<'_, C>) { dbg!(format_args!("closing {:?}", id)); assert!(&ctx.span(&id).is_some()); } @@ -394,7 +467,7 @@ mod tests { #[test] fn single_layer_can_access_closed_span() { - let subscriber = AssertionLayer.with_subscriber(Registry::default()); + let subscriber = AssertionSubscriber.with_collector(Registry::default()); with_default(subscriber, || { let span = tracing::debug_span!("span"); @@ -404,9 +477,9 @@ mod tests { #[test] fn multiple_layers_can_access_closed_span() { - let subscriber = AssertionLayer - .and_then(AssertionLayer) - .with_subscriber(Registry::default()); + let subscriber = AssertionSubscriber + .and_then(AssertionSubscriber) + .with_collector(Registry::default()); with_default(subscriber, || { let span = tracing::debug_span!("span"); @@ -430,9 +503,9 @@ mod tests { struct SetRemoved(Arc<()>); - impl Layer for CloseLayer + impl Subscribe for CloseLayer where - S: Subscriber + for<'a> LookupSpan<'a>, + S: Collect + for<'a> LookupSpan<'a>, { fn new_span(&self, _: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) { let span = ctx.span(id).expect("Missing span; this is a bug"); @@ -585,18 +658,18 @@ mod tests { #[test] fn spans_are_removed_from_registry() { let (close_layer, state) = CloseLayer::new(); - let subscriber = AssertionLayer + let subscriber = AssertionSubscriber .and_then(close_layer) - .with_subscriber(Registry::default()); + .with_collector(Registry::default()); // Create a `Dispatch` (which is internally reference counted) so that // the subscriber lives to the end of the test. Otherwise, if we just // passed the subscriber itself to `with_default`, we could see the span // be dropped when the subscriber itself is dropped, destroying the // registry. - let dispatch = dispatcher::Dispatch::new(subscriber); + let dispatch = dispatch::Dispatch::new(subscriber); - dispatcher::with_default(&dispatch, || { + dispatch::with_default(&dispatch, || { let span = tracing::debug_span!("span1"); drop(span); let span = tracing::info_span!("span2"); @@ -613,18 +686,18 @@ mod tests { #[test] fn spans_are_only_closed_when_the_last_ref_drops() { let (close_layer, state) = CloseLayer::new(); - let subscriber = AssertionLayer + let subscriber = AssertionSubscriber .and_then(close_layer) - .with_subscriber(Registry::default()); + .with_collector(Registry::default()); // Create a `Dispatch` (which is internally reference counted) so that // the subscriber lives to the end of the test. Otherwise, if we just // passed the subscriber itself to `with_default`, we could see the span // be dropped when the subscriber itself is dropped, destroying the // registry. - let dispatch = dispatcher::Dispatch::new(subscriber); + let dispatch = dispatch::Dispatch::new(subscriber); - let span2 = dispatcher::with_default(&dispatch, || { + let span2 = dispatch::with_default(&dispatch, || { let span = tracing::debug_span!("span1"); drop(span); let span2 = tracing::info_span!("span2"); @@ -646,18 +719,18 @@ mod tests { #[test] fn span_enter_guards_are_dropped_out_of_order() { let (close_layer, state) = CloseLayer::new(); - let subscriber = AssertionLayer + let subscriber = AssertionSubscriber .and_then(close_layer) - .with_subscriber(Registry::default()); + .with_collector(Registry::default()); // Create a `Dispatch` (which is internally reference counted) so that // the subscriber lives to the end of the test. Otherwise, if we just // passed the subscriber itself to `with_default`, we could see the span // be dropped when the subscriber itself is dropped, destroying the // registry. - let dispatch = dispatcher::Dispatch::new(subscriber); + let dispatch = dispatch::Dispatch::new(subscriber); - dispatcher::with_default(&dispatch, || { + dispatch::with_default(&dispatch, || { let span1 = tracing::debug_span!("span1"); let span2 = tracing::info_span!("span2"); @@ -686,11 +759,11 @@ mod tests { // closes, and will then be closed. let (close_layer, state) = CloseLayer::new(); - let subscriber = close_layer.with_subscriber(Registry::default()); + let subscriber = close_layer.with_collector(Registry::default()); - let dispatch = dispatcher::Dispatch::new(subscriber); + let dispatch = dispatch::Dispatch::new(subscriber); - dispatcher::with_default(&dispatch, || { + dispatch::with_default(&dispatch, || { let span1 = tracing::info_span!("parent"); let span2 = tracing::info_span!(parent: &span1, "child"); @@ -713,11 +786,11 @@ mod tests { // is *itself* kept open by a child, closing the grandchild will close // both the parent *and* the grandparent. let (close_layer, state) = CloseLayer::new(); - let subscriber = close_layer.with_subscriber(Registry::default()); + let subscriber = close_layer.with_collector(Registry::default()); - let dispatch = dispatcher::Dispatch::new(subscriber); + let dispatch = dispatch::Dispatch::new(subscriber); - dispatcher::with_default(&dispatch, || { + dispatch::with_default(&dispatch, || { let span1 = tracing::info_span!("grandparent"); let span2 = tracing::info_span!(parent: &span1, "parent"); let span3 = tracing::info_span!(parent: &span2, "child"); diff --git a/tracing-subscriber/src/reload.rs b/tracing-subscriber/src/reload.rs index c302144dae..0bde3fd9ca 100644 --- a/tracing-subscriber/src/reload.rs +++ b/tracing-subscriber/src/reload.rs @@ -1,17 +1,16 @@ -//! Wrapper for a `Layer` to allow it to be dynamically reloaded. +//! Wrapper for a `Collect` or `Subscribe` to allow it to be dynamically reloaded. //! -//! This module provides a [`Layer` type] which wraps another type implementing -//! the [`Layer` trait], allowing the wrapped type to be replaced with another +//! This module provides a type implementing [`Subscribe`] which wraps another type implementing +//! the [`Subscribe`] trait, allowing the wrapped type to be replaced with another //! instance of that type at runtime. //! -//! This can be used in cases where a subset of `Subscriber` functionality +//! This can be used in cases where a subset of `Collect` functionality //! should be dynamically reconfigured, such as when filtering directives may -//! change at runtime. Note that this layer introduces a (relatively small) +//! change at runtime. Note that this subscriber introduces a (relatively small) //! amount of overhead, and should thus only be used as needed. //! -//! [`Layer` type]: struct.Layer.html -//! [`Layer` trait]: ../layer/trait.Layer.html -use crate::layer; +//! [`Subscribe`]: ../subscriber/trait.Subscribe.html +use crate::subscribe; use crate::sync::RwLock; use std::{ @@ -19,28 +18,28 @@ use std::{ sync::{Arc, Weak}, }; use tracing_core::{ - callsite, span, - subscriber::{Interest, Subscriber}, - Event, Metadata, + callsite, + collect::{Collect, Interest}, + span, Event, Metadata, }; -/// Wraps a `Layer`, allowing it to be reloaded dynamically at runtime. +/// Wraps a `Collect` or `Subscribe`, allowing it to be reloaded dynamically at runtime. #[derive(Debug)] -pub struct Layer { +pub struct Subscriber { // TODO(eliza): this once used a `crossbeam_util::ShardedRwLock`. We may // eventually wish to replace it with a sharded lock implementation on top // of our internal `RwLock` wrapper type. If possible, we should profile // this first to determine if it's necessary. - inner: Arc>, + inner: Arc>, } -/// Allows reloading the state of an associated `Layer`. +/// Allows reloading the state of an associated `Collect`. #[derive(Debug)] -pub struct Handle { - inner: Weak>, +pub struct Handle { + inner: Weak>, } -/// Indicates that an error occurred when reloading a layer. +/// Indicates that an error occurred when reloading a subscriber. #[derive(Debug)] pub struct Error { kind: ErrorKind, @@ -48,16 +47,16 @@ pub struct Error { #[derive(Debug)] enum ErrorKind { - SubscriberGone, + CollectorGone, Poisoned, } -// ===== impl Layer ===== +// ===== impl Collect ===== -impl crate::Layer for Layer +impl crate::Subscribe for Subscriber where - L: crate::Layer + 'static, - S: Subscriber, + S: crate::Subscribe + 'static, + C: Collect, { #[inline] fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest { @@ -65,55 +64,65 @@ where } #[inline] - fn enabled(&self, metadata: &Metadata<'_>, ctx: layer::Context<'_, S>) -> bool { + fn enabled(&self, metadata: &Metadata<'_>, ctx: subscribe::Context<'_, C>) -> bool { try_lock!(self.inner.read(), else return false).enabled(metadata, ctx) } #[inline] - fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: layer::Context<'_, S>) { + fn new_span( + &self, + attrs: &span::Attributes<'_>, + id: &span::Id, + ctx: subscribe::Context<'_, C>, + ) { try_lock!(self.inner.read()).new_span(attrs, id, ctx) } #[inline] - fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: layer::Context<'_, S>) { + fn on_record( + &self, + span: &span::Id, + values: &span::Record<'_>, + ctx: subscribe::Context<'_, C>, + ) { try_lock!(self.inner.read()).on_record(span, values, ctx) } #[inline] - fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: layer::Context<'_, S>) { + fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: subscribe::Context<'_, C>) { try_lock!(self.inner.read()).on_follows_from(span, follows, ctx) } #[inline] - fn on_event(&self, event: &Event<'_>, ctx: layer::Context<'_, S>) { + fn on_event(&self, event: &Event<'_>, ctx: subscribe::Context<'_, C>) { try_lock!(self.inner.read()).on_event(event, ctx) } #[inline] - fn on_enter(&self, id: &span::Id, ctx: layer::Context<'_, S>) { + fn on_enter(&self, id: &span::Id, ctx: subscribe::Context<'_, C>) { try_lock!(self.inner.read()).on_enter(id, ctx) } #[inline] - fn on_exit(&self, id: &span::Id, ctx: layer::Context<'_, S>) { + fn on_exit(&self, id: &span::Id, ctx: subscribe::Context<'_, C>) { try_lock!(self.inner.read()).on_exit(id, ctx) } #[inline] - fn on_close(&self, id: span::Id, ctx: layer::Context<'_, S>) { + fn on_close(&self, id: span::Id, ctx: subscribe::Context<'_, C>) { try_lock!(self.inner.read()).on_close(id, ctx) } #[inline] - fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: layer::Context<'_, S>) { + fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: subscribe::Context<'_, C>) { try_lock!(self.inner.read()).on_id_change(old, new, ctx) } } -impl Layer { - /// Wraps the given `Layer`, returning a `Layer` and a `Handle` that allows +impl Subscriber { + /// Wraps the given `Subscribe`, returning a subscriber and a `Handle` that allows /// the inner type to be modified at runtime. - pub fn new(inner: L) -> (Self, Handle) { + pub fn new(inner: S) -> (Self, Handle) { let this = Self { inner: Arc::new(RwLock::new(inner)), }; @@ -121,8 +130,8 @@ impl Layer { (this, handle) } - /// Returns a `Handle` that can be used to reload the wrapped `Layer`. - pub fn handle(&self) -> Handle { + /// Returns a `Handle` that can be used to reload the wrapped `Subscribe`. + pub fn handle(&self) -> Handle { Handle { inner: Arc::downgrade(&self.inner), } @@ -131,52 +140,52 @@ impl Layer { // ===== impl Handle ===== -impl Handle { - /// Replace the current layer with the provided `new_layer`. - pub fn reload(&self, new_layer: impl Into) -> Result<(), Error> { - self.modify(|layer| { - *layer = new_layer.into(); +impl Handle { + /// Replace the current subscriber with the provided `new_subscriber`. + pub fn reload(&self, new_subscriber: impl Into) -> Result<(), Error> { + self.modify(|subscriber| { + *subscriber = new_subscriber.into(); }) } - /// Invokes a closure with a mutable reference to the current layer, + /// Invokes a closure with a mutable reference to the current subscriber, /// allowing it to be modified in place. - pub fn modify(&self, f: impl FnOnce(&mut L)) -> Result<(), Error> { + pub fn modify(&self, f: impl FnOnce(&mut S)) -> Result<(), Error> { let inner = self.inner.upgrade().ok_or(Error { - kind: ErrorKind::SubscriberGone, + kind: ErrorKind::CollectorGone, })?; let mut lock = try_lock!(inner.write(), else return Err(Error::poisoned())); f(&mut *lock); // Release the lock before rebuilding the interest cache, as that - // function will lock the new layer. + // function will lock the new subscriber. drop(lock); callsite::rebuild_interest_cache(); Ok(()) } - /// Returns a clone of the layer's current value if it still exists. - /// Otherwise, if the subscriber has been dropped, returns `None`. - pub fn clone_current(&self) -> Option + /// Returns a clone of the subscriber's current value if it still exists. + /// Otherwise, if the collector has been dropped, returns `None`. + pub fn clone_current(&self) -> Option where - L: Clone, + S: Clone, { - self.with_current(L::clone).ok() + self.with_current(S::clone).ok() } - /// Invokes a closure with a borrowed reference to the current layer, - /// returning the result (or an error if the subscriber no longer exists). - pub fn with_current(&self, f: impl FnOnce(&L) -> T) -> Result { + /// Invokes a closure with a borrowed reference to the current subscriber, + /// returning the result (or an error if the collector no longer exists). + pub fn with_current(&self, f: impl FnOnce(&S) -> T) -> Result { let inner = self.inner.upgrade().ok_or(Error { - kind: ErrorKind::SubscriberGone, + kind: ErrorKind::CollectorGone, })?; let inner = try_lock!(inner.read(), else return Err(Error::poisoned())); Ok(f(&*inner)) } } -impl Clone for Handle { +impl Clone for Handle { fn clone(&self) -> Self { Handle { inner: self.inner.clone(), @@ -193,23 +202,23 @@ impl Error { } } - /// Returns `true` if this error occurred because the layer was poisoned by + /// Returns `true` if this error occurred because the subscriber was poisoned by /// a panic on another thread. pub fn is_poisoned(&self) -> bool { matches!(self.kind, ErrorKind::Poisoned) } - /// Returns `true` if this error occurred because the `Subscriber` - /// containing the reloadable layer was dropped. + /// Returns `true` if this error occurred because the `Collector` + /// containing the reloadable subscriber was dropped. pub fn is_dropped(&self) -> bool { - matches!(self.kind, ErrorKind::SubscriberGone) + matches!(self.kind, ErrorKind::CollectorGone) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match self.kind { - ErrorKind::SubscriberGone => "subscriber no longer exists", + ErrorKind::CollectorGone => "subscriber no longer exists", ErrorKind::Poisoned => "lock poisoned", }; f.pad(msg) diff --git a/tracing-subscriber/src/layer.rs b/tracing-subscriber/src/subscribe.rs similarity index 62% rename from tracing-subscriber/src/layer.rs rename to tracing-subscriber/src/subscribe.rs index e3609c9b18..455852ea22 100644 --- a/tracing-subscriber/src/layer.rs +++ b/tracing-subscriber/src/subscribe.rs @@ -1,9 +1,8 @@ -//! A composable abstraction for building `Subscriber`s. +//! A composable abstraction for building `Collector`s. use tracing_core::{ + collect::{Collect, Interest}, metadata::Metadata, - span, - subscriber::{Interest, Subscriber}, - Event, LevelFilter, + span, Event, LevelFilter, }; #[cfg(feature = "registry")] @@ -12,60 +11,60 @@ use std::{any::TypeId, marker::PhantomData}; /// A composable handler for `tracing` events. /// -/// The [`Subscriber`] trait in `tracing-core` represents the _complete_ set of +/// The [`Collect`] trait in `tracing-core` represents the _complete_ set of /// functionality required to consume `tracing` instrumentation. This means that -/// a single `Subscriber` instance is a self-contained implementation of a +/// a single `Collector` instance is a self-contained implementation of a /// complete strategy for collecting traces; but it _also_ means that the -/// `Subscriber` trait cannot easily be composed with other `Subscriber`s. +/// `Collector` trait cannot easily be composed with other `Collector`s. /// -/// In particular, [`Subscriber`]'s are responsible for generating [span IDs] and +/// In particular, collectors are responsible for generating [span IDs] and /// assigning them to spans. Since these IDs must uniquely identify a span /// within the context of the current trace, this means that there may only be -/// a single `Subscriber` for a given thread at any point in time — +/// a single `Collector` for a given thread at any point in time — /// otherwise, there would be no authoritative source of span IDs. /// -/// On the other hand, the majority of the [`Subscriber`] trait's functionality -/// is composable: any number of subscribers may _observe_ events, span entry +/// On the other hand, the majority of the [`Collect`] trait's functionality +/// is composable: any number of collectors may _observe_ events, span entry /// and exit, and so on, provided that there is a single authoritative source of -/// span IDs. The `Layer` trait represents this composable subset of the -/// [`Subscriber`] behavior; it can _observe_ events and spans, but does not +/// span IDs. The `Subscribe` trait represents this composable subset of the +/// [`Collect`]'s behavior; it can _observe_ events and spans, but does not /// assign IDs. /// -/// ## Composing Layers +/// ## Composing Subscribers /// -/// Since a `Layer` does not implement a complete strategy for collecting -/// traces, it must be composed with a `Subscriber` in order to be used. The -/// `Layer` trait is generic over a type parameter (called `S` in the trait -/// definition), representing the types of `Subscriber` they can be composed -/// with. Thus, a `Layer` may be implemented that will only compose with a -/// particular `Subscriber` implementation, or additional trait bounds may be -/// added to constrain what types implementing `Subscriber` a `Layer` can wrap. +/// Since `Subscribe` does not implement a complete strategy for collecting +/// traces, it must be composed with a `Collect` in order to be used. The +/// `Subscribe` trait is generic over a type parameter (called `S` in the trait +/// definition), representing the types of `Collect` they can be composed +/// with. Thus, a subscriber may be implemented that will only compose with a +/// particular `Collect` implementation, or additional trait bounds may be +/// added to constrain what types implementing `Collect` a subscriber can wrap. /// -/// `Layer`s may be added to a `Subscriber` by using the [`SubscriberExt::with`] +/// Subscribers may be added to a `Collect` by using the [`SubscriberExt::with`] /// method, which is provided by `tracing-subscriber`'s [prelude]. This method -/// returns a [`Layered`] struct that implements `Subscriber` by composing the -/// `Layer` with the `Subscriber`. +/// returns a [`Layered`] struct that implements `Collect` by composing the +/// subscriber with the collector. /// /// For example: /// ```rust -/// use tracing_subscriber::Layer; +/// use tracing_subscriber::Subscribe; /// use tracing_subscriber::prelude::*; -/// use tracing::Subscriber; +/// use tracing::Collect; /// -/// pub struct MyLayer { +/// pub struct MySubscriber { /// // ... /// } /// -/// impl Layer for MyLayer { +/// impl Subscribe for MySubscriber { /// // ... /// } /// -/// pub struct MySubscriber { +/// pub struct MyCollector { /// // ... /// } /// /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event}; -/// impl Subscriber for MySubscriber { +/// impl Collect for MySubscriber { /// // ... /// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) } /// # fn record(&self, _: &Id, _: &Record) {} @@ -75,44 +74,44 @@ use std::{any::TypeId, marker::PhantomData}; /// # fn enter(&self, _: &Id) {} /// # fn exit(&self, _: &Id) {} /// } -/// # impl MyLayer { +/// # impl MySubscriber { /// # fn new() -> Self { Self {} } /// # } -/// # impl MySubscriber { +/// # impl MyCollector { /// # fn new() -> Self { Self { }} /// # } /// -/// let subscriber = MySubscriber::new() -/// .with(MyLayer::new()); +/// let collector = MySubscriber::new() +/// .with(MySubscriber::new()); /// -/// tracing::subscriber::set_global_default(subscriber); +/// tracing::collect::set_global_default(collector); /// ``` /// -/// Multiple `Layer`s may be composed in the same manner: +/// Multiple `Subscriber`s may be composed in the same manner: /// ```rust -/// # use tracing_subscriber::Layer; +/// # use tracing_subscriber::Subscribe; /// # use tracing_subscriber::prelude::*; -/// # use tracing::Subscriber; -/// pub struct MyOtherLayer { +/// # use tracing::Collect; +/// pub struct MyOtherSubscriber { /// // ... /// } /// -/// impl Layer for MyOtherLayer { +/// impl Subscribe for MyOtherSubscriber { /// // ... /// } /// -/// pub struct MyThirdLayer { +/// pub struct MyThirdSubscriber { /// // ... /// } /// -/// impl Layer for MyThirdLayer { +/// impl Subscribe for MyThirdSubscriber { /// // ... /// } -/// # pub struct MyLayer {} -/// # impl Layer for MyLayer {} -/// # pub struct MySubscriber { } +/// # pub struct MySubscriber {} +/// # impl Subscribe for MySubscriber {} +/// # pub struct MyCollector { } /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event}; -/// # impl Subscriber for MySubscriber { +/// # impl Collect for MyCollector { /// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) } /// # fn record(&self, _: &Id, _: &Record) {} /// # fn event(&self, _: &Event) {} @@ -121,93 +120,93 @@ use std::{any::TypeId, marker::PhantomData}; /// # fn enter(&self, _: &Id) {} /// # fn exit(&self, _: &Id) {} /// } -/// # impl MyLayer { +/// # impl MySubscriber { /// # fn new() -> Self { Self {} } /// # } -/// # impl MyOtherLayer { +/// # impl MyOtherSubscriber { /// # fn new() -> Self { Self {} } /// # } -/// # impl MyThirdLayer { +/// # impl MyThirdSubscriber { /// # fn new() -> Self { Self {} } /// # } -/// # impl MySubscriber { +/// # impl MyCollector { /// # fn new() -> Self { Self { }} /// # } /// -/// let subscriber = MySubscriber::new() -/// .with(MyLayer::new()) -/// .with(MyOtherLayer::new()) -/// .with(MyThirdLayer::new()); +/// let collector = MyCollector::new() +/// .with(MySubscriber::new()) +/// .with(MyOtherSubscriber::new()) +/// .with(MyThirdSubscriber::new()); /// -/// tracing::subscriber::set_global_default(subscriber); +/// tracing::collect::set_global_default(collector); /// ``` /// -/// The [`Layer::with_subscriber` method][with-sub] constructs the `Layered` -/// type from a `Layer` and `Subscriber`, and is called by +/// The [`Subscribe::with_collector` method][with-col] constructs the `Layered` +/// type from a `Subscribe` and `Collect`, and is called by /// [`SubscriberExt::with`]. In general, it is more idiomatic to use -/// `SubscriberExt::with`, and treat `Layer::with_subscriber` as an -/// implementation detail, as `with_subscriber` calls must be nested, leading to -/// less clear code for the reader. However, `Layer`s which wish to perform +/// `SubscriberExt::with`, and treat `Subscribe::with_collector` as an +/// implementation detail, as `with_collector` calls must be nested, leading to +/// less clear code for the reader. However, subscribers which wish to perform /// additional behavior when composed with a subscriber may provide their own /// implementations of `SubscriberExt::with`. /// /// [`SubscriberExt::with`]: trait.SubscriberExt.html#method.with /// [`Layered`]: struct.Layered.html /// [prelude]: ../prelude/index.html -/// [with-sub]: #method.with_subscriber +/// [with-col]: #method.with_collector /// /// ## Recording Traces /// -/// The `Layer` trait defines a set of methods for consuming notifications from +/// The `Subscribe` trait defines a set of methods for consuming notifications from /// tracing instrumentation, which are generally equivalent to the similarly -/// named methods on [`Subscriber`]. Unlike [`Subscriber`], the methods on -/// `Layer` are additionally passed a [`Context`] type, which exposes additional -/// information provided by the wrapped subscriber (such as [the current span]) -/// to the layer. +/// named methods on [`Collect`]. Unlike [`Collect`], the methods on +/// `Subscribe` are additionally passed a [`Context`] type, which exposes additional +/// information provided by the wrapped collector (such as [the current span]) +/// to the subscriber. /// -/// ## Filtering with `Layer`s +/// ## Filtering with Subscribers /// -/// As well as strategies for handling trace events, the `Layer` trait may also +/// As well as strategies for handling trace events, the `Subscriber` trait may also /// be used to represent composable _filters_. This allows the determination of /// what spans and events should be recorded to be decoupled from _how_ they are /// recorded: a filtering layer can be applied to other layers or -/// subscribers. A `Layer` that implements a filtering strategy should override the +/// subscribers. A `Subscriber` that implements a filtering strategy should override the /// [`register_callsite`] and/or [`enabled`] methods. It may also choose to implement /// methods such as [`on_enter`], if it wishes to filter trace events based on /// the current span context. /// -/// Note that the [`Layer::register_callsite`] and [`Layer::enabled`] methods +/// Note that the [`Subscribe::register_callsite`] and [`Subscribe::enabled`] methods /// determine whether a span or event is enabled *globally*. Thus, they should /// **not** be used to indicate whether an individual layer wishes to record a -/// particular span or event. Instead, if a layer is only interested in a subset +/// particular span or event. Instead, if a subscriber is only interested in a subset /// of trace data, but does *not* wish to disable other spans and events for the -/// rest of the layer stack should ignore those spans and events in its +/// rest of the subscriber stack should ignore those spans and events in its /// notification methods. /// -/// The filtering methods on a stack of `Layer`s are evaluated in a top-down -/// order, starting with the outermost `Layer` and ending with the wrapped -/// [`Subscriber`]. If any layer returns `false` from its [`enabled`] method, or +/// The filtering methods on a stack of subscribers are evaluated in a top-down +/// order, starting with the outermost `Subscribe` and ending with the wrapped +/// [`Collect`]. If any subscriber returns `false` from its [`enabled`] method, or /// [`Interest::never()`] from its [`register_callsite`] method, filter /// evaluation will short-circuit and the span or event will be disabled. /// -/// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html +/// [`Collect`]: https://docs.rs/tracing-core/latest/tracing_core/collect/trait.Collect.html /// [span IDs]: https://docs.rs/tracing-core/latest/tracing_core/span/struct.Id.html /// [`Context`]: struct.Context.html /// [the current span]: struct.Context.html#method.current_span /// [`register_callsite`]: #method.register_callsite /// [`enabled`]: #method.enabled /// [`on_enter`]: #method.on_enter -/// [`Layer::register_callsite`]: #method.register_callsite -/// [`Layer::enabled`]: #method.enabled +/// [`Subscribe::register_callsite`]: #method.register_callsite +/// [`Subscribe::enabled`]: #method.enabled /// [`Interest::never()`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/struct.Interest.html#method.never -pub trait Layer +pub trait Subscribe where - S: Subscriber, + C: Collect, Self: 'static, { - /// Registers a new callsite with this layer, returning whether or not - /// the layer is interested in being notified about the callsite, similarly - /// to [`Subscriber::register_callsite`]. + /// Registers a new callsite with this subscriber, returning whether or not + /// the subscriber is interested in being notified about the callsite, similarly + /// to [`Collector::register_callsite`]. /// /// By default, this returns [`Interest::always()`] if [`self.enabled`] returns /// true, or [`Interest::never()`] if it returns false. @@ -218,10 +217,10 @@ where ///
///
     /// Note: This method (and 
-    /// Layer::enabled) determine whether a span or event is
-    /// globally enabled, not whether the individual layer will be
+    /// Subscriber::enabled) determine whether a span or event is
+    /// globally enabled, not whether the individual subscriber will be
     /// notified about that span or event. This is intended to be used
-    /// by layers that implement filtering for the entire stack. Layers which do
+    /// by subscribers that implement filtering for the entire stack. Subscribers which do
     /// not wish to be notified about certain spans or events but do not wish to
     /// globally disable them should ignore those spans or events in their
     /// on_event,
@@ -231,20 +230,20 @@ where
     /// 
/// /// See [the trait-level documentation] for more information on filtering - /// with `Layer`s. + /// with `Subscriber`s. /// - /// Layers may also implement this method to perform any behaviour that + /// Subscribers may also implement this method to perform any behaviour that /// should be run once per callsite. If the layer wishes to use /// `register_callsite` for per-callsite behaviour, but does not want to /// globally enable or disable those callsites, it should always return /// [`Interest::always()`]. /// /// [`Interest`]: https://docs.rs/tracing-core/latest/tracing_core/struct.Interest.html - /// [`Subscriber::register_callsite`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html#method.register_callsite + /// [`Collector::register_callsite`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html#method.register_callsite /// [`Interest::never()`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/struct.Interest.html#method.never /// [`Interest::always()`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/struct.Interest.html#method.always /// [`self.enabled`]: #method.enabled - /// [`Layer::enabled`]: #method.enabled + /// [`Subscriber::enabled`]: #method.enabled /// [`on_event`]: #method.on_event /// [`on_enter`]: #method.on_enter /// [`on_exit`]: #method.on_exit @@ -257,11 +256,11 @@ where } } - /// Returns `true` if this layer is interested in a span or event with the + /// Returns `true` if this subscriber is interested in a span or event with the /// given `metadata` in the current [`Context`], similarly to - /// [`Subscriber::enabled`]. + /// [`Collector::enabled`]. /// - /// By default, this always returns `true`, allowing the wrapped subscriber + /// By default, this always returns `true`, allowing the wrapped collector /// to choose to disable the span. /// ///
@@ -270,7 +269,7 @@ where ///
///
     /// Note: This method (and 
-    /// Layer::register_callsite) determine whether a span or event is
+    /// Subscriber::register_callsite) determine whether a span or event is
     /// globally enabled, not whether the individual layer will be
     /// notified about that span or event. This is intended to be used
     /// by layers that implement filtering for the entire stack. Layers which do
@@ -284,106 +283,106 @@ where
     ///
     ///
     /// See [the trait-level documentation] for more information on filtering
-    /// with `Layer`s.
+    /// with `Subscriber`s.
     ///
     /// [`Interest`]: https://docs.rs/tracing-core/latest/tracing_core/struct.Interest.html
     /// [`Context`]: ../struct.Context.html
-    /// [`Subscriber::enabled`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html#method.enabled
-    /// [`Layer::register_callsite`]: #method.register_callsite
+    /// [`Collector::enabled`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html#method.enabled
+    /// [`Subscriber::register_callsite`]: #method.register_callsite
     /// [`on_event`]: #method.on_event
     /// [`on_enter`]: #method.on_enter
     /// [`on_exit`]: #method.on_exit
     /// [the trait-level documentation]: #filtering-with-layers
-    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
+    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, C>) -> bool {
         let _ = (metadata, ctx);
         true
     }
 
     /// Notifies this layer that a new span was constructed with the given
     /// `Attributes` and `Id`.
-    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
+    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, C>) {
         let _ = (attrs, id, ctx);
     }
 
     // TODO(eliza): do we want this to be a public API? If we end up moving
-    // filtering layers to a separate trait, we may no longer want `Layer`s to
+    // filtering subscribers to a separate trait, we may no longer want `Subscriber`s to
     // be able to participate in max level hinting...
     #[doc(hidden)]
     fn max_level_hint(&self) -> Option {
         None
     }
 
-    /// Notifies this layer that a span with the given `Id` recorded the given
+    /// Notifies this subscriber that a span with the given `Id` recorded the given
     /// `values`.
     // Note: it's unclear to me why we'd need the current span in `record` (the
     // only thing the `Context` type currently provides), but passing it in anyway
     // seems like a good future-proofing measure as it may grow other methods later...
-    fn on_record(&self, _span: &span::Id, _values: &span::Record<'_>, _ctx: Context<'_, S>) {}
+    fn on_record(&self, _span: &span::Id, _values: &span::Record<'_>, _ctx: Context<'_, C>) {}
 
-    /// Notifies this layer that a span with the ID `span` recorded that it
+    /// Notifies this subscriber that a span with the ID `span` recorded that it
     /// follows from the span with the ID `follows`.
     // Note: it's unclear to me why we'd need the current span in `record` (the
     // only thing the `Context` type currently provides), but passing it in anyway
     // seems like a good future-proofing measure as it may grow other methods later...
-    fn on_follows_from(&self, _span: &span::Id, _follows: &span::Id, _ctx: Context<'_, S>) {}
+    fn on_follows_from(&self, _span: &span::Id, _follows: &span::Id, _ctx: Context<'_, C>) {}
 
-    /// Notifies this layer that an event has occurred.
-    fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, S>) {}
+    /// Notifies this subscriber that an event has occurred.
+    fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, C>) {}
 
-    /// Notifies this layer that a span with the given ID was entered.
-    fn on_enter(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
+    /// Notifies this subscriber that a span with the given ID was entered.
+    fn on_enter(&self, _id: &span::Id, _ctx: Context<'_, C>) {}
 
-    /// Notifies this layer that the span with the given ID was exited.
-    fn on_exit(&self, _id: &span::Id, _ctx: Context<'_, S>) {}
+    /// Notifies this subscriber that the span with the given ID was exited.
+    fn on_exit(&self, _id: &span::Id, _ctx: Context<'_, C>) {}
 
-    /// Notifies this layer that the span with the given ID has been closed.
-    fn on_close(&self, _id: span::Id, _ctx: Context<'_, S>) {}
+    /// Notifies this subscriber that the span with the given ID has been closed.
+    fn on_close(&self, _id: span::Id, _ctx: Context<'_, C>) {}
 
-    /// Notifies this layer that a span ID has been cloned, and that the
+    /// Notifies this subscriber that a span ID has been cloned, and that the
     /// subscriber returned a different ID.
-    fn on_id_change(&self, _old: &span::Id, _new: &span::Id, _ctx: Context<'_, S>) {}
+    fn on_id_change(&self, _old: &span::Id, _new: &span::Id, _ctx: Context<'_, C>) {}
 
-    /// Composes this layer around the given `Layer`, returning a `Layered`
-    /// struct implementing `Layer`.
+    /// Composes this subscriber around the given collector, returning a `Layered`
+    /// struct implementing `Subscribe`.
     ///
-    /// The returned `Layer` will call the methods on this `Layer` and then
-    /// those of the new `Layer`, before calling the methods on the subscriber
+    /// The returned subscriber will call the methods on this subscriber and then
+    /// those of the new subscriber, before calling the methods on the collector
     /// it wraps. For example:
     ///
     /// ```rust
-    /// # use tracing_subscriber::layer::Layer;
-    /// # use tracing_core::Subscriber;
-    /// pub struct FooLayer {
+    /// # use tracing_subscriber::subscribe::Subscribe;
+    /// # use tracing_core::Collect;
+    /// pub struct FooSubscriber {
     ///     // ...
     /// }
     ///
-    /// pub struct BarLayer {
+    /// pub struct BarSubscriber {
     ///     // ...
     /// }
     ///
-    /// pub struct MySubscriber {
+    /// pub struct MyCollector {
     ///     // ...
     /// }
     ///
-    /// impl Layer for FooLayer {
+    /// impl Subscribe for FooSubscriber {
     ///     // ...
     /// }
     ///
-    /// impl Layer for BarLayer {
+    /// impl Subscribe for BarSubscriber {
     ///     // ...
     /// }
     ///
-    /// # impl FooLayer {
+    /// # impl FooSubscriber {
     /// # fn new() -> Self { Self {} }
     /// # }
-    /// # impl BarLayer {
+    /// # impl BarSubscriber {
     /// # fn new() -> Self { Self { }}
     /// # }
-    /// # impl MySubscriber {
+    /// # impl MyCollector {
     /// # fn new() -> Self { Self { }}
     /// # }
     /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
-    /// # impl tracing_core::Subscriber for MySubscriber {
+    /// # impl tracing_core::Collect for MyCollector {
     /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
     /// #   fn record(&self, _: &Id, _: &Record) {}
     /// #   fn event(&self, _: &Event) {}
@@ -392,32 +391,32 @@ where
     /// #   fn enter(&self, _: &Id) {}
     /// #   fn exit(&self, _: &Id) {}
     /// # }
-    /// let subscriber = FooLayer::new()
-    ///     .and_then(BarLayer::new())
-    ///     .with_subscriber(MySubscriber::new());
+    /// let collector = FooSubscriber::new()
+    ///     .and_then(BarSubscriber::new())
+    ///     .with_collector(MyCollector::new());
     /// ```
     ///
-    /// Multiple layers may be composed in this manner:
+    /// Multiple subscribers may be composed in this manner:
     ///
     /// ```rust
-    /// # use tracing_subscriber::layer::Layer;
-    /// # use tracing_core::Subscriber;
-    /// # pub struct FooLayer {}
-    /// # pub struct BarLayer {}
-    /// # pub struct MySubscriber {}
-    /// # impl Layer for FooLayer {}
-    /// # impl Layer for BarLayer {}
-    /// # impl FooLayer {
+    /// # use tracing_subscriber::subscribe::Subscribe;
+    /// # use tracing_core::Collect;
+    /// # pub struct FooSubscriber {}
+    /// # pub struct BarSubscriber {}
+    /// # pub struct MyCollector {}
+    /// # impl Subscribe for FooSubscriber {}
+    /// # impl Subscribe for BarSubscriber {}
+    /// # impl FooSubscriber {
     /// # fn new() -> Self { Self {} }
     /// # }
-    /// # impl BarLayer {
+    /// # impl BarSubscriber {
     /// # fn new() -> Self { Self { }}
     /// # }
-    /// # impl MySubscriber {
+    /// # impl MyCollector {
     /// # fn new() -> Self { Self { }}
     /// # }
     /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
-    /// # impl tracing_core::Subscriber for MySubscriber {
+    /// # impl tracing_core::Collect for MyCollector {
     /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
     /// #   fn record(&self, _: &Id, _: &Record) {}
     /// #   fn event(&self, _: &Event) {}
@@ -426,62 +425,62 @@ where
     /// #   fn enter(&self, _: &Id) {}
     /// #   fn exit(&self, _: &Id) {}
     /// # }
-    /// pub struct BazLayer {
+    /// pub struct BazSubscriber {
     ///     // ...
     /// }
     ///
-    /// impl Layer for BazLayer {
+    /// impl Subscribe for BazSubscriber {
     ///     // ...
     /// }
-    /// # impl BazLayer { fn new() -> Self { BazLayer {} } }
+    /// # impl BazSubscriber { fn new() -> Self { BazSubscriber {} } }
     ///
-    /// let subscriber = FooLayer::new()
-    ///     .and_then(BarLayer::new())
-    ///     .and_then(BazLayer::new())
-    ///     .with_subscriber(MySubscriber::new());
+    /// let collector = FooSubscriber::new()
+    ///     .and_then(BarSubscriber::new())
+    ///     .and_then(BazSubscriber::new())
+    ///     .with_collector(MyCollector::new());
     /// ```
-    fn and_then(self, layer: L) -> Layered
+    fn and_then(self, subscriber: S) -> Layered
     where
-        L: Layer,
+        S: Subscribe,
         Self: Sized,
     {
         Layered {
-            layer,
+            subscriber,
             inner: self,
             _s: PhantomData,
         }
     }
 
-    /// Composes this `Layer` with the given [`Subscriber`], returning a
-    /// `Layered` struct that implements [`Subscriber`].
+    /// Composes this subscriber with the given collecto, returning a
+    /// `Layered` struct that implements [`Collect`].
     ///
-    /// The returned `Layered` subscriber will call the methods on this `Layer`
-    /// and then those of the wrapped subscriber.
+    /// The returned `Layered` subscriber will call the methods on this subscriber
+    /// and then those of the wrapped collector.
     ///
     /// For example:
     /// ```rust
-    /// # use tracing_subscriber::layer::Layer;
-    /// # use tracing_core::Subscriber;
-    /// pub struct FooLayer {
+    /// # use tracing_subscriber::subscribe::Subscribe;
+    /// # use tracing_core::Collect;
+    /// pub struct FooSubscriber {
     ///     // ...
     /// }
     ///
-    /// pub struct MySubscriber {
+    /// pub struct MyCollector {
     ///     // ...
     /// }
     ///
-    /// impl Layer for FooLayer {
+    /// impl Subscribe for FooSubscriber {
     ///     // ...
     /// }
     ///
-    /// # impl FooLayer {
+    /// # impl FooSubscriber {
     /// # fn new() -> Self { Self {} }
     /// # }
-    /// # impl MySubscriber {
+    /// # impl MyCollector {
     /// # fn new() -> Self { Self { }}
     /// # }
     /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata};
-    /// # impl tracing_core::Subscriber for MySubscriber {
+    /// # impl tracing_core::Collect for MyCollector {
     /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
     /// #   fn record(&self, _: &Id, _: &Record) {}
     /// #   fn event(&self, _: &tracing_core::Event) {}
@@ -490,17 +489,17 @@ where
     /// #   fn enter(&self, _: &Id) {}
     /// #   fn exit(&self, _: &Id) {}
     /// # }
-    /// let subscriber = FooLayer::new()
-    ///     .with_subscriber(MySubscriber::new());
+    /// let collector = FooSubscriber::new()
+    ///     .with_collector(MyCollector::new());
     ///```
     ///
-    /// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html
-    fn with_subscriber(self, inner: S) -> Layered
+    /// [`Collect`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Collect.html
+    fn with_collector(self, inner: C) -> Layered
     where
         Self: Sized,
     {
         Layered {
-            layer: self,
+            subscriber: self,
             inner,
             _s: PhantomData,
         }
@@ -516,41 +515,41 @@ where
     }
 }
 
-/// Extension trait adding a `with(Layer)` combinator to `Subscriber`s.
-pub trait SubscriberExt: Subscriber + crate::sealed::Sealed {
+/// Extension trait adding a `with(Subscriber)` combinator to `Collector`s.
+pub trait CollectorExt: Collect + crate::sealed::Sealed {
     /// Wraps `self` with the provided `layer`.
-    fn with(self, layer: L) -> Layered
+    fn with(self, subscriber: S) -> Layered
     where
-        L: Layer,
+        S: Subscribe,
         Self: Sized,
     {
-        layer.with_subscriber(self)
+        subscriber.with_collector(self)
     }
 }
 
-/// Represents information about the current context provided to [`Layer`]s by the
-/// wrapped [`Subscriber`].
+/// Represents information about the current context provided to [subscriber]s by the
+/// wrapped [collector].
 ///
-/// To access [stored data] keyed by a span ID, implementors of the `Layer`
-/// trait should ensure that the `Subscriber` type parameter is *also* bound by the
+/// To access [stored data] keyed by a span ID, implementors of the `Subscribe`
+/// trait should ensure that the `Collect` type parameter is *also* bound by the
 /// [`LookupSpan`]:
 ///
 /// ```rust
-/// use tracing::Subscriber;
-/// use tracing_subscriber::{Layer, registry::LookupSpan};
+/// use tracing::Collect;
+/// use tracing_subscriber::{Subscribe, registry::LookupSpan};
 ///
-/// pub struct MyLayer;
+/// pub struct MyCollector;
 ///
-/// impl Layer for MyLayer
+/// impl Subscribe for MyCollector
 /// where
-///     S: Subscriber + for<'a> LookupSpan<'a>,
+///     C: Collect + for<'a> LookupSpan<'a>,
 /// {
 ///     // ...
 /// }
 /// ```
 ///
-/// [`Layer`]: ../layer/trait.Layer.html
-/// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html
+/// [subscriber]: ../subscriber/trait.Subscribe.html
+/// [collector]: https://docs.rs/tracing-core/latest/tracing_core/trait.Collect.html
 /// [stored data]: ../registry/struct.SpanRef.html
 /// [`LookupSpan`]: "../registry/trait.LookupSpan.html
 #[derive(Debug)]
@@ -558,19 +557,19 @@ pub struct Context<'a, S> {
     subscriber: Option<&'a S>,
 }
 
-/// A [`Subscriber`] composed of a `Subscriber` wrapped by one or more
-/// [`Layer`]s.
+/// A [collector] composed of a collector wrapped by one or more
+/// [subscriber]s.
 ///
-/// [`Layer`]: ../layer/trait.Layer.html
-/// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html
+/// [subscriber]: ../subscribe/trait.Subscribe.html
+/// [collector]: https://docs.rs/tracing-core/latest/tracing_core/trait.Collect.html
 #[derive(Clone, Debug)]
-pub struct Layered {
-    layer: L,
+pub struct Layered {
+    subscriber: S,
     inner: I,
-    _s: PhantomData,
+    _s: PhantomData,
 }
 
-/// A layer that does nothing.
+/// A Subscriber that does nothing.
 #[derive(Clone, Debug, Default)]
 pub struct Identity {
     _p: (),
@@ -592,16 +591,16 @@ pub struct Scope<'a, L: LookupSpan<'a>>(
 
 // === impl Layered ===
 
-impl Subscriber for Layered
+impl Collect for Layered
 where
-    L: Layer,
-    S: Subscriber,
+    S: Subscribe,
+    C: Collect,
 {
     fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
-        let outer = self.layer.register_callsite(metadata);
+        let outer = self.subscriber.register_callsite(metadata);
         if outer.is_never() {
-            // if the outer layer has disabled the callsite, return now so that
-            // the subscriber doesn't get its hopes up.
+            // if the outer subscriber has disabled the callsite, return now so that
+            // the collector doesn't get its hopes up.
             return outer;
         }
 
@@ -611,60 +610,63 @@ where
             // filters are reevaluated.
             outer
         } else {
-            // otherwise, allow the inner subscriber to weigh in.
+            // otherwise, allow the inner subscriber or collector to weigh in.
             inner
         }
     }
 
     fn enabled(&self, metadata: &Metadata<'_>) -> bool {
-        if self.layer.enabled(metadata, self.ctx()) {
-            // if the outer layer enables the callsite metadata, ask the subscriber.
+        if self.subscriber.enabled(metadata, self.ctx()) {
+            // if the outer subscriber enables the callsite metadata, ask the collector.
             self.inner.enabled(metadata)
         } else {
-            // otherwise, the callsite is disabled by the layer
+            // otherwise, the callsite is disabled by the subscriber
             false
         }
     }
 
     fn max_level_hint(&self) -> Option {
-        std::cmp::max(self.layer.max_level_hint(), self.inner.max_level_hint())
+        std::cmp::max(
+            self.subscriber.max_level_hint(),
+            self.inner.max_level_hint(),
+        )
     }
 
     fn new_span(&self, span: &span::Attributes<'_>) -> span::Id {
         let id = self.inner.new_span(span);
-        self.layer.new_span(span, &id, self.ctx());
+        self.subscriber.new_span(span, &id, self.ctx());
         id
     }
 
     fn record(&self, span: &span::Id, values: &span::Record<'_>) {
         self.inner.record(span, values);
-        self.layer.on_record(span, values, self.ctx());
+        self.subscriber.on_record(span, values, self.ctx());
     }
 
     fn record_follows_from(&self, span: &span::Id, follows: &span::Id) {
         self.inner.record_follows_from(span, follows);
-        self.layer.on_follows_from(span, follows, self.ctx());
+        self.subscriber.on_follows_from(span, follows, self.ctx());
     }
 
     fn event(&self, event: &Event<'_>) {
         self.inner.event(event);
-        self.layer.on_event(event, self.ctx());
+        self.subscriber.on_event(event, self.ctx());
     }
 
     fn enter(&self, span: &span::Id) {
         self.inner.enter(span);
-        self.layer.on_enter(span, self.ctx());
+        self.subscriber.on_enter(span, self.ctx());
     }
 
     fn exit(&self, span: &span::Id) {
         self.inner.exit(span);
-        self.layer.on_exit(span, self.ctx());
+        self.subscriber.on_exit(span, self.ctx());
     }
 
     fn clone_span(&self, old: &span::Id) -> span::Id {
         let new = self.inner.clone_span(old);
         if &new != old {
-            self.layer.on_id_change(old, &new, self.ctx())
+            self.subscriber.on_id_change(old, &new, self.ctx())
         };
         new
     }
@@ -676,7 +678,7 @@ where
 
     fn try_close(&self, id: span::Id) -> bool {
         #[cfg(feature = "registry")]
-        let subscriber = &self.inner as &dyn Subscriber;
+        let subscriber = &self.inner as &dyn Collect;
         #[cfg(feature = "registry")]
         let mut guard = subscriber
             .downcast_ref::()
@@ -691,7 +693,7 @@ where
                 };
             }
 
-            self.layer.on_close(id, self.ctx());
+            self.subscriber.on_close(id, self.ctx());
             true
         } else {
             false
@@ -708,23 +710,23 @@ where
         if id == TypeId::of::() {
             return Some(self as *const _ as *const ());
         }
-        self.layer
+        self.subscriber
             .downcast_raw(id)
             .or_else(|| self.inner.downcast_raw(id))
     }
 }
 
-impl Layer for Layered
+impl Subscribe for Layered
 where
-    A: Layer,
-    B: Layer,
-    S: Subscriber,
+    A: Subscribe,
+    B: Subscribe,
+    C: Collect,
 {
     fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
-        let outer = self.layer.register_callsite(metadata);
+        let outer = self.subscriber.register_callsite(metadata);
         if outer.is_never() {
-            // if the outer layer has disabled the callsite, return now so that
-            // inner layers don't get their hopes up.
+            // if the outer subscriber has disabled the callsite, return now so that
+            // inner subscribers don't get their hopes up.
             return outer;
         }
 
@@ -734,67 +736,67 @@ where
             // filters are reevaluated.
             outer
         } else {
-            // otherwise, allow the inner layer to weigh in.
+            // otherwise, allow the inner subscriber or collector to weigh in.
             inner
         }
     }
 
-    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
-        if self.layer.enabled(metadata, ctx.clone()) {
-            // if the outer layer enables the callsite metadata, ask the inner layer.
-            self.inner.enabled(metadata, ctx)
+    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, C>) -> bool {
+        if self.subscriber.enabled(metadata, ctx.clone()) {
+            // if the outer subscriber enables the callsite metadata, ask the inner subscriber.
+            self.subscriber.enabled(metadata, ctx)
         } else {
-            // otherwise, the callsite is disabled by this layer
+            // otherwise, the callsite is disabled by this subscriber
             false
         }
     }
 
     #[inline]
-    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
+    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, C>) {
         self.inner.new_span(attrs, id, ctx.clone());
-        self.layer.new_span(attrs, id, ctx);
+        self.subscriber.new_span(attrs, id, ctx);
     }
 
     #[inline]
-    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
+    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, C>) {
         self.inner.on_record(span, values, ctx.clone());
-        self.layer.on_record(span, values, ctx);
+        self.subscriber.on_record(span, values, ctx);
     }
 
     #[inline]
-    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
+    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, C>) {
         self.inner.on_follows_from(span, follows, ctx.clone());
-        self.layer.on_follows_from(span, follows, ctx);
+        self.subscriber.on_follows_from(span, follows, ctx);
     }
 
     #[inline]
-    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
+    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, C>) {
         self.inner.on_event(event, ctx.clone());
-        self.layer.on_event(event, ctx);
+        self.subscriber.on_event(event, ctx);
     }
 
     #[inline]
-    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
+    fn on_enter(&self, id: &span::Id, ctx: Context<'_, C>) {
         self.inner.on_enter(id, ctx.clone());
-        self.layer.on_enter(id, ctx);
+        self.subscriber.on_enter(id, ctx);
     }
 
     #[inline]
-    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
+    fn on_exit(&self, id: &span::Id, ctx: Context<'_, C>) {
         self.inner.on_exit(id, ctx.clone());
-        self.layer.on_exit(id, ctx);
+        self.subscriber.on_exit(id, ctx);
     }
 
     #[inline]
-    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
+    fn on_close(&self, id: span::Id, ctx: Context<'_, C>) {
         self.inner.on_close(id.clone(), ctx.clone());
-        self.layer.on_close(id, ctx);
+        self.subscriber.on_close(id, ctx);
     }
 
     #[inline]
-    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
+    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, C>) {
         self.inner.on_id_change(old, new, ctx.clone());
-        self.layer.on_id_change(old, new, ctx);
+        self.subscriber.on_id_change(old, new, ctx);
     }
 
     #[doc(hidden)]
@@ -802,24 +804,17 @@ where
         if id == TypeId::of::() {
             return Some(self as *const _ as *const ());
         }
-        self.layer
+        self.subscriber
             .downcast_raw(id)
             .or_else(|| self.inner.downcast_raw(id))
     }
 }
 
-impl Layer for Option
+impl Subscribe for Option
 where
-    L: Layer,
-    S: Subscriber,
+    S: Subscribe,
+    C: Collect,
 {
-    #[inline]
-    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
-        if let Some(ref inner) = self {
-            inner.new_span(attrs, id, ctx)
-        }
-    }
-
     #[inline]
     fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
         match self {
@@ -829,13 +824,20 @@ where
     }
 
     #[inline]
-    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
+    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, C>) -> bool {
         match self {
             Some(ref inner) => inner.enabled(metadata, ctx),
             None => true,
         }
     }
 
+    #[inline]
+    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, C>) {
+        if let Some(ref inner) = self {
+            inner.new_span(attrs, id, ctx)
+        }
+    }
+
     #[inline]
     fn max_level_hint(&self) -> Option {
         match self {
@@ -845,49 +847,49 @@ where
     }
 
     #[inline]
-    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
+    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, C>) {
         if let Some(ref inner) = self {
             inner.on_record(span, values, ctx);
         }
     }
 
     #[inline]
-    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
+    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, C>) {
         if let Some(ref inner) = self {
             inner.on_follows_from(span, follows, ctx);
         }
     }
 
     #[inline]
-    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
+    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, C>) {
         if let Some(ref inner) = self {
             inner.on_event(event, ctx);
         }
     }
 
     #[inline]
-    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
+    fn on_enter(&self, id: &span::Id, ctx: Context<'_, C>) {
         if let Some(ref inner) = self {
             inner.on_enter(id, ctx);
         }
     }
 
     #[inline]
-    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
+    fn on_exit(&self, id: &span::Id, ctx: Context<'_, C>) {
         if let Some(ref inner) = self {
             inner.on_exit(id, ctx);
         }
     }
 
     #[inline]
-    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
+    fn on_close(&self, id: span::Id, ctx: Context<'_, C>) {
         if let Some(ref inner) = self {
             inner.on_close(id, ctx);
         }
     }
 
     #[inline]
-    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
+    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, C>) {
         if let Some(ref inner) = self {
             inner.on_id_change(old, new, ctx)
         }
@@ -906,22 +908,22 @@ where
 
 #[cfg(feature = "registry")]
 #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
-impl<'a, L, S> LookupSpan<'a> for Layered
+impl<'a, S, C> LookupSpan<'a> for Layered
 where
-    S: Subscriber + LookupSpan<'a>,
+    C: Collect + LookupSpan<'a>,
 {
-    type Data = S::Data;
+    type Data = C::Data;
 
     fn span_data(&'a self, id: &span::Id) -> Option {
         self.inner.span_data(id)
     }
 }
 
-impl Layered
+impl Layered
 where
-    S: Subscriber,
+    C: Collect,
 {
-    fn ctx(&self) -> Context<'_, S> {
+    fn ctx(&self) -> Context<'_, C> {
         Context {
             subscriber: Some(&self.inner),
         }
@@ -935,22 +937,22 @@ where
 //     }
 // }
 
-// === impl SubscriberExt ===
+// === impl CollectorExt ===
 
-impl crate::sealed::Sealed for S {}
-impl SubscriberExt for S {}
+impl crate::sealed::Sealed for C {}
+impl CollectorExt for C {}
 
 // === impl Context ===
 
-impl<'a, S> Context<'a, S>
+impl<'a, C> Context<'a, C>
 where
-    S: Subscriber,
+    C: Collect,
 {
     /// Returns the wrapped subscriber's view of the current span.
     #[inline]
     pub fn current_span(&self) -> span::Current {
         self.subscriber
-            .map(Subscriber::current_span)
+            .map(Collect::current_span)
             // TODO: this would be more correct as "unknown", so perhaps
             // `tracing-core` should make `Current::unknown()` public?
             .unwrap_or_else(span::Current::none)
@@ -962,30 +964,30 @@ where
         self.subscriber
             .map(|subscriber| subscriber.enabled(metadata))
             // If this context is `None`, we are registering a callsite, so
-            // return `true` so that the layer does not incorrectly assume that
+            // return `true` so that the subscriber does not incorrectly assume that
             // the inner subscriber has disabled this metadata.
             // TODO(eliza): would it be more correct for this to return an `Option`?
             .unwrap_or(true)
     }
 
-    /// Records the provided `event` with the wrapped subscriber.
+    /// Records the provided `event` with the wrapped collector.
     ///
     /// # Notes
     ///
-    /// - The subscriber is free to expect that the event's callsite has been
+    /// - The collector is free to expect that the event's callsite has been
     ///   [registered][register], and may panic or fail to observe the event if this is
     ///   not the case. The `tracing` crate's macros ensure that all events are
     ///   registered, but if the event is constructed through other means, the
     ///   user is responsible for ensuring that [`register_callsite`][register]
     ///   has been called prior to calling this method.
-    /// - This does _not_ call [`enabled`] on the inner subscriber. If the
-    ///   caller wishes to apply the wrapped subscriber's filter before choosing
+    /// - This does _not_ call [`enabled`] on the inner collector. If the
+    ///   caller wishes to apply the wrapped collector's filter before choosing
     ///   whether to record the event, it may first call [`Context::enabled`] to
-    ///   check whether the event would be enabled. This allows `Layer`s to
+    ///   check whether the event would be enabled. This allows `Collectors`s to
     ///   elide constructing the event if it would not be recorded.
     ///
-    /// [register]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html#method.register_callsite
-    /// [`enabled`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html#method.enabled
+    /// [register]: https://docs.rs/tracing-core/latest/tracing_core/collect/trait.Collect.html#method.register_callsite
+    /// [`enabled`]: https://docs.rs/tracing-core/latest/tracing_core/collect/trait.Collect.html#method.enabled
     /// [`Context::enabled`]: #method.enabled
     #[inline]
     pub fn event(&self, event: &Event<'_>) {
@@ -1003,7 +1005,7 @@ where
     #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
     pub fn metadata(&self, id: &span::Id) -> Option<&'static Metadata<'static>>
     where
-        S: for<'lookup> LookupSpan<'lookup>,
+        C: for<'lookup> LookupSpan<'lookup>,
     {
         let span = self.subscriber.as_ref()?.span(id)?;
         Some(span.metadata())
@@ -1019,7 +1021,7 @@ where
     /// 
///
///
-    /// Note: This requires the wrapped subscriber to implement the
+    /// Note: This requires the wrapped collector to implement the
     /// LookupSpan trait.
     /// See the documentation on Context's
     /// declaration for details.
@@ -1029,9 +1031,9 @@ where
     #[inline]
     #[cfg(feature = "registry")]
     #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
-    pub fn span(&self, id: &span::Id) -> Option>
+    pub fn span(&self, id: &span::Id) -> Option>
     where
-        S: for<'lookup> LookupSpan<'lookup>,
+        C: for<'lookup> LookupSpan<'lookup>,
     {
         self.subscriber.as_ref()?.span(id)
     }
@@ -1053,12 +1055,12 @@ where
     #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
     pub fn exists(&self, id: &span::Id) -> bool
     where
-        S: for<'lookup> LookupSpan<'lookup>,
+        C: for<'lookup> LookupSpan<'lookup>,
     {
         self.subscriber.as_ref().and_then(|s| s.span(id)).is_some()
     }
 
-    /// Returns [stored data] for the span that the wrapped subscriber considers
+    /// Returns [stored data] for the span that the wrapped collector considers
     /// to be the current.
     ///
     /// If this returns `None`, then we are not currently within a span.
@@ -1068,7 +1070,7 @@ where
     /// 
///
///
-    /// Note: This requires the wrapped subscriber to implement the
+    /// Note: This requires the wrapped collector to implement the
     /// LookupSpan trait.
     /// See the documentation on Context's
     /// declaration for details.
@@ -1078,9 +1080,9 @@ where
     #[inline]
     #[cfg(feature = "registry")]
     #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
-    pub fn lookup_current(&self) -> Option>
+    pub fn lookup_current(&self) -> Option>
     where
-        S: for<'lookup> LookupSpan<'lookup>,
+        C: for<'lookup> LookupSpan<'lookup>,
     {
         let subscriber = self.subscriber.as_ref()?;
         let current = subscriber.current_span();
@@ -1114,9 +1116,9 @@ where
     /// [stored data]: ../registry/struct.SpanRef.html
     #[cfg(feature = "registry")]
     #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
-    pub fn scope(&self) -> Scope<'_, S>
+    pub fn scope(&self) -> Scope<'_, C>
     where
-        S: for<'lookup> registry::LookupSpan<'lookup>,
+        C: for<'lookup> registry::LookupSpan<'lookup>,
     {
         let scope = self.lookup_current().map(|span| {
             let parents = span.from_root();
@@ -1126,13 +1128,13 @@ where
     }
 }
 
-impl<'a, S> Context<'a, S> {
+impl<'a, C> Context<'a, C> {
     pub(crate) fn none() -> Self {
         Self { subscriber: None }
     }
 }
 
-impl<'a, S> Clone for Context<'a, S> {
+impl<'a, C> Clone for Context<'a, C> {
     #[inline]
     fn clone(&self) -> Self {
         let subscriber = if let Some(ref subscriber) = self.subscriber {
@@ -1146,10 +1148,10 @@ impl<'a, S> Clone for Context<'a, S> {
 
 // === impl Identity ===
 //
-impl Layer for Identity {}
+impl Subscribe for Identity {}
 
 impl Identity {
-    /// Returns a new `Identity` layer.
+    /// Returns a new `Identity` subscriber.
     pub fn new() -> Self {
         Self { _p: () }
     }
@@ -1180,9 +1182,9 @@ impl<'a, L: LookupSpan<'a>> std::fmt::Debug for Scope<'a, L> {
 pub(crate) mod tests {
     use super::*;
 
-    pub(crate) struct NopSubscriber;
+    pub(crate) struct NopCollector;
 
-    impl Subscriber for NopSubscriber {
+    impl Collect for NopCollector {
         fn register_callsite(&self, _: &'static Metadata<'static>) -> Interest {
             Interest::never()
         }
@@ -1202,27 +1204,27 @@ pub(crate) mod tests {
         fn exit(&self, _: &span::Id) {}
     }
 
-    struct NopLayer;
-    impl Layer for NopLayer {}
+    struct NopSubscriber;
+    impl Subscribe for NopSubscriber {}
 
     #[allow(dead_code)]
-    struct NopLayer2;
-    impl Layer for NopLayer2 {}
+    struct NopSubscriber2;
+    impl Subscribe for NopSubscriber2 {}
 
-    /// A layer that holds a string.
+    /// A subscriber that holds a string.
     ///
     /// Used to test that pointers returned by downcasting are actually valid.
-    struct StringLayer(String);
-    impl Layer for StringLayer {}
-    struct StringLayer2(String);
-    impl Layer for StringLayer2 {}
+    struct StringSubscriber(String);
+    impl Subscribe for StringSubscriber {}
+    struct StringSubscriber2(String);
+    impl Subscribe for StringSubscriber2 {}
 
-    struct StringLayer3(String);
-    impl Layer for StringLayer3 {}
+    struct StringSubscriber3(String);
+    impl Subscribe for StringSubscriber3 {}
 
-    pub(crate) struct StringSubscriber(String);
+    pub(crate) struct StringCollector(String);
 
-    impl Subscriber for StringSubscriber {
+    impl Collect for StringCollector {
         fn register_callsite(&self, _: &'static Metadata<'static>) -> Interest {
             Interest::never()
         }
@@ -1242,51 +1244,56 @@ pub(crate) mod tests {
         fn exit(&self, _: &span::Id) {}
     }
 
-    fn assert_subscriber(_s: impl Subscriber) {}
+    fn assert_collector(_s: impl Collect) {}
 
     #[test]
-    fn layer_is_subscriber() {
-        let s = NopLayer.with_subscriber(NopSubscriber);
-        assert_subscriber(s)
+    fn subscriber_is_collector() {
+        let s = NopSubscriber.with_collector(NopCollector);
+        assert_collector(s)
     }
 
     #[test]
-    fn two_layers_are_subscriber() {
-        let s = NopLayer.and_then(NopLayer).with_subscriber(NopSubscriber);
-        assert_subscriber(s)
+    fn two_subscribers_are_collector() {
+        let s = NopSubscriber
+            .and_then(NopSubscriber)
+            .with_collector(NopCollector);
+        assert_collector(s)
     }
 
     #[test]
-    fn three_layers_are_subscriber() {
-        let s = NopLayer
-            .and_then(NopLayer)
-            .and_then(NopLayer)
-            .with_subscriber(NopSubscriber);
-        assert_subscriber(s)
+    fn three_subscribers_are_collector() {
+        let s = NopSubscriber
+            .and_then(NopSubscriber)
+            .and_then(NopSubscriber)
+            .with_collector(NopCollector);
+        assert_collector(s)
     }
 
     #[test]
-    fn downcasts_to_subscriber() {
-        let s = NopLayer
-            .and_then(NopLayer)
-            .and_then(NopLayer)
-            .with_subscriber(StringSubscriber("subscriber".into()));
-        let subscriber =
-            Subscriber::downcast_ref::(&s).expect("subscriber should downcast");
-        assert_eq!(&subscriber.0, "subscriber");
+    fn downcasts_to_collector() {
+        let s = NopSubscriber
+            .and_then(NopSubscriber)
+            .and_then(NopSubscriber)
+            .with_collector(StringCollector("collector".into()));
+        let collector =
+            Collect::downcast_ref::(&s).expect("collector should downcast");
+        assert_eq!(&collector.0, "collector");
     }
 
     #[test]
-    fn downcasts_to_layer() {
-        let s = StringLayer("layer_1".into())
-            .and_then(StringLayer2("layer_2".into()))
-            .and_then(StringLayer3("layer_3".into()))
-            .with_subscriber(NopSubscriber);
-        let layer = Subscriber::downcast_ref::(&s).expect("layer 1 should downcast");
-        assert_eq!(&layer.0, "layer_1");
-        let layer = Subscriber::downcast_ref::(&s).expect("layer 2 should downcast");
-        assert_eq!(&layer.0, "layer_2");
-        let layer = Subscriber::downcast_ref::(&s).expect("layer 3 should downcast");
-        assert_eq!(&layer.0, "layer_3");
+    fn downcasts_to_subscriber() {
+        let s = StringSubscriber("subscriber_1".into())
+            .and_then(StringSubscriber2("subscriber_2".into()))
+            .and_then(StringSubscriber3("subscriber_3".into()))
+            .with_collector(NopCollector);
+        let layer =
+            Collect::downcast_ref::(&s).expect("subscriber 2 should downcast");
+        assert_eq!(&layer.0, "subscriber_1");
+        let layer =
+            Collect::downcast_ref::(&s).expect("subscriber 2 should downcast");
+        assert_eq!(&layer.0, "subscriber_2");
+        let layer =
+            Collect::downcast_ref::(&s).expect("subscriber 3 should downcast");
+        assert_eq!(&layer.0, "subscriber_3");
     }
 }
diff --git a/tracing-subscriber/src/sync.rs b/tracing-subscriber/src/sync.rs
index e89a8087e8..f09731f50b 100644
--- a/tracing-subscriber/src/sync.rs
+++ b/tracing-subscriber/src/sync.rs
@@ -33,6 +33,11 @@ mod parking_lot_impl {
             }
         }
 
+        #[inline]
+        pub(crate) fn get_mut(&mut self) -> LockResult<&mut T> {
+            Ok(self.inner.get_mut())
+        }
+
         #[inline]
         pub(crate) fn read<'a>(&'a self) -> LockResult> {
             Ok(self.inner.read())
diff --git a/tracing-subscriber/src/util.rs b/tracing-subscriber/src/util.rs
index 48d62c50a5..49a3c0357f 100644
--- a/tracing-subscriber/src/util.rs
+++ b/tracing-subscriber/src/util.rs
@@ -1,17 +1,17 @@
 //! Extension traits and other utilities to make working with subscribers more
 //! ergonomic.
 use std::{error::Error, fmt};
-use tracing_core::dispatcher::{self, Dispatch};
+use tracing_core::dispatch::{self, Dispatch};
 
 /// Extension trait adding utility methods for subscriber initialization.
 ///
 /// This trait provides extension methods to make configuring and setting a
 /// [default subscriber] more ergonomic. It is automatically implemented for all
 /// types that can be converted into a [trace dispatcher]. Since `Dispatch`
-/// implements `From` for all `T: Subscriber`, all `Subscriber`
+/// implements `From` for all `T: Collector`, all `Collector`
 /// implementations will implement this extension trait as well. Types which
-/// can be converted into `Subscriber`s, such as builders that construct a
-/// `Subscriber`, may implement `Into`, and will also receive an
+/// can be converted into `Collector`s, such as builders that construct a
+/// `Collector`, may implement `Into`, and will also receive an
 /// implementation of this trait.
 ///
 /// [default subscriber]: https://docs.rs/tracing/0.1.21/tracing/dispatcher/index.html#setting-the-default-subscriber
@@ -29,11 +29,11 @@ where
     ///
     /// [default subscriber]: https://docs.rs/tracing/0.1.21/tracing/dispatcher/index.html#setting-the-default-subscriber
     /// [`log`]: https://crates.io/log
-    fn set_default(self) -> dispatcher::DefaultGuard {
+    fn set_default(self) -> dispatch::DefaultGuard {
         #[cfg(feature = "tracing-log")]
         let _ = tracing_log::LogTracer::init();
 
-        dispatcher::set_default(&self.into())
+        dispatch::set_default(&self.into())
     }
 
     /// Attempts to set `self` as the [global default subscriber] in the current
@@ -53,7 +53,7 @@ where
         #[cfg(feature = "tracing-log")]
         tracing_log::LogTracer::init().map_err(TryInitError::new)?;
 
-        dispatcher::set_global_default(self.into()).map_err(TryInitError::new)?;
+        dispatch::set_global_default(self.into()).map_err(TryInitError::new)?;
 
         Ok(())
     }
diff --git a/tracing-subscriber/tests/duplicate_spans.rs b/tracing-subscriber/tests/duplicate_spans.rs
index 34174d1657..92aee0eb61 100644
--- a/tracing-subscriber/tests/duplicate_spans.rs
+++ b/tracing-subscriber/tests/duplicate_spans.rs
@@ -1,14 +1,14 @@
 mod support;
-use tracing::{self, subscriber::with_default, Span};
-use tracing_subscriber::{filter::EnvFilter, FmtSubscriber};
+use tracing::{self, collect::with_default, Span};
+use tracing_subscriber::{filter::EnvFilter, fmt::Collector};
 
 #[test]
 fn duplicate_spans() {
-    let subscriber = FmtSubscriber::builder()
+    let collector = Collector::builder()
         .with_env_filter(EnvFilter::new("[root]=debug"))
         .finish();
 
-    with_default(subscriber, || {
+    with_default(collector, || {
         let root = tracing::debug_span!("root");
         root.in_scope(|| {
             // root:
diff --git a/tracing-subscriber/tests/field_filter.rs b/tracing-subscriber/tests/field_filter.rs
index 7c39441739..ef0e9ae7b8 100644
--- a/tracing-subscriber/tests/field_filter.rs
+++ b/tracing-subscriber/tests/field_filter.rs
@@ -1,12 +1,12 @@
 mod support;
 use self::support::*;
-use tracing::{self, subscriber::with_default, Level};
+use tracing::{self, collect::with_default, Level};
 use tracing_subscriber::{filter::EnvFilter, prelude::*};
 
 #[test]
 fn field_filter_events() {
     let filter: EnvFilter = "[{thing}]=debug".parse().expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(
             event::mock()
                 .at_level(Level::INFO)
@@ -37,7 +37,7 @@ fn field_filter_spans() {
     let filter: EnvFilter = "[{enabled=true}]=debug"
         .parse()
         .expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .enter(span::mock().named("span1"))
         .event(
             event::mock()
@@ -80,7 +80,7 @@ fn record_after_created() {
     let filter: EnvFilter = "[{enabled=true}]=debug"
         .parse()
         .expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .enter(span::mock().named("span"))
         .exit(span::mock().named("span"))
         .record(
diff --git a/tracing-subscriber/tests/filter.rs b/tracing-subscriber/tests/filter.rs
index 5b6afbb595..5d426c1231 100644
--- a/tracing-subscriber/tests/filter.rs
+++ b/tracing-subscriber/tests/filter.rs
@@ -1,6 +1,6 @@
 mod support;
 use self::support::*;
-use tracing::{self, subscriber::with_default, Level};
+use tracing::{self, collect::with_default, Level};
 use tracing_subscriber::{
     filter::{EnvFilter, LevelFilter},
     prelude::*,
@@ -9,7 +9,7 @@ use tracing_subscriber::{
 #[test]
 fn level_filter_event() {
     let filter: EnvFilter = "info".parse().expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(event::mock().at_level(Level::INFO))
         .event(event::mock().at_level(Level::WARN))
         .event(event::mock().at_level(Level::ERROR))
@@ -33,7 +33,7 @@ fn same_name_spans() {
     let filter: EnvFilter = "[foo{bar}]=trace,[foo{baz}]=trace"
         .parse()
         .expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .new_span(
             span::mock()
                 .named("foo")
@@ -60,7 +60,7 @@ fn same_name_spans() {
 #[test]
 fn level_filter_event_with_target() {
     let filter: EnvFilter = "info,stuff=debug".parse().expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(event::mock().at_level(Level::INFO))
         .event(event::mock().at_level(Level::DEBUG).with_target("stuff"))
         .event(event::mock().at_level(Level::WARN).with_target("stuff"))
@@ -89,7 +89,7 @@ fn not_order_dependent() {
     // this test reproduces tokio-rs/tracing#623
 
     let filter: EnvFilter = "stuff=debug,info".parse().expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(event::mock().at_level(Level::INFO))
         .event(event::mock().at_level(Level::DEBUG).with_target("stuff"))
         .event(event::mock().at_level(Level::WARN).with_target("stuff"))
@@ -123,7 +123,7 @@ fn add_directive_enables_event() {
     // overwrite with a more specific directive
     filter = filter.add_directive("hello=trace".parse().expect("directive should parse"));
 
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(event::mock().at_level(Level::INFO).with_target("hello"))
         .event(event::mock().at_level(Level::TRACE).with_target("hello"))
         .done()
@@ -143,7 +143,7 @@ fn span_name_filter_is_dynamic() {
     let filter: EnvFilter = "info,[cool_span]=debug"
         .parse()
         .expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(event::mock().at_level(Level::INFO))
         .enter(span::mock().named("cool_span"))
         .event(event::mock().at_level(Level::DEBUG))
diff --git a/tracing-subscriber/tests/filter_log.rs b/tracing-subscriber/tests/filter_log.rs
index 21cbda527a..a7b67348ec 100644
--- a/tracing-subscriber/tests/filter_log.rs
+++ b/tracing-subscriber/tests/filter_log.rs
@@ -1,6 +1,6 @@
 mod support;
 use self::support::*;
-use tracing::{self, subscriber::with_default, Level};
+use tracing::{self, collect::with_default, Level};
 use tracing_subscriber::{filter::EnvFilter, prelude::*};
 
 #[test]
@@ -19,7 +19,7 @@ fn log_is_enabled() {
     let filter: EnvFilter = "filter_log::my_module=info"
         .parse()
         .expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(event::mock().at_level(Level::INFO))
         .event(event::mock().at_level(Level::WARN))
         .event(event::mock().at_level(Level::ERROR))
diff --git a/tracing-subscriber/tests/registry_with_subscriber.rs b/tracing-subscriber/tests/registry_with_subscriber.rs
index e0d6544e0a..e9fee7d0a1 100644
--- a/tracing-subscriber/tests/registry_with_subscriber.rs
+++ b/tracing-subscriber/tests/registry_with_subscriber.rs
@@ -1,4 +1,4 @@
-use tracing_futures::{Instrument, WithSubscriber};
+use tracing_futures::{Instrument, WithCollector};
 use tracing_subscriber::prelude::*;
 
 #[tokio::test]
@@ -17,7 +17,7 @@ async fn future_with_subscriber() {
             .instrument(tracing::info_span!("hi"))
             .await
         }
-        .with_subscriber(tracing_subscriber::registry()),
+        .with_collector(tracing_subscriber::registry()),
     )
     .await
     .unwrap();
diff --git a/tracing-subscriber/tests/reload.rs b/tracing-subscriber/tests/reload.rs
index b43aad6ea0..5d1a9c55fe 100644
--- a/tracing-subscriber/tests/reload.rs
+++ b/tracing-subscriber/tests/reload.rs
@@ -1,14 +1,14 @@
 use std::sync::atomic::{AtomicUsize, Ordering};
 use tracing_core::{
+    collect::Interest,
     span::{Attributes, Id, Record},
-    subscriber::Interest,
-    Event, Metadata, Subscriber,
+    Collect, Event, Metadata,
 };
-use tracing_subscriber::{layer, prelude::*, reload::*};
+use tracing_subscriber::{prelude::*, reload::*, subscribe};
 
 pub struct NopSubscriber;
 
-impl Subscriber for NopSubscriber {
+impl Collect for NopSubscriber {
     fn register_callsite(&self, _: &'static Metadata<'static>) -> Interest {
         Interest::never()
     }
@@ -38,13 +38,13 @@ fn reload_handle() {
         Two,
     }
 
-    impl tracing_subscriber::Layer for Filter {
+    impl tracing_subscriber::Subscribe for Filter {
         fn register_callsite(&self, m: &Metadata<'_>) -> Interest {
             println!("REGISTER: {:?}", m);
             Interest::sometimes()
         }
 
-        fn enabled(&self, m: &Metadata<'_>, _: layer::Context<'_, S>) -> bool {
+        fn enabled(&self, m: &Metadata<'_>, _: subscribe::Context<'_, S>) -> bool {
             println!("ENABLED: {:?}", m);
             match self {
                 Filter::One => FILTER1_CALLS.fetch_add(1, Ordering::SeqCst),
@@ -57,11 +57,11 @@ fn reload_handle() {
         tracing::trace!("my event");
     }
 
-    let (layer, handle) = Layer::new(Filter::One);
+    let (layer, handle) = Subscriber::new(Filter::One);
 
-    let subscriber = tracing_core::dispatcher::Dispatch::new(layer.with_subscriber(NopSubscriber));
+    let subscriber = tracing_core::dispatch::Dispatch::new(layer.with_collector(NopSubscriber));
 
-    tracing_core::dispatcher::with_default(&subscriber, || {
+    tracing_core::dispatch::with_default(&subscriber, || {
         assert_eq!(FILTER1_CALLS.load(Ordering::SeqCst), 0);
         assert_eq!(FILTER2_CALLS.load(Ordering::SeqCst), 0);
 
diff --git a/tracing-subscriber/tests/same_len_filters.rs b/tracing-subscriber/tests/same_len_filters.rs
index 5b85ac7717..5219785c6f 100644
--- a/tracing-subscriber/tests/same_len_filters.rs
+++ b/tracing-subscriber/tests/same_len_filters.rs
@@ -3,13 +3,13 @@
 
 mod support;
 use self::support::*;
-use tracing::{self, subscriber::with_default, Level};
+use tracing::{self, collect::with_default, Level};
 use tracing_subscriber::{filter::EnvFilter, prelude::*};
 
 #[test]
 fn same_length_targets() {
     let filter: EnvFilter = "foo=trace,bar=trace".parse().expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(event::mock().at_level(Level::TRACE))
         .event(event::mock().at_level(Level::TRACE))
         .done()
@@ -29,7 +29,7 @@ fn same_num_fields_event() {
     let filter: EnvFilter = "[{foo}]=trace,[{bar}]=trace"
         .parse()
         .expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(
             event::mock()
                 .at_level(Level::TRACE)
@@ -56,7 +56,7 @@ fn same_num_fields_and_name_len() {
     let filter: EnvFilter = "[foo{bar=1}]=trace,[baz{boz=1}]=trace"
         .parse()
         .expect("filter should parse");
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .new_span(
             span::mock()
                 .named("foo")
diff --git a/tracing-subscriber/tests/utils.rs b/tracing-subscriber/tests/utils.rs
index baef27defa..0d8e47b05e 100644
--- a/tracing-subscriber/tests/utils.rs
+++ b/tracing-subscriber/tests/utils.rs
@@ -4,7 +4,7 @@ use tracing_subscriber::prelude::*;
 
 #[test]
 fn init_ext_works() {
-    let (subscriber, finished) = subscriber::mock()
+    let (subscriber, finished) = collector::mock()
         .event(
             event::mock()
                 .at_level(tracing::Level::INFO)
@@ -30,7 +30,7 @@ fn builders_are_init_ext() {
 #[test]
 fn layered_is_init_ext() {
     tracing_subscriber::registry()
-        .with(tracing_subscriber::fmt::layer())
+        .with(tracing_subscriber::fmt::subscriber())
         .with(tracing_subscriber::EnvFilter::new("foo=info"))
         .set_default();
 }
diff --git a/tracing-tower/src/request_span.rs b/tracing-tower/src/request_span.rs
index 3c9ed61215..80216f3f70 100644
--- a/tracing-tower/src/request_span.rs
+++ b/tracing-tower/src/request_span.rs
@@ -45,7 +45,7 @@ mod layer {
         }
     }
 
-    // === impl Layer ===
+    // === impl Subscriber ===
     impl tower_layer::Layer for Layer
     where
         S: tower_service::Service,
diff --git a/tracing-tower/src/service_span.rs b/tracing-tower/src/service_span.rs
index 3f80f0967e..608e087b56 100644
--- a/tracing-tower/src/service_span.rs
+++ b/tracing-tower/src/service_span.rs
@@ -46,7 +46,7 @@ mod layer {
         }
     }
 
-    // === impl Layer ===
+    // === impl Subscriber ===
 
     impl tower_layer::Layer for Layer
     where
diff --git a/tracing/benches/global_subscriber.rs b/tracing/benches/global_subscriber.rs
index 3c8f53b0ad..0e78761ef5 100644
--- a/tracing/benches/global_subscriber.rs
+++ b/tracing/benches/global_subscriber.rs
@@ -6,10 +6,10 @@ use tracing::Level;
 
 use tracing::{span, Event, Id, Metadata};
 
-/// A subscriber that is enabled but otherwise does nothing.
-struct EnabledSubscriber;
+/// A collector that is enabled but otherwise does nothing.
+struct EnabledCollector;
 
-impl tracing::Subscriber for EnabledSubscriber {
+impl tracing::Collect for EnabledCollector {
     fn new_span(&self, span: &span::Attributes<'_>) -> Id {
         let _ = span;
         Id::from_u64(0xDEAD_FACE)
@@ -44,8 +44,8 @@ impl tracing::Subscriber for EnabledSubscriber {
 const N_SPANS: usize = 100;
 
 fn criterion_benchmark(c: &mut Criterion) {
-    let mut c = c.benchmark_group("global/subscriber");
-    let _ = tracing::subscriber::set_global_default(EnabledSubscriber);
+    let mut c = c.benchmark_group("global/collector");
+    let _ = tracing::collect::set_global_default(EnabledCollector);
     c.bench_function("span_no_fields", |b| b.iter(|| span!(Level::TRACE, "span")));
 
     c.bench_function("event", |b| {
@@ -85,18 +85,18 @@ fn criterion_benchmark(c: &mut Criterion) {
 }
 
 fn bench_dispatch(c: &mut Criterion) {
-    let _ = tracing::subscriber::set_global_default(EnabledSubscriber);
+    let _ = tracing::collect::set_global_default(EnabledCollector);
     let mut group = c.benchmark_group("global/dispatch");
     group.bench_function("get_ref", |b| {
         b.iter(|| {
-            tracing::dispatcher::get_default(|current| {
+            tracing::dispatch::get_default(|current| {
                 black_box(¤t);
             })
         })
     });
     group.bench_function("get_clone", |b| {
         b.iter(|| {
-            let current = tracing::dispatcher::get_default(|current| current.clone());
+            let current = tracing::dispatch::get_default(|current| current.clone());
             black_box(current);
         })
     });
diff --git a/tracing/benches/subscriber.rs b/tracing/benches/subscriber.rs
index 8a581d678c..e8719cf9ac 100644
--- a/tracing/benches/subscriber.rs
+++ b/tracing/benches/subscriber.rs
@@ -13,7 +13,7 @@ use tracing::{field, span, Event, Id, Metadata};
 /// A subscriber that is enabled but otherwise does nothing.
 struct EnabledSubscriber;
 
-impl tracing::Subscriber for EnabledSubscriber {
+impl tracing::Collect for EnabledSubscriber {
     fn new_span(&self, span: &span::Attributes<'_>) -> Id {
         let _ = span;
         Id::from_u64(0xDEAD_FACE)
@@ -57,7 +57,7 @@ impl<'a> field::Visit for Visitor<'a> {
     }
 }
 
-impl tracing::Subscriber for VisitingSubscriber {
+impl tracing::Collect for VisitingSubscriber {
     fn new_span(&self, span: &span::Attributes<'_>) -> Id {
         let mut visitor = Visitor(self.0.lock().unwrap());
         span.record(&mut visitor);
@@ -97,13 +97,13 @@ const N_SPANS: usize = 100;
 fn criterion_benchmark(c: &mut Criterion) {
     let mut c = c.benchmark_group("scoped/subscriber");
     c.bench_function("span_no_fields", |b| {
-        tracing::subscriber::with_default(EnabledSubscriber, || {
+        tracing::collect::with_default(EnabledSubscriber, || {
             b.iter(|| span!(Level::TRACE, "span"))
         });
     });
 
     c.bench_function("enter_span", |b| {
-        tracing::subscriber::with_default(EnabledSubscriber, || {
+        tracing::collect::with_default(EnabledSubscriber, || {
             let span = span!(Level::TRACE, "span");
             #[allow(clippy::unit_arg)]
             b.iter(|| black_box(span.in_scope(|| {})))
@@ -111,7 +111,7 @@ fn criterion_benchmark(c: &mut Criterion) {
     });
 
     c.bench_function("event", |b| {
-        tracing::subscriber::with_default(EnabledSubscriber, || {
+        tracing::collect::with_default(EnabledSubscriber, || {
             b.iter(|| {
                 tracing::event!(Level::TRACE, "hello");
             });
@@ -125,13 +125,13 @@ fn criterion_benchmark(c: &mut Criterion) {
         }
 
         let n = black_box(N_SPANS);
-        tracing::subscriber::with_default(EnabledSubscriber, || {
+        tracing::collect::with_default(EnabledSubscriber, || {
             b.iter(|| (0..n).fold(mk_span(0), |_, i| mk_span(i as u64)))
         });
     });
 
     c.bench_function("span_with_fields", |b| {
-        tracing::subscriber::with_default(EnabledSubscriber, || {
+        tracing::collect::with_default(EnabledSubscriber, || {
             b.iter(|| {
                 span!(
                     Level::TRACE,
@@ -147,7 +147,7 @@ fn criterion_benchmark(c: &mut Criterion) {
 
     c.bench_function("span_with_fields_record", |b| {
         let subscriber = VisitingSubscriber(Mutex::new(String::from("")));
-        tracing::subscriber::with_default(subscriber, || {
+        tracing::collect::with_default(subscriber, || {
             b.iter(|| {
                 span!(
                     Level::TRACE,
@@ -168,14 +168,14 @@ fn bench_dispatch(c: &mut Criterion) {
     let mut group = c.benchmark_group("no/dispatch");
     group.bench_function("get_ref", |b| {
         b.iter(|| {
-            tracing::dispatcher::get_default(|current| {
+            tracing::dispatch::get_default(|current| {
                 black_box(¤t);
             })
         })
     });
     group.bench_function("get_clone", |b| {
         b.iter(|| {
-            let current = tracing::dispatcher::get_default(|current| current.clone());
+            let current = tracing::dispatch::get_default(|current| current.clone());
             black_box(current);
         })
     });
@@ -183,18 +183,18 @@ fn bench_dispatch(c: &mut Criterion) {
 
     let mut group = c.benchmark_group("scoped/dispatch");
     group.bench_function("get_ref", |b| {
-        tracing::subscriber::with_default(EnabledSubscriber, || {
+        tracing::collect::with_default(EnabledSubscriber, || {
             b.iter(|| {
-                tracing::dispatcher::get_default(|current| {
+                tracing::dispatch::get_default(|current| {
                     black_box(¤t);
                 })
             })
         })
     });
     group.bench_function("get_clone", |b| {
-        tracing::subscriber::with_default(EnabledSubscriber, || {
+        tracing::collect::with_default(EnabledSubscriber, || {
             b.iter(|| {
-                let current = tracing::dispatcher::get_default(|current| current.clone());
+                let current = tracing::dispatch::get_default(|current| current.clone());
                 black_box(current);
             })
         })
diff --git a/tracing/src/collect.rs b/tracing/src/collect.rs
new file mode 100644
index 0000000000..75b1edffe7
--- /dev/null
+++ b/tracing/src/collect.rs
@@ -0,0 +1,68 @@
+//! Collects and records trace data.
+pub use tracing_core::collect::*;
+
+#[cfg(feature = "std")]
+#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
+pub use tracing_core::dispatch::DefaultGuard;
+
+/// Sets this collector as the default for the duration of a closure.
+///
+/// The default collector 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 collector that
+/// tagged that span, instead.
+///
+/// [`Span`]: ../span/struct.Span.html
+/// [`Collect`]: ../collect/trait.Collect.html
+/// [`Event`]: :../event/struct.Event.html
+#[cfg(feature = "std")]
+#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
+pub fn with_default(collector: S, f: impl FnOnce() -> T) -> T
+where
+    S: Collect + Send + Sync + 'static,
+{
+    crate::dispatch::with_default(&crate::Dispatch::new(collector), f)
+}
+
+/// Sets this collector as the global default for the duration of the entire program.
+/// Will be used as a fallback if no thread-local collector has been set in a thread (using `with_default`.)
+///
+/// Can only be set once; subsequent attempts to set the global default will fail.
+/// Returns whether the initialization was successful.
+///
+/// Note: Libraries should *NOT* call `set_global_default()`! That will cause conflicts when
+/// executables try to set them later.
+///
+/// [span]: ../span/index.html
+/// [`Event`]: ../event/struct.Event.html
+#[cfg(feature = "alloc")]
+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
+pub fn set_global_default(collector: S) -> Result<(), SetGlobalDefaultError>
+where
+    S: Collect + Send + Sync + 'static,
+{
+    crate::dispatch::set_global_default(crate::Dispatch::new(collector))
+}
+
+/// Sets the collector as the default for the duration of the lifetime of the
+/// returned [`DefaultGuard`]
+///
+/// The default collector 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 collector that
+/// tagged that span, instead.
+///
+/// [`Span`]: ../span/struct.Span.html
+/// [`Event`]: :../event/struct.Event.html
+/// [`DefaultGuard`]: ../dispatcher/struct.DefaultGuard.html
+#[cfg(feature = "std")]
+#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
+#[must_use = "Dropping the guard unregisters the collector."]
+pub fn set_default(collector: S) -> DefaultGuard
+where
+    S: Collect + Send + Sync + 'static,
+{
+    crate::dispatch::set_default(&crate::Dispatch::new(collector))
+}
+
+pub use tracing_core::dispatch::SetGlobalDefaultError;
diff --git a/tracing/src/dispatcher.rs b/tracing/src/dispatch.rs
similarity index 63%
rename from tracing/src/dispatcher.rs
rename to tracing/src/dispatch.rs
index a7e2a7c5aa..448dc5b98e 100644
--- a/tracing/src/dispatcher.rs
+++ b/tracing/src/dispatch.rs
@@ -1,34 +1,34 @@
-//! Dispatches trace events to [`Subscriber`]s.
+//! Dispatches trace events to a [`Collect`].
 //!
 //! The _dispatcher_ is the component of the tracing system which is responsible
 //! for forwarding trace data from the instrumentation points that generate it
-//! to the subscriber that collects it.
+//! to the collector that collects it.
 //!
 //! # Using the Trace Dispatcher
 //!
-//! Every thread in a program using `tracing` has a _default subscriber_. When
+//! Every thread in a program using `tracing` has a _default collector_. When
 //! events occur, or spans are created, they are dispatched to the thread's
-//! current subscriber.
+//! current collector.
 //!
-//! ## Setting the Default Subscriber
+//! ## Setting the Default Collector
 //!
-//! By default, the current subscriber is an empty implementation that does
-//! nothing. To use a subscriber implementation, it must be set as the default.
+//! By default, the current collector is an empty implementation that does
+//! nothing. To use a collector implementation, it must be set as the default.
 //! There are two methods for doing so: [`with_default`] and
-//! [`set_global_default`]. `with_default` sets the default subscriber for the
-//! duration of a scope, while `set_global_default` sets a default subscriber
+//! [`set_global_default`]. `with_default` sets the default collector for the
+//! duration of a scope, while `set_global_default` sets a default collector
 //! for the entire process.
 //!
-//! To use either of these functions, we must first wrap our subscriber in a
-//! [`Dispatch`], a cloneable, type-erased reference to a subscriber. For
+//! To use either of these functions, we must first wrap our collector in a
+//! [`Dispatch`], a cloneable, type-erased reference to a collector. For
 //! example:
 //! ```rust
-//! # pub struct FooSubscriber;
+//! # pub struct FooCollector;
 //! # use tracing_core::{
-//! #   dispatcher, Event, Metadata,
+//! #   dispatch, Event, Metadata,
 //! #   span::{Attributes, Id, Record}
 //! # };
-//! # impl tracing_core::Subscriber for FooSubscriber {
+//! # impl tracing_core::Collect for FooCollector {
 //! #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
 //! #   fn record(&self, _: &Id, _: &Record) {}
 //! #   fn event(&self, _: &Event) {}
@@ -37,24 +37,24 @@
 //! #   fn enter(&self, _: &Id) {}
 //! #   fn exit(&self, _: &Id) {}
 //! # }
-//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } }
+//! # impl FooCollector { fn new() -> Self { FooCollector } }
 //! # #[cfg(feature = "alloc")]
-//! use dispatcher::Dispatch;
+//! use dispatch::Dispatch;
 //!
 //! # #[cfg(feature = "alloc")]
-//! let my_subscriber = FooSubscriber::new();
+//! let my_collector = FooCollector::new();
 //! # #[cfg(feature = "alloc")]
-//! let my_dispatch = Dispatch::new(my_subscriber);
+//! let my_dispatch = Dispatch::new(my_collector);
 //! ```
 //! Then, we can use [`with_default`] to set our `Dispatch` as the default for
 //! the duration of a block:
 //! ```rust
-//! # pub struct FooSubscriber;
+//! # pub struct FooCollector;
 //! # use tracing_core::{
-//! #   dispatcher, Event, Metadata,
+//! #   dispatch, Event, Metadata,
 //! #   span::{Attributes, Id, Record}
 //! # };
-//! # impl tracing_core::Subscriber for FooSubscriber {
+//! # impl tracing_core::Collect for FooCollector {
 //! #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
 //! #   fn record(&self, _: &Id, _: &Record) {}
 //! #   fn event(&self, _: &Event) {}
@@ -63,35 +63,35 @@
 //! #   fn enter(&self, _: &Id) {}
 //! #   fn exit(&self, _: &Id) {}
 //! # }
-//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } }
+//! # impl FooCollector { fn new() -> Self { FooCollector } }
 //! # #[cfg(feature = "alloc")]
-//! # let my_subscriber = FooSubscriber::new();
+//! # let my_collector = FooCollector::new();
 //! # #[cfg(feature = "alloc")]
-//! # let my_dispatch = dispatcher::Dispatch::new(my_subscriber);
-//! // no default subscriber
+//! # let my_dispatch = dispatch::Dispatch::new(my_collector);
+//! // no default collector
 //!
 //! # #[cfg(feature = "std")]
-//! dispatcher::with_default(&my_dispatch, || {
-//!     // my_subscriber is the default
+//! dispatch::with_default(&my_dispatch, || {
+//!     // my_collector is the default
 //! });
 //!
-//! // no default subscriber again
+//! // no default collector again
 //! ```
 //! It's important to note that `with_default` will not propagate the current
-//! thread's default subscriber to any threads spawned within the `with_default`
-//! block. To propagate the default subscriber to new threads, either use
+//! thread's default collector to any threads spawned within the `with_default`
+//! block. To propagate the default collector to new threads, either use
 //! `with_default` from the new thread, or use `set_global_default`.
 //!
 //! As an alternative to `with_default`, we can use [`set_global_default`] to
 //! set a `Dispatch` as the default for all threads, for the lifetime of the
 //! program. For example:
 //! ```rust
-//! # pub struct FooSubscriber;
+//! # pub struct FooCollector;
 //! # use tracing_core::{
-//! #   dispatcher, Event, Metadata,
+//! #   dispatch, Event, Metadata,
 //! #   span::{Attributes, Id, Record}
 //! # };
-//! # impl tracing_core::Subscriber for FooSubscriber {
+//! # impl tracing_core::Collect for FooCollector {
 //! #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
 //! #   fn record(&self, _: &Id, _: &Record) {}
 //! #   fn event(&self, _: &Event) {}
@@ -100,20 +100,20 @@
 //! #   fn enter(&self, _: &Id) {}
 //! #   fn exit(&self, _: &Id) {}
 //! # }
-//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } }
+//! # impl FooCollector { fn new() -> Self { FooCollector } }
 //! # #[cfg(feature = "alloc")]
-//! # let my_subscriber = FooSubscriber::new();
+//! # let my_collector = FooCollector::new();
 //! # #[cfg(feature = "alloc")]
-//! # let my_dispatch = dispatcher::Dispatch::new(my_subscriber);
-//! // no default subscriber
+//! # let my_dispatch = dispatch::Dispatch::new(my_collector);
+//! // no default collector
 //!
 //! # #[cfg(feature = "alloc")]
-//! dispatcher::set_global_default(my_dispatch)
+//! dispatch::set_global_default(my_dispatch)
 //!     // `set_global_default` will return an error if the global default
-//!     // subscriber has already been set.
+//!     // collector has already been set.
 //!     .expect("global default was already set!");
 //!
-//! // `my_subscriber` is now the default
+//! // `my_collector` is now the default
 //! ```
 //! 
//!
Note
@@ -126,28 +126,28 @@ //! instead. //!
//! -//! ## Accessing the Default Subscriber +//! ## Accessing the Default Collector //! -//! A thread's current default subscriber can be accessed using the +//! A thread's current default collector can be accessed using the //! [`get_default`] function, which executes a closure with a reference to the //! currently default `Dispatch`. This is used primarily by `tracing` //! instrumentation. //! -//! [`Subscriber`]: struct.Subscriber.html +//! [`Collect`]: struct.Collect.html //! [`with_default`]: fn.with_default.html //! [`set_global_default`]: fn.set_global_default.html //! [`get_default`]: fn.get_default.html //! [`Dispatch`]: struct.Dispatch.html #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] -pub use tracing_core::dispatcher::set_default; +pub use tracing_core::dispatch::set_default; #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] -pub use tracing_core::dispatcher::with_default; +pub use tracing_core::dispatch::with_default; #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] -pub use tracing_core::dispatcher::DefaultGuard; -pub use tracing_core::dispatcher::{ +pub use tracing_core::dispatch::DefaultGuard; +pub use tracing_core::dispatch::{ get_default, set_global_default, Dispatch, SetGlobalDefaultError, }; @@ -157,4 +157,4 @@ pub use tracing_core::dispatcher::{ /// stability guarantees. If you use it, and it breaks or disappears entirely, /// don't say we didn;'t warn you. #[doc(hidden)] -pub use tracing_core::dispatcher::has_been_set; +pub use tracing_core::dispatch::has_been_set; diff --git a/tracing/src/instrument.rs b/tracing/src/instrument.rs index ee53b99746..e3aaf0b4ef 100644 --- a/tracing/src/instrument.rs +++ b/tracing/src/instrument.rs @@ -1,4 +1,4 @@ -use crate::{dispatcher, span::Span, Dispatch}; +use crate::{dispatch, span::Span, Dispatch}; use core::pin::Pin; use core::task::{Context, Poll}; use core::{future::Future, marker::Sized}; @@ -77,51 +77,49 @@ pub trait Instrument: Sized { } /// Extension trait allowing futures to be instrumented with -/// a `tracing` [`Subscriber`]. +/// a `tracing` collector. /// -/// [`Subscriber`]: ../trait.Subscriber.html -pub trait WithSubscriber: Sized { - /// Attaches the provided [`Subscriber`] to this type, returning a +pub trait WithCollector: Sized { + /// Attaches the provided collector to this type, returning a /// `WithDispatch` wrapper. /// - /// The attached subscriber will be set as the [default] when the returned `Future` is polled. + /// The attached collector will be set as the [default] when the returned `Future` is polled. /// - /// [`Subscriber`]: ../trait.Subscriber.html - /// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber - fn with_subscriber(self, subscriber: S) -> WithDispatch + /// [`Collect`]: ../trait.Collect.html + /// [default]: https://docs.rs/tracing/latest/tracing/dispatch/index.html#setting-the-default-collector + fn with_collector(self, collector: S) -> WithDispatch where S: Into, { WithDispatch { inner: self, - dispatch: subscriber.into(), + dispatch: collector.into(), } } - /// Attaches the current [default] [`Subscriber`] to this type, returning a + /// Attaches the current [default] collector to this type, returning a /// `WithDispatch` wrapper. /// /// When the wrapped type is a future, stream, or sink, the attached - /// subscriber will be set as the [default] while it is being polled. - /// When the wrapped type is an executor, the subscriber will be set as the + /// collector will be set as the [default] while it is being polled. + /// When the wrapped type is an executor, the collector will be set as the /// default for any futures spawned on that executor. /// /// This can be used to propagate the current dispatcher context when /// spawning a new future. /// - /// [`Subscriber`]: ../trait.Subscriber.html - /// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber + /// [default]: https://docs.rs/tracing/latest/tracing/dispatch/index.html#setting-the-default-collector #[inline] - fn with_current_subscriber(self) -> WithDispatch { + fn with_current_collector(self) -> WithDispatch { WithDispatch { inner: self, - dispatch: dispatcher::get_default(|default| default.clone()), + dispatch: dispatch::get_default(|default| default.clone()), } } } pin_project! { - /// A future that has been instrumented with a `tracing` subscriber. + /// A future that has been instrumented with a `tracing` collector. #[derive(Clone, Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct WithDispatch { diff --git a/tracing/src/lib.rs b/tracing/src/lib.rs index 1b03fc1e3d..208568c67e 100644 --- a/tracing/src/lib.rs +++ b/tracing/src/lib.rs @@ -25,7 +25,7 @@ //! # Core Concepts //! //! The core of `tracing`'s API is composed of _spans_, _events_ and -//! _subscribers_. We'll cover these in turn. +//! _collectors_. We'll cover these in turn. //! //! ## Spans //! @@ -92,23 +92,23 @@ //! The [`Event` struct][`Event`] documentation provides further details on using //! events. //! -//! ## Subscribers +//! ## Collectors //! //! As `Span`s and `Event`s occur, they are recorded or aggregated by -//! implementations of the [`Subscriber`] trait. `Subscriber`s are notified +//! implementations of the [`Collect`] trait. Collectors 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: +//! notifications are represented by the following `Collect` trait methods: //! -//! + [`event`][Subscriber::event], called when an `Event` takes place, +//! + [`event`][Collect::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_ +//! In addition, collectors 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 +//! or `Event`. If a call to `Collect::enabled` returns `false` for a given +//! set of metadata, that collector 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 +//! active collectors express interest in a given set of metadata by returning //! `true`, then the corresponding `Span` or `Event` will never be constructed. //! //! # Usage @@ -201,7 +201,7 @@ //! event. Optionally, the [target] and [parent span] may be overridden. If the //! target and parent span are not overridden, they will default to the //! module path where the macro was invoked and the current span (as determined -//! by the subscriber), respectively. +//! by the collector), respectively. //! //! For example: //! @@ -527,20 +527,20 @@ //! //! ## In executables //! -//! In order to record trace events, executables have to use a `Subscriber` -//! implementation compatible with `tracing`. A `Subscriber` implements a +//! In order to record trace events, executables have to use a collector +//! implementation compatible with `tracing`. A collector implements a //! way of collecting trace data, such as by logging it to standard output. //! -//! This library does not contain any `Subscriber` implementations; these are +//! This library does not contain any `Collect` implementations; these are //! provided by [other crates](#related-crates). //! -//! The simplest way to use a subscriber is to call the [`set_global_default`] +//! The simplest way to use a collector is to call the [`set_global_default`] //! function: //! //! ``` -//! # pub struct FooSubscriber; +//! # pub struct FooCollector; //! # use tracing::{span::{Id, Attributes, Record}, Metadata}; -//! # impl tracing::Subscriber for FooSubscriber { +//! # impl tracing::Collect for FooCollector { //! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } //! # fn record(&self, _: &Id, _: &Record) {} //! # fn event(&self, _: &tracing::Event) {} @@ -549,15 +549,15 @@ //! # fn enter(&self, _: &Id) {} //! # fn exit(&self, _: &Id) {} //! # } -//! # impl FooSubscriber { -//! # fn new() -> Self { FooSubscriber } +//! # impl FooCollector { +//! # fn new() -> Self { FooCollector } //! # } //! # fn main() { //! //! # #[cfg(feature = "alloc")] -//! let my_subscriber = FooSubscriber::new(); +//! let my_collector = FooCollector::new(); //! # #[cfg(feature = "alloc")] -//! tracing::subscriber::set_global_default(my_subscriber) +//! tracing::collect::set_global_default(my_collector) //! .expect("setting tracing default failed"); //! # } //! ``` @@ -570,19 +570,19 @@ //! executables that depend on the library try to set the default later. //!
//! -//! This subscriber will be used as the default in all threads for the +//! This collector will be used as the default in all threads for the //! remainder of the duration of the program, similar to setting the logger //! in the `log` crate. //! -//! In addition, the default subscriber can be set through using the +//! In addition, the default collector can be set through using the //! [`with_default`] function. This follows the `tokio` pattern of using //! closures to represent executing code in a context that is exited at the end //! of the closure. For example: //! //! ```rust -//! # pub struct FooSubscriber; +//! # pub struct FooCollector; //! # use tracing::{span::{Id, Attributes, Record}, Metadata}; -//! # impl tracing::Subscriber for FooSubscriber { +//! # impl tracing::Collect for FooCollector { //! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } //! # fn record(&self, _: &Id, _: &Record) {} //! # fn event(&self, _: &tracing::Event) {} @@ -591,27 +591,27 @@ //! # fn enter(&self, _: &Id) {} //! # fn exit(&self, _: &Id) {} //! # } -//! # impl FooSubscriber { -//! # fn new() -> Self { FooSubscriber } +//! # impl FooCollector { +//! # fn new() -> Self { FooCollector } //! # } //! # fn main() { //! -//! let my_subscriber = FooSubscriber::new(); +//! let my_collector = FooCollector::new(); //! # #[cfg(feature = "std")] -//! tracing::subscriber::with_default(my_subscriber, || { +//! tracing::collect::with_default(my_collector, || { //! // Any trace events generated in this closure or by functions it calls -//! // will be collected by `my_subscriber`. +//! // will be collected by `my_collector`. //! }) //! # } //! ``` //! -//! This approach allows trace data to be collected by multiple subscribers +//! This approach allows trace data to be collected by multiple collectors //! within different contexts in the program. Note that the override only applies to the //! currently executing thread; other threads will not see the change from with_default. //! -//! Any trace events generated outside the context of a subscriber will not be collected. +//! Any trace events generated outside the context of a collector will not be collected. //! -//! Once a subscriber has been set, instrumentation points may be added to the +//! Once a collector has been set, instrumentation points may be added to the //! executable using the `tracing` crate's macros. //! //! ## `log` Compatibility @@ -623,13 +623,13 @@ //! libraries and applications either emit or consume `log` records. Therefore, //! `tracing` provides multiple forms of interoperability with `log`: `tracing` //! instrumentation can emit `log` records, and a compatibility layer enables -//! `tracing` [`Subscriber`]s to consume `log` records as `tracing` [`Event`]s. +//! `tracing` [`Collect`]s to consume `log` records as `tracing` [`Event`]s. //! //! ### Emitting `log` Records //! //! This crate provides two feature flags, "log" and "log-always", which will //! cause [spans] and [events] to emit `log` records. When the "log" feature is -//! enabled, if no `tracing` `Subscriber` is active, invoking an event macro or +//! enabled, if no `tracing` collector is active, invoking an event macro or //! creating a span with fields will emit a `log` record. This is intended //! primarily for use in libraries which wish to emit diagnostics that can be //! consumed by applications using `tracing` *or* `log`, without paying the @@ -637,7 +637,7 @@ //! in use. //! //! Enabling the "log-always" feature will cause `log` records to be emitted -//! even if a `tracing` `Subscriber` _is_ set. This is intended to be used in +//! even if a `tracing` collector _is_ set. This is intended to be used in //! applications where a `log` `Logger` is being used to record a textual log, //! and `tracing` is used only to record other forms of diagnostics (such as //! metrics, profiling, or distributed tracing data). Unlike the "log" feature, @@ -662,7 +662,7 @@ //! ### Consuming `log` Records //! //! The [`tracing-log`] crate provides a compatibility layer which -//! allows a `tracing` [`Subscriber`] to consume `log` records as though they +//! allows a `tracing` collector to consume `log` records as though they //! were `tracing` [events]. This allows applications using `tracing` to record //! the logs emitted by dependencies using `log` as events within the context of //! the application's trace tree. See [that crate's documentation][log-tracer] @@ -699,9 +699,9 @@ //! require a global memory allocator. //! //! The "alloc" feature is required to enable the [`Dispatch::new`] function, -//! which requires dynamic memory allocation to construct a `Subscriber` trait +//! which requires dynamic memory allocation to construct a collect trait //! object at runtime. When liballoc is disabled, new `Dispatch`s may still be -//! created from `&'static dyn Subscriber` references, using +//! created from `&'static dyn Collector` references, using //! [`Dispatch::from_static`]. //! //! The "std" feature is required to enable the following features: @@ -718,26 +718,26 @@ //! without `std` and `alloc`. //! //! [`libstd`]: https://doc.rust-lang.org/std/index.html -//! [`Dispatch::new`]: crate::dispatcher::Dispatch::new -//! [`Dispatch::from_static`]: crate::dispatcher::Dispatch::from_static -//! [`Dispatch::set_default`]: crate::dispatcher::set_default -//! [`with_default`]: crate::dispatcher::with_default +//! [`Dispatch::new`]: crate::dispatch::Dispatch::new +//! [`Dispatch::from_static`]: crate::dispatch::Dispatch::from_static +//! [`Dispatch::set_default`]: crate::dispatch::set_default +//! [`with_default`]: crate::dispatch::with_default //! [err]: crate::field::Visit::record_error //! //! ## Related Crates //! //! In addition to `tracing` and `tracing-core`, the [`tokio-rs/tracing`] repository //! contains several additional crates designed to be used with the `tracing` ecosystem. -//! This includes a collection of `Subscriber` implementations, as well as utility -//! and adapter crates to assist in writing `Subscriber`s and instrumenting +//! This includes a collection of `Collect` implementations, as well as utility +//! and adapter crates to assist in writing collectors and instrumenting //! applications. //! //! In particular, the following crates are likely to be of interest: //! //! - [`tracing-futures`] provides a compatibility layer with the `futures` //! crate, allowing spans to be attached to `Future`s, `Stream`s, and `Executor`s. -//! - [`tracing-subscriber`] provides `Subscriber` implementations and -//! utilities for working with `Subscriber`s. This includes a [`FmtSubscriber`] +//! - [`tracing-subscriber`] provides `tracing_subscriber::Subscribe` implementations and +//! utilities for working with collectors. This includes a [`FmtSubscriber`] //! `FmtSubscriber` for logging formatted trace data to stdout, with similar //! filtering and formatting to the [`env_logger`] crate. //! - [`tracing-log`] provides a compatibility layer with the [`log`] crate, @@ -767,13 +767,13 @@ //! (Linux-only). //! - [`tracing-bunyan-formatter`] provides a layer implementation that reports events and spans //! in [bunyan] format, enriched with timing information. -//! - [`tracing-wasm`] provides a `Subscriber`/`Layer` implementation that reports +//! - [`tracing-wasm`] provides a `Collect`/`Subscribe` implementation that reports //! events and spans via browser `console.log` and [User Timing API (`window.performance`)]. //! - [`tide-tracing`] provides a [tide] middleware to trace all incoming requests and responses. //! - [`test-env-log`] takes care of initializing `tracing` for tests, based on //! environment variables with an `env_logger` compatible syntax. //! - [`tracing-unwrap`] provides convenience methods to report failed unwraps -//! on `Result` or `Option` types to a `Subscriber`. +//! on `Result` or `Option` types to a [`collect`]. //! - [`diesel-tracing`] provides integration with [`diesel`] database connections. //! - [`tracing-tracy`] provides a way to collect [Tracy] profiles in instrumented //! applications. @@ -819,11 +819,11 @@ //! //! * A set of features controlling the [static verbosity level]. //! * `log`: causes trace instrumentation points to emit [`log`] records as well -//! as trace events, if a default `tracing` subscriber has not been set. This +//! as trace events, if a default `tracing` collector has not been set. This //! is intended for use in libraries whose users may be using either `tracing` //! or `log`. //! * `log-always`: Emit `log` records from all `tracing` spans and events, even -//! if a `tracing` subscriber has been set. This should be set only by +//! if a `tracing` collector has been set. This should be set only by //! applications which intend to collect traces and logs separately; if an //! adapter is used to convert `log` records into `tracing` events, this will //! cause duplicate events to occur. @@ -855,16 +855,16 @@ //! [`in_scope`]: span::Span::in_scope //! [event]: Event //! [events]: Event -//! [`Subscriber`]: subscriber::Subscriber -//! [Subscriber::event]: subscriber::Subscriber::event -//! [`enter`]: subscriber::Subscriber::enter -//! [`exit`]: subscriber::Subscriber::exit -//! [`enabled`]: subscriber::Subscriber::enabled +//! [`collect`]: collect::Collect +//! [Collect::event]: collect::Collect::event +//! [`enter`]: collect::Collect::enter +//! [`exit`]: collect::Collect::exit +//! [`enabled`]: collect::Collect::enabled //! [metadata]: Metadata //! [`field::display`]: field::display //! [`field::debug`]: field::debug -//! [`set_global_default`]: subscriber::set_global_default -//! [`with_default`]: subscriber::with_default +//! [`set_global_default`]: collect::set_global_default +//! [`with_default`]: collect::with_default //! [`tokio-rs/tracing`]: https://github.com/tokio-rs/tracing //! [`tracing-futures`]: https://crates.io/crates/tracing-futures //! [`tracing-subscriber`]: https://crates.io/crates/tracing-subscriber @@ -922,7 +922,7 @@ use tracing_core::*; #[doc(inline)] pub use self::instrument::Instrument; -pub use self::{dispatcher::Dispatch, event::Event, field::Value, subscriber::Subscriber}; +pub use self::{collect::Collect, dispatch::Dispatch, event::Event, field::Value}; #[doc(hidden)] pub use self::span::Id; @@ -944,18 +944,18 @@ pub use tracing_attributes::instrument; #[macro_use] mod macros; -pub mod dispatcher; +pub mod collect; +pub mod dispatch; pub mod field; /// Attach a span to a `std::future::Future`. pub mod instrument; pub mod level_filters; pub mod span; -pub mod subscriber; #[doc(hidden)] pub mod __macro_support { pub use crate::callsite::{Callsite, Registration}; - use crate::{subscriber::Interest, Metadata}; + use crate::{collect::Interest, Metadata}; use core::fmt; use core::sync::atomic::{AtomicUsize, Ordering}; use tracing_core::Once; @@ -1045,7 +1045,7 @@ pub mod __macro_support { pub fn is_enabled(&self, interest: Interest) -> bool { interest.is_always() - || crate::dispatcher::get_default(|default| default.enabled(self.meta)) + || crate::dispatch::get_default(|default| default.enabled(self.meta)) } #[inline] diff --git a/tracing/src/macros.rs b/tracing/src/macros.rs index 8128c5609a..fe456e48aa 100644 --- a/tracing/src/macros.rs +++ b/tracing/src/macros.rs @@ -31,7 +31,7 @@ macro_rules! span { level: $lvl, fields: $($fields)* }; - let mut interest = $crate::subscriber::Interest::never(); + let mut interest = $crate::collect::Interest::never(); if $crate::level_enabled!($lvl) && { interest = CALLSITE.interest(); !interest.is_never() } && CALLSITE.is_enabled(interest) @@ -63,7 +63,7 @@ macro_rules! span { fields: $($fields)* }; - let mut interest = $crate::subscriber::Interest::never(); + let mut interest = $crate::collect::Interest::never(); if $crate::level_enabled!($lvl) && { interest = CALLSITE.interest(); !interest.is_never() } && CALLSITE.is_enabled(interest) diff --git a/tracing/src/span.rs b/tracing/src/span.rs index 86af4cfa06..4c8b851816 100644 --- a/tracing/src/span.rs +++ b/tracing/src/span.rs @@ -45,10 +45,10 @@ //! ## Recording Span Creation //! //! The [`Attributes`] type contains data associated with a span, and is -//! provided to the [`Subscriber`] when a new span is created. It contains +//! provided to the [collector] when a new span is created. It contains //! the span's metadata, the ID of [the span's parent][parent] if one was //! explicitly set, and any fields whose values were recorded when the span was -//! constructed. The subscriber, which is responsible for recording `tracing` +//! constructed. The collector, which is responsible for recording `tracing` //! data, can then store or record these values. //! //! # The Span Lifecycle @@ -162,7 +162,7 @@ //! ``` //! //! A child span should typically be considered _part_ of its parent. For -//! example, if a subscriber is recording the length of time spent in various +//! example, if a collector is recording the length of time spent in various //! spans, it should generally include the time spent in a span's children as //! part of that span's duration. //! @@ -220,11 +220,11 @@ //! 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 +//! [collector]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`] 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`] method is called with that span's ID. The subscriber may use +//! collector that the span has been exited. When span handles are dropped, the +//! [`drop_span`] method is called with that span's ID. The collector 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 @@ -236,22 +236,22 @@ //! { //! span!(Level::TRACE, "my_span").in_scope(|| { //! // perform some work in the context of `my_span`... -//! }); // --> Subscriber::exit(my_span) +//! }); // --> Collect::exit(my_span) //! //! // The handle to `my_span` only lives inside of this block; when it is -//! // dropped, the subscriber will be informed via `drop_span`. +//! // dropped, the collector will be informed via `drop_span`. //! -//! } // --> Subscriber::drop_span(my_span) +//! } // --> Collect::drop_span(my_span) //! ``` //! //! 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`] method, which is called +//! been dropped, collectors have a [`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. +//! collector may then treat it as closed. //! //! # When to use spans //! @@ -303,10 +303,10 @@ //! [`info_span!`]: ../macro.info_span.html //! [`warn_span!`]: ../macro.warn_span.html //! [`error_span!`]: ../macro.error_span.html -//! [`clone_span`]: ../subscriber/trait.Subscriber.html#method.clone_span -//! [`drop_span`]: ../subscriber/trait.Subscriber.html#method.drop_span -//! [`exit`]: ../subscriber/trait.Subscriber.html#tymethod.exit -//! [`Subscriber`]: ../subscriber/trait.Subscriber.html +//! [`clone_span`]: ../collect/trait.Collect.html#method.clone_span +//! [`drop_span`]: ../collect/trait.Collect.html#method.drop_span +//! [`exit`]: ../collect/trait.Collect.html#tymethod.exit +//! [collector]: ../collect/trait.Collect.html //! [`Attributes`]: struct.Attributes.html //! [`enter`]: struct.Span.html#method.enter //! [`in_scope`]: struct.Span.html#method.in_scope @@ -316,7 +316,7 @@ pub use tracing_core::span::{Attributes, Id, Record}; use crate::{ - dispatcher::{self, Dispatch}, + dispatch::{self, Dispatch}, field, Metadata, }; use core::{ @@ -335,7 +335,7 @@ pub trait AsId: crate::sealed::Sealed { /// 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 +/// If the span was rejected by the current `Collector`'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)] @@ -358,14 +358,14 @@ pub struct Span { /// span handles; users should typically not need to interact with it directly. #[derive(Debug)] pub(crate) struct Inner { - /// The span's ID, as provided by `subscriber`. + /// The span's ID, as provided by `collector`. id: Id, - /// The subscriber that will receive events relating to this span. + /// The collector that will receive events relating to this span. /// - /// This should be the same subscriber that provided this span with its + /// This should be the same collector that provided this span with its /// `id`. - subscriber: Dispatch, + collector: Dispatch, } /// A guard representing a span which has been entered and is currently @@ -396,18 +396,18 @@ impl Span { /// Constructs a new `Span` with the given [metadata] and set of /// [field values]. /// - /// The new span will be constructed by the currently-active [`Subscriber`], + /// The new span will be constructed by the currently-active [collector], /// 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 - /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [collector]: ../collect/trait.Collect.html /// [field values]: ../field/struct.ValueSet.html /// [`follows_from`]: ../struct.Span.html#method.follows_from pub fn new(meta: &'static Metadata<'static>, values: &field::ValueSet<'_>) -> Span { - dispatcher::get_default(|dispatch| Self::new_with(meta, values, dispatch)) + dispatch::get_default(|dispatch| Self::new_with(meta, values, dispatch)) } #[inline] @@ -431,7 +431,7 @@ impl Span { /// [field values]: ../field/struct.ValueSet.html /// [`follows_from`]: ../struct.Span.html#method.follows_from pub fn new_root(meta: &'static Metadata<'static>, values: &field::ValueSet<'_>) -> Span { - dispatcher::get_default(|dispatch| Self::new_root_with(meta, values, dispatch)) + dispatch::get_default(|dispatch| Self::new_root_with(meta, values, dispatch)) } #[inline] @@ -460,7 +460,7 @@ impl Span { values: &field::ValueSet<'_>, ) -> Span { let mut parent = parent.into(); - dispatcher::get_default(move |dispatch| { + dispatch::get_default(move |dispatch| { Self::child_of_with(Option::take(&mut parent), meta, values, dispatch) }) } @@ -483,10 +483,10 @@ impl Span { /// Constructs a new disabled span with the given `Metadata`. /// /// This should be used when a span is constructed from a known callsite, - /// but the subscriber indicates that it is disabled. + /// but the collector indicates that it is disabled. /// /// Entering, exiting, and recording values on this span will not notify the - /// `Subscriber` but _may_ record log messages if the `log` feature flag is + /// `Collector` but _may_ record log messages if the `log` feature flag is /// enabled. #[inline(always)] pub fn new_disabled(meta: &'static Metadata<'static>) -> Span { @@ -510,16 +510,16 @@ impl Span { } } - /// Returns a handle to the span [considered by the `Subscriber`] to be the + /// Returns a handle to the span [considered by the `Collector`] to be the /// current span. /// - /// If the subscriber indicates that it does not track the current span, or + /// If the collector indicates that it does not track the current span, or /// that the thread from which this function is called is not currently /// inside a span, the returned span will be disabled. /// - /// [considered by the `Subscriber`]: ../subscriber/trait.Subscriber.html#method.current + /// [considered by the `Collector`]: ../collector/trait.Collector.html#method.current pub fn current() -> Span { - dispatcher::get_default(|dispatch| { + dispatch::get_default(|dispatch| { if let Some((id, meta)) = dispatch.current_span().into_inner() { let id = dispatch.clone_span(&id); Self { @@ -559,9 +559,9 @@ impl Span { } /// Enters this span, returning a guard that will exit the span when dropped. /// - /// If this span is enabled by the current subscriber, then this function will - /// call [`Subscriber::enter`] with the span's [`Id`], and dropping the guard - /// will call [`Subscriber::exit`]. If the span is disabled, this does + /// If this span is enabled by the current collector, then this function will + /// call [`Collector::enter`] with the span's [`Id`], and dropping the guard + /// will call [`Collector::exit`]. If the span is disabled, this does /// nothing. /// ///
@@ -753,12 +753,12 @@ impl Span { /// info!("i'm outside the span!") /// ``` /// - /// [`Subscriber::enter`]: ../subscriber/trait.Subscriber.html#method.enter - /// [`Subscriber::exit`]: ../subscriber/trait.Subscriber.html#method.exit + /// [`Collector::enter`]: ../collector/trait.Collector.html#method.enter + /// [`Collector::exit`]: ../collector/trait.Collector.html#method.exit /// [`Id`]: ../struct.Id.html pub fn enter(&self) -> Entered<'_> { if let Some(ref inner) = self.inner.as_ref() { - inner.subscriber.enter(&inner.id); + inner.collector.enter(&inner.id); } if_log_enabled! {{ @@ -945,7 +945,7 @@ impl Span { self } - /// Returns `true` if this span was disabled by the subscriber and does not + /// Returns `true` if this span was disabled by the collector and does not /// exist. /// /// See also [`is_none`]. @@ -960,7 +960,7 @@ impl Span { /// empty. /// /// If `is_none` returns `true` for a given span, then [`is_disabled`] will - /// also return `true`. However, when a span is disabled by the subscriber + /// also return `true`. However, when a span is disabled by the collector /// rather than constructed by `Span::none`, this method will return /// `false`, while `is_disabled` will return `true`. /// @@ -1063,15 +1063,15 @@ impl Span { } } - /// Invokes a function with a reference to this span's ID and subscriber. + /// Invokes a function with a reference to this span's ID and collector. /// /// if this span is enabled, the provided function is called, and the result is returned. /// If the span is disabled, the function is not called, and this method returns `None` /// instead. - pub fn with_subscriber(&self, f: impl FnOnce((&Id, &Dispatch)) -> T) -> Option { + pub fn with_collector(&self, f: impl FnOnce((&Id, &Dispatch)) -> T) -> Option { self.inner .as_ref() - .map(|inner| f((&inner.id, &inner.subscriber))) + .map(|inner| f((&inner.id, &inner.collector))) } } @@ -1141,10 +1141,10 @@ impl Drop for Span { fn drop(&mut self) { if let Some(Inner { ref id, - ref subscriber, + ref collector, }) = self.inner { - subscriber.try_close(id.clone()); + collector.try_close(id.clone()); } if_log_enabled!({ @@ -1178,7 +1178,7 @@ impl Inner { /// 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) + self.collector.record_follows_from(&self.id, &from) } /// Returns the span's ID. @@ -1187,13 +1187,13 @@ impl Inner { } fn record(&self, values: &Record<'_>) { - self.subscriber.record(&self.id, values) + self.collector.record(&self.id, values) } - fn new(id: Id, subscriber: &Dispatch) -> Self { + fn new(id: Id, collector: &Dispatch) -> Self { Inner { id, - subscriber: subscriber.clone(), + collector: collector.clone(), } } } @@ -1213,8 +1213,8 @@ impl Hash for Inner { impl Clone for Inner { fn clone(&self) -> Self { Inner { - id: self.subscriber.clone_span(&self.id), - subscriber: self.subscriber.clone(), + id: self.collector.clone_span(&self.id), + collector: self.collector.clone(), } } } @@ -1247,7 +1247,7 @@ impl<'a> Drop for Entered<'a> { // Running this behaviour on drop rather than with an explicit function // call means that spans may still be exited when unwinding. if let Some(inner) = self.span.inner.as_ref() { - inner.subscriber.exit(&inner.id); + inner.collector.exit(&inner.id); } if_log_enabled! {{ diff --git a/tracing/src/subscribe.rs b/tracing/src/subscribe.rs new file mode 100644 index 0000000000..a48fa09b84 --- /dev/null +++ b/tracing/src/subscribe.rs @@ -0,0 +1,71 @@ +//! Collects and records trace data. +pub use tracing_core::collect::*; + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +pub use tracing_core::dispatch::DefaultGuard; + +/// Sets this collector as the default for the duration of a closure. +/// +/// The default subscriber 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/struct.Span.html +/// [`Collect`]: ../collect/trait.Collect.html +// /// [`Event`]: :../event/struct.Event.html +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +pub fn with_default(collector: S, f: impl FnOnce() -> T) -> T +where + S: Collect + Send + Sync + 'static, +{ + crate::dispatch::with_default(&crate::Dispatch::new(collector), f) +} + +/// Sets this collector as the global default for the duration of the entire program. +/// Will be used as a fallback if no thread-local collector has been set in a thread (using `with_default`.) +/// +/// Can only be set once; subsequent attempts to set the global default will fail. +/// Returns whether the initialization was successful. +/// +/// Note: Libraries should *NOT* call `set_global_default()`! That will cause conflicts when +/// executables try to set them later. +/// +/// [span]: ../span/index.html +/// [`Collect`]: ../collect/trait.Collect.html +/// [`Event`]: ../event/struct.Event.html +#[cfg(feature = "alloc")] +#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] +pub fn set_global_default(collector: S) -> Result<(), SetGlobalDefaultError> +where + S: Collect + Send + Sync + 'static, +{ + crate::dispatch::set_global_default(crate::Dispatch::new(collector)) +} + +/// Sets the collector as the default for the duration of the lifetime of the +/// returned [`DefaultGuard`] +/// +/// The default collector 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 collector that +/// tagged that span, instead. +/// +/// [`Span`]: ../span/struct.Span.html +/// [`Collect`]: ../collect/trait.Collect.html +/// [`Event`]: :../event/struct.Event.html +/// [`DefaultGuard`]: ../dispatch/struct.DefaultGuard.html +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[must_use = "Dropping the guard unregisters the collector."] +pub fn set_default(collector: S) -> DefaultGuard +where + S: Collect + Send + Sync + 'static, +{ + crate::dispatch::set_default(&crate::Dispatch::new(collector)) +} + +pub use tracing_core::dispatch::SetGlobalDefaultError; +use tracing_core::Collect; diff --git a/tracing/src/subscriber.rs b/tracing/src/subscriber.rs deleted file mode 100644 index bcb51c5053..0000000000 --- a/tracing/src/subscriber.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Collects and records trace data. -pub use tracing_core::subscriber::*; - -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] -pub use tracing_core::dispatcher::DefaultGuard; - -/// Sets this subscriber as the default for the duration of a closure. -/// -/// The default subscriber 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/struct.Span.html -/// [`Subscriber`]: ../subscriber/trait.Subscriber.html -/// [`Event`]: :../event/struct.Event.html -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] -pub fn with_default(subscriber: S, f: impl FnOnce() -> T) -> T -where - S: Subscriber + Send + Sync + 'static, -{ - crate::dispatcher::with_default(&crate::Dispatch::new(subscriber), f) -} - -/// Sets this subscriber as the global default for the duration of the entire program. -/// Will be used as a fallback if no thread-local subscriber has been set in a thread (using `with_default`.) -/// -/// Can only be set once; subsequent attempts to set the global default will fail. -/// Returns whether the initialization was successful. -/// -/// Note: Libraries should *NOT* call `set_global_default()`! That will cause conflicts when -/// executables try to set them later. -/// -/// [span]: ../span/index.html -/// [`Subscriber`]: ../subscriber/trait.Subscriber.html -/// [`Event`]: ../event/struct.Event.html -#[cfg(feature = "alloc")] -#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))] -pub fn set_global_default(subscriber: S) -> Result<(), SetGlobalDefaultError> -where - S: Subscriber + Send + Sync + 'static, -{ - crate::dispatcher::set_global_default(crate::Dispatch::new(subscriber)) -} - -/// Sets the subscriber as the default for the duration of the lifetime of the -/// returned [`DefaultGuard`] -/// -/// The default subscriber 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/struct.Span.html -/// [`Subscriber`]: ../subscriber/trait.Subscriber.html -/// [`Event`]: :../event/struct.Event.html -/// [`DefaultGuard`]: ../dispatcher/struct.DefaultGuard.html -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] -#[must_use = "Dropping the guard unregisters the subscriber."] -pub fn set_default(subscriber: S) -> DefaultGuard -where - S: Subscriber + Send + Sync + 'static, -{ - crate::dispatcher::set_default(&crate::Dispatch::new(subscriber)) -} - -pub use tracing_core::dispatcher::SetGlobalDefaultError; diff --git a/tracing/test-log-support/tests/log_with_trace.rs b/tracing/test-log-support/tests/log_with_trace.rs index d2d5b2cf81..19c9e5ae2a 100644 --- a/tracing/test-log-support/tests/log_with_trace.rs +++ b/tracing/test-log-support/tests/log_with_trace.rs @@ -5,9 +5,9 @@ extern crate test_log_support; use test_log_support::Test; use tracing::Level; -pub struct NopSubscriber; +pub struct NopCollector; -impl tracing::Subscriber for NopSubscriber { +impl tracing::Collect for NopCollector { fn enabled(&self, _: &tracing::Metadata) -> bool { true } @@ -29,7 +29,7 @@ impl tracing::Subscriber for NopSubscriber { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn log_with_trace() { - tracing::subscriber::set_global_default(NopSubscriber).expect("set global should succeed"); + tracing::collect::set_global_default(NopCollector).expect("set global should succeed"); let test = Test::start(); diff --git a/tracing/test_static_max_level_features/tests/test.rs b/tracing/test_static_max_level_features/tests/test.rs index 419dd28ef0..ba923932bb 100644 --- a/tracing/test_static_max_level_features/tests/test.rs +++ b/tracing/test_static_max_level_features/tests/test.rs @@ -3,15 +3,15 @@ extern crate tracing; use std::sync::{Arc, Mutex}; use tracing::span::{Attributes, Record}; -use tracing::{span, Event, Id, Level, Metadata, Subscriber}; +use tracing::{span, Collect, Event, Id, Level, Metadata}; struct State { last_level: Mutex>, } -struct TestSubscriber(Arc); +struct TestCollector(Arc); -impl Subscriber for TestSubscriber { +impl Collect for TestCollector { fn enabled(&self, _: &Metadata) -> bool { true } @@ -40,7 +40,7 @@ fn test_static_max_level_features() { last_level: Mutex::new(None), }); let a = me.clone(); - tracing::subscriber::with_default(TestSubscriber(me), || { + tracing::collect::with_default(TestCollector(me), || { error!(""); last(&a, Some(Level::ERROR)); warn!(""); diff --git a/tracing/tests/subscriber.rs b/tracing/tests/collector.rs similarity index 92% rename from tracing/tests/subscriber.rs rename to tracing/tests/collector.rs index 2a810c9111..a7a7629192 100644 --- a/tracing/tests/subscriber.rs +++ b/tracing/tests/collector.rs @@ -9,9 +9,8 @@ #[macro_use] extern crate tracing; use tracing::{ - span, - subscriber::{with_default, Interest, Subscriber}, - Event, Level, Metadata, + collect::{with_default, Collect, Interest}, + span, Event, Level, Metadata, }; #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] @@ -20,7 +19,7 @@ fn event_macros_dont_infinite_loop() { // This test ensures that an event macro within a subscriber // won't cause an infinite loop of events. struct TestSubscriber; - impl Subscriber for TestSubscriber { + impl Collect for TestSubscriber { fn register_callsite(&self, _: &Metadata<'_>) -> Interest { // Always return sometimes so that `enabled` will be called // (which can loop). diff --git a/tracing/tests/event.rs b/tracing/tests/event.rs index d61ef748b8..7933ed3b99 100644 --- a/tracing/tests/event.rs +++ b/tracing/tests/event.rs @@ -13,8 +13,8 @@ mod support; use self::support::*; use tracing::{ + collect::with_default, field::{debug, display}, - subscriber::with_default, Level, }; @@ -23,7 +23,7 @@ macro_rules! event_without_message { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn $name() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("answer") @@ -38,7 +38,7 @@ macro_rules! event_without_message { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { info!( answer = $e, to_question = "life, the universe, and everything" @@ -59,14 +59,14 @@ event_without_message! {nonzeroi32_event_without_message: std::num::NonZeroI32:: #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn event_with_message() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event(event::mock().with_fields(field::mock("message").with_value( &tracing::field::debug(format_args!("hello from my event! yak shaved = {:?}", true)), ))) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { debug!("hello from my event! yak shaved = {:?}", true); }); @@ -76,7 +76,7 @@ fn event_with_message() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn message_without_delims() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("answer") @@ -94,7 +94,7 @@ fn message_without_delims() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let question = "life, the universe, and everything"; debug!(answer = 42, question, "hello from {where}! tricky? {:?}!", true, where = "my event"); }); @@ -105,7 +105,7 @@ fn message_without_delims() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn string_message_without_delims() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("answer") @@ -122,7 +122,7 @@ fn string_message_without_delims() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let question = "life, the universe, and everything"; debug!(answer = 42, question, "hello from my event"); }); @@ -133,7 +133,7 @@ fn string_message_without_delims() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn one_with_everything() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock() .with_fields( @@ -153,7 +153,7 @@ fn one_with_everything() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { event!( target: "whatever", Level::ERROR, @@ -168,7 +168,7 @@ fn one_with_everything() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn moved_field() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("foo") @@ -178,7 +178,7 @@ fn moved_field() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let from = "my event"; event!(Level::INFO, foo = display(format!("hello from {}", from))) }); @@ -189,7 +189,7 @@ fn moved_field() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn dotted_field_name() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("foo.bar") @@ -200,7 +200,7 @@ fn dotted_field_name() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { event!(Level::INFO, foo.bar = true, foo.baz = false); }); @@ -210,7 +210,7 @@ fn dotted_field_name() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn borrowed_field() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("foo") @@ -220,7 +220,7 @@ fn borrowed_field() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let from = "my event"; let mut message = format!("hello from {}", from); event!(Level::INFO, foo = display(&message)); @@ -247,7 +247,7 @@ fn move_field_out_of_struct() { x: 3.234, y: -1.223, }; - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("x") @@ -260,7 +260,7 @@ fn move_field_out_of_struct() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let pos = Position { x: 3.234, y: -1.223, @@ -274,7 +274,7 @@ fn move_field_out_of_struct() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn display_shorthand() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("my_field") @@ -284,7 +284,7 @@ fn display_shorthand() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { event!(Level::TRACE, my_field = %"hello world"); }); @@ -294,7 +294,7 @@ fn display_shorthand() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn debug_shorthand() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("my_field") @@ -304,7 +304,7 @@ fn debug_shorthand() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { event!(Level::TRACE, my_field = ?"hello world"); }); @@ -314,7 +314,7 @@ fn debug_shorthand() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn both_shorthands() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event( event::mock().with_fields( field::mock("display_field") @@ -325,7 +325,7 @@ fn both_shorthands() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { event!(Level::TRACE, display_field = %"hello world", debug_field = ?"hello world"); }); @@ -335,13 +335,13 @@ fn both_shorthands() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn explicit_child() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo")) .event(event::mock().with_explicit_parent(Some("foo"))) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = span!(Level::TRACE, "foo"); event!(parent: foo.id(), Level::TRACE, "bar"); }); @@ -352,7 +352,7 @@ fn explicit_child() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn explicit_child_at_levels() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo")) .event(event::mock().with_explicit_parent(Some("foo"))) .event(event::mock().with_explicit_parent(Some("foo"))) @@ -362,7 +362,7 @@ fn explicit_child_at_levels() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = span!(Level::TRACE, "foo"); trace!(parent: foo.id(), "a"); debug!(parent: foo.id(), "b"); diff --git a/tracing/tests/filter_caching_is_lexically_scoped.rs b/tracing/tests/filter_caching_is_lexically_scoped.rs index 1e4bc6ef33..13fbcfd50c 100644 --- a/tracing/tests/filter_caching_is_lexically_scoped.rs +++ b/tracing/tests/filter_caching_is_lexically_scoped.rs @@ -37,8 +37,8 @@ fn filter_caching_is_lexically_scoped() { let count = Arc::new(AtomicUsize::new(0)); let count2 = count.clone(); - let subscriber = subscriber::mock() - .with_filter(move |meta| match meta.name().as_ref() { + let subscriber = collector::mock() + .with_filter(move |meta| match meta.name() { "emily" | "frank" => { count2.fetch_add(1, Ordering::Relaxed); true @@ -49,7 +49,7 @@ fn filter_caching_is_lexically_scoped() { // Since this test is in its own file anyway, we can do this. Thus, this // test will work even with no-std. - tracing::subscriber::set_global_default(subscriber).unwrap(); + tracing::collect::set_global_default(subscriber).unwrap(); // Call the function once. The filter should be re-evaluated. assert!(my_great_function()); diff --git a/tracing/tests/filters_are_not_reevaluated_for_the_same_span.rs b/tracing/tests/filters_are_not_reevaluated_for_the_same_span.rs index 722eed659f..aea946ea1b 100644 --- a/tracing/tests/filters_are_not_reevaluated_for_the_same_span.rs +++ b/tracing/tests/filters_are_not_reevaluated_for_the_same_span.rs @@ -27,14 +27,14 @@ use std::sync::{ #[test] fn filters_are_not_reevaluated_for_the_same_span() { // Asserts that the `span!` macro caches the result of calling - // `Subscriber::enabled` for each span. + // `Collector::enabled` for each span. let alice_count = Arc::new(AtomicUsize::new(0)); let bob_count = Arc::new(AtomicUsize::new(0)); let alice_count2 = alice_count.clone(); let bob_count2 = bob_count.clone(); - let (subscriber, handle) = subscriber::mock() - .with_filter(move |meta| match meta.name().as_ref() { + let (collector, handle) = collector::mock() + .with_filter(move |meta| match meta.name() { "alice" => { alice_count2.fetch_add(1, Ordering::Relaxed); false @@ -49,7 +49,7 @@ fn filters_are_not_reevaluated_for_the_same_span() { // Since this test is in its own file anyway, we can do this. Thus, this // test will work even with no-std. - tracing::subscriber::set_global_default(subscriber).unwrap(); + tracing::collect::set_global_default(collector).unwrap(); // Enter "alice" and then "bob". The dispatcher expects to see "bob" but // not "alice." diff --git a/tracing/tests/filters_are_reevaluated_for_different_call_sites.rs b/tracing/tests/filters_are_reevaluated_for_different_call_sites.rs index 9166bd252e..4495ef5a87 100644 --- a/tracing/tests/filters_are_reevaluated_for_different_call_sites.rs +++ b/tracing/tests/filters_are_reevaluated_for_different_call_sites.rs @@ -27,13 +27,13 @@ use std::sync::{ #[test] fn filters_are_reevaluated_for_different_call_sites() { // Asserts that the `span!` macro caches the result of calling - // `Subscriber::enabled` for each span. + // `Collector::enabled` for each span. let charlie_count = Arc::new(AtomicUsize::new(0)); let dave_count = Arc::new(AtomicUsize::new(0)); let charlie_count2 = charlie_count.clone(); let dave_count2 = dave_count.clone(); - let subscriber = subscriber::mock() + let subscriber = collector::mock() .with_filter(move |meta| { println!("Filter: {:?}", meta.name()); match meta.name().as_ref() { @@ -52,7 +52,7 @@ fn filters_are_reevaluated_for_different_call_sites() { // Since this test is in its own file anyway, we can do this. Thus, this // test will work even with no-std. - tracing::subscriber::set_global_default(subscriber).unwrap(); + tracing::collect::set_global_default(subscriber).unwrap(); // Enter "charlie" and then "dave". The dispatcher expects to see "dave" but // not "charlie." diff --git a/tracing/tests/filters_dont_leak.rs b/tracing/tests/filters_dont_leak.rs index 666335a8a4..8587dd1cf0 100644 --- a/tracing/tests/filters_dont_leak.rs +++ b/tracing/tests/filters_dont_leak.rs @@ -11,18 +11,18 @@ fn spans_dont_leak() { let _e = span.enter(); } - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .named("spans/subscriber1") .with_filter(|_| false) .done() .run_with_handle(); - let _guard = tracing::subscriber::set_default(subscriber); + let _guard = tracing::collect::set_default(collector); do_span(); let alice = span::mock().named("alice"); - let (subscriber2, handle2) = subscriber::mock() + let (subscriber2, handle2) = collector::mock() .named("spans/subscriber2") .with_filter(|_| true) .new_span(alice.clone()) @@ -32,7 +32,7 @@ fn spans_dont_leak() { .done() .run_with_handle(); - tracing::subscriber::with_default(subscriber2, || { + tracing::collect::with_default(subscriber2, || { println!("--- subscriber 2 is default ---"); do_span() }); @@ -51,29 +51,29 @@ fn events_dont_leak() { tracing::debug!("alice"); } - let (subscriber, handle) = subscriber::mock() - .named("events/subscriber1") + let (collector, handle) = collector::mock() + .named("events/collector1") .with_filter(|_| false) .done() .run_with_handle(); - let _guard = tracing::subscriber::set_default(subscriber); + let _guard = tracing::collect::set_default(collector); do_event(); - let (subscriber2, handle2) = subscriber::mock() - .named("events/subscriber2") + let (collector2, handle2) = collector::mock() + .named("events/collector2") .with_filter(|_| true) .event(event::mock()) .done() .run_with_handle(); - tracing::subscriber::with_default(subscriber2, || { - println!("--- subscriber 2 is default ---"); + tracing::collect::with_default(collector2, || { + println!("--- collector 2 is default ---"); do_event() }); - println!("--- subscriber 1 is default ---"); + println!("--- collector 1 is default ---"); do_event(); diff --git a/tracing/tests/max_level_hint.rs b/tracing/tests/max_level_hint.rs index f49ff950ef..d2e51adee7 100644 --- a/tracing/tests/max_level_hint.rs +++ b/tracing/tests/max_level_hint.rs @@ -12,12 +12,12 @@ use tracing::Level; fn max_level_hints() { // This test asserts that when a subscriber provides us with the global // maximum level that it will enable (by implementing the - // `Subscriber::max_level_hint` method), we will never call - // `Subscriber::enabled` for events above that maximum level. + // `Collector::max_level_hint` method), we will never call + // `Collector::enabled` for events above that maximum level. // // In this case, we test that by making the `enabled` method assert that no // `Metadata` for spans or events at the `TRACE` or `DEBUG` levels. - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .with_max_level_hint(Level::INFO) .with_filter(|meta| { assert!( @@ -32,7 +32,7 @@ fn max_level_hints() { .done() .run_with_handle(); - tracing::subscriber::set_global_default(subscriber).unwrap(); + tracing::collect::set_global_default(collector).unwrap(); tracing::info!("doing a thing that you might care about"); tracing::debug!("charging turboencabulator with interocitor"); diff --git a/tracing/tests/multiple_max_level_hints.rs b/tracing/tests/multiple_max_level_hints.rs index b2be6351cf..df04d89ab3 100644 --- a/tracing/tests/multiple_max_level_hints.rs +++ b/tracing/tests/multiple_max_level_hints.rs @@ -9,7 +9,7 @@ use tracing::Level; fn multiple_max_level_hints() { // This test ensures that when multiple subscribers are active, their max // level hints are handled correctly. The global max level should be the - // maximum of the level filters returned by the two `Subscriber`'s + // maximum of the level filters returned by the two `Collector`'s // `max_level_hint` method. // // In this test, we create a subscriber whose max level is `INFO`, and @@ -25,7 +25,7 @@ fn multiple_max_level_hints() { tracing::error!("everything is on fire"); } - let (subscriber1, handle1) = subscriber::mock() + let (subscriber1, handle1) = collector::mock() .named("subscriber1") .with_max_level_hint(Level::INFO) .with_filter(|meta| { @@ -41,7 +41,7 @@ fn multiple_max_level_hints() { .event(event::mock().at_level(Level::ERROR)) .done() .run_with_handle(); - let (subscriber2, handle2) = subscriber::mock() + let (subscriber2, handle2) = collector::mock() .named("subscriber2") .with_max_level_hint(Level::DEBUG) .with_filter(|meta| { @@ -61,10 +61,10 @@ fn multiple_max_level_hints() { let dispatch1 = tracing::Dispatch::new(subscriber1); - tracing::dispatcher::with_default(&dispatch1, do_events); + tracing::dispatch::with_default(&dispatch1, do_events); handle1.assert_finished(); let dispatch2 = tracing::Dispatch::new(subscriber2); - tracing::dispatcher::with_default(&dispatch2, do_events); + tracing::dispatch::with_default(&dispatch2, do_events); handle2.assert_finished(); } diff --git a/tracing/tests/span.rs b/tracing/tests/span.rs index 79914950c2..3443342868 100644 --- a/tracing/tests/span.rs +++ b/tracing/tests/span.rs @@ -10,19 +10,19 @@ mod support; use self::support::*; use std::thread; use tracing::{ + collect::with_default, field::{debug, display}, - subscriber::with_default, Level, Span, }; #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn handles_to_the_same_span_are_equal() { - // Create a mock subscriber that will return `true` on calls to - // `Subscriber::enabled`, so that the spans will be constructed. We - // won't enter any spans in this test, so the subscriber won't actually + // Create a mock collector that will return `true` on calls to + // `Collector::enabled`, so that the spans will be constructed. We + // won't enter any spans in this test, so the collector won't actually // expect to see any spans. - with_default(subscriber::mock().run(), || { + with_default(collector::mock().run(), || { let foo1 = span!(Level::TRACE, "foo"); let foo2 = foo1.clone(); // Two handles that point to the same span are equal. @@ -33,7 +33,7 @@ fn handles_to_the_same_span_are_equal() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn handles_to_different_spans_are_not_equal() { - with_default(subscriber::mock().run(), || { + with_default(collector::mock().run(), || { // Even though these spans have the same name and fields, they will have // differing metadata, since they were created on different lines. let foo1 = span!(Level::TRACE, "foo", bar = 1u64, baz = false); @@ -52,7 +52,7 @@ fn handles_to_different_spans_with_the_same_metadata_are_not_equal() { span!(Level::TRACE, "foo", bar = 1u64, baz = false) } - with_default(subscriber::mock().run(), || { + with_default(collector::mock().run(), || { let foo1 = make_span(); let foo2 = make_span(); @@ -64,7 +64,7 @@ fn handles_to_different_spans_with_the_same_metadata_are_not_equal() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn spans_always_go_to_the_subscriber_that_tagged_them() { - let subscriber1 = subscriber::mock() + let collector1 = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -72,16 +72,16 @@ fn spans_always_go_to_the_subscriber_that_tagged_them() { .drop_span(span::mock().named("foo")) .done() .run(); - let subscriber2 = subscriber::mock().run(); + let collector2 = collector::mock().run(); - let foo = with_default(subscriber1, || { + let foo = with_default(collector1, || { let foo = span!(Level::TRACE, "foo"); foo.in_scope(|| {}); foo }); // Even though we enter subscriber 2's context, the subscriber that // tagged the span should see the enter/exit. - with_default(subscriber2, move || foo.in_scope(|| {})); + with_default(collector2, move || foo.in_scope(|| {})); } // This gets exempt from testing in wasm because of: `thread::spawn` which is @@ -91,7 +91,7 @@ fn spans_always_go_to_the_subscriber_that_tagged_them() { // But for now since it's not possible we don't need to test for it :) #[test] fn spans_always_go_to_the_subscriber_that_tagged_them_even_across_threads() { - let subscriber1 = subscriber::mock() + let collector1 = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .enter(span::mock().named("foo")) @@ -99,7 +99,7 @@ fn spans_always_go_to_the_subscriber_that_tagged_them_even_across_threads() { .drop_span(span::mock().named("foo")) .done() .run(); - let foo = with_default(subscriber1, || { + let foo = with_default(collector1, || { let foo = span!(Level::TRACE, "foo"); foo.in_scope(|| {}); foo @@ -108,7 +108,7 @@ fn spans_always_go_to_the_subscriber_that_tagged_them_even_across_threads() { // Even though we enter subscriber 2's context, the subscriber that // tagged the span should see the enter/exit. thread::spawn(move || { - with_default(subscriber::mock().run(), || { + with_default(collector::mock().run(), || { foo.in_scope(|| {}); }) }) @@ -119,13 +119,13 @@ fn spans_always_go_to_the_subscriber_that_tagged_them_even_across_threads() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn dropping_a_span_calls_drop_span() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let span = span!(Level::TRACE, "foo"); span.in_scope(|| {}); drop(span); @@ -137,14 +137,14 @@ fn dropping_a_span_calls_drop_span() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn span_closes_after_event() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .event(event::mock()) .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "foo").in_scope(|| { event!(Level::DEBUG, {}, "my event!"); }); @@ -156,7 +156,7 @@ fn span_closes_after_event() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn new_span_after_event() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .event(event::mock()) .exit(span::mock().named("foo")) @@ -166,7 +166,7 @@ fn new_span_after_event() { .drop_span(span::mock().named("bar")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "foo").in_scope(|| { event!(Level::DEBUG, {}, "my event!"); }); @@ -179,14 +179,14 @@ fn new_span_after_event() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn event_outside_of_span() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .event(event::mock()) .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { debug!("my event!"); span!(Level::TRACE, "foo").in_scope(|| {}); }); @@ -197,10 +197,10 @@ fn event_outside_of_span() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn cloning_a_span_calls_clone_span() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .clone_span(span::mock().named("foo")) .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let span = span!(Level::TRACE, "foo"); // Allow the "redundant" `.clone` since it is used to call into the `.clone_span` hook. #[allow(clippy::redundant_clone)] @@ -213,12 +213,12 @@ fn cloning_a_span_calls_clone_span() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn drop_span_when_exiting_dispatchers_context() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .clone_span(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let span = span!(Level::TRACE, "foo"); let _span2 = span.clone(); drop(span); @@ -230,7 +230,7 @@ fn drop_span_when_exiting_dispatchers_context() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn clone_and_drop_span_always_go_to_the_subscriber_that_tagged_the_span() { - let (subscriber1, handle1) = subscriber::mock() + let (subscriber1, handle1) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .clone_span(span::mock().named("foo")) @@ -239,7 +239,7 @@ fn clone_and_drop_span_always_go_to_the_subscriber_that_tagged_the_span() { .drop_span(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .run_with_handle(); - let subscriber2 = subscriber::mock().done().run(); + let subscriber2 = collector::mock().done().run(); let foo = with_default(subscriber1, || { let foo = span!(Level::TRACE, "foo"); @@ -261,13 +261,13 @@ fn clone_and_drop_span_always_go_to_the_subscriber_that_tagged_the_span() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn span_closes_when_exited() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = span!(Level::TRACE, "foo"); foo.in_scope(|| {}); @@ -281,14 +281,14 @@ fn span_closes_when_exited() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn enter() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .enter(span::mock().named("foo")) .event(event::mock()) .exit(span::mock().named("foo")) .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = span!(Level::TRACE, "foo"); let _enter = foo.enter(); debug!("dropping guard..."); @@ -300,7 +300,7 @@ fn enter() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn moved_field() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("foo").with_field( field::mock("bar") @@ -313,7 +313,7 @@ fn moved_field() { .drop_span(span::mock().named("foo")) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let from = "my span"; let span = span!( Level::TRACE, @@ -329,7 +329,7 @@ fn moved_field() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn dotted_field_name() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock() .named("foo") @@ -337,7 +337,7 @@ fn dotted_field_name() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "foo", fields.bar = true); }); @@ -347,7 +347,7 @@ fn dotted_field_name() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn borrowed_field() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("foo").with_field( field::mock("bar") @@ -361,7 +361,7 @@ fn borrowed_field() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let from = "my span"; let mut message = format!("hello from {}", from); let span = span!(Level::TRACE, "foo", bar = display(&message)); @@ -390,7 +390,7 @@ fn move_field_out_of_struct() { x: 3.234, y: -1.223, }; - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("foo").with_field( field::mock("x") @@ -406,7 +406,7 @@ fn move_field_out_of_struct() { ) .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let pos = Position { x: 3.234, y: -1.223, @@ -426,7 +426,7 @@ fn move_field_out_of_struct() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn add_field_after_new_span() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = subscriber::mock() .new_span( span::mock() .named("foo") @@ -455,7 +455,7 @@ fn add_field_after_new_span() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn add_fields_only_after_new_span() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = subscriber::mock() .new_span(span::mock().named("foo")) .record( span::mock().named("foo"), @@ -485,7 +485,7 @@ fn add_fields_only_after_new_span() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn record_new_value_for_field() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("foo").with_field( field::mock("bar") @@ -504,7 +504,7 @@ fn record_new_value_for_field() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let span = span!(Level::TRACE, "foo", bar = 5, baz = false); span.record("baz", &true); span.in_scope(|| {}) @@ -516,7 +516,7 @@ fn record_new_value_for_field() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn record_new_values_for_fields() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("foo").with_field( field::mock("bar") @@ -539,7 +539,7 @@ fn record_new_values_for_fields() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let span = span!(Level::TRACE, "foo", bar = 4, baz = false); span.record("bar", &5); span.record("baz", &true); @@ -552,7 +552,7 @@ fn record_new_values_for_fields() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn new_span_with_target_and_log_level() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock() .named("foo") @@ -562,7 +562,7 @@ fn new_span_with_target_and_log_level() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(target: "app_span", Level::DEBUG, "foo"); }); @@ -572,12 +572,12 @@ fn new_span_with_target_and_log_level() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn explicit_root_span_is_root() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo").with_explicit_parent(None)) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(parent: None, Level::TRACE, "foo"); }); @@ -587,7 +587,7 @@ fn explicit_root_span_is_root() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn explicit_root_span_is_root_regardless_of_ctx() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo")) .enter(span::mock().named("foo")) .new_span(span::mock().named("bar").with_explicit_parent(None)) @@ -595,7 +595,7 @@ fn explicit_root_span_is_root_regardless_of_ctx() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "foo").in_scope(|| { span!(parent: None, Level::TRACE, "bar"); }) @@ -607,13 +607,13 @@ fn explicit_root_span_is_root_regardless_of_ctx() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn explicit_child() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo")) .new_span(span::mock().named("bar").with_explicit_parent(Some("foo"))) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = span!(Level::TRACE, "foo"); span!(parent: foo.id(), Level::TRACE, "bar"); }); @@ -624,7 +624,7 @@ fn explicit_child() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn explicit_child_at_levels() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo")) .new_span(span::mock().named("a").with_explicit_parent(Some("foo"))) .new_span(span::mock().named("b").with_explicit_parent(Some("foo"))) @@ -634,7 +634,7 @@ fn explicit_child_at_levels() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = span!(Level::TRACE, "foo"); trace_span!(parent: foo.id(), "a"); debug_span!(parent: foo.id(), "b"); @@ -649,7 +649,7 @@ fn explicit_child_at_levels() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn explicit_child_regardless_of_ctx() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo")) .new_span(span::mock().named("bar")) .enter(span::mock().named("bar")) @@ -658,7 +658,7 @@ fn explicit_child_regardless_of_ctx() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { let foo = span!(Level::TRACE, "foo"); span!(Level::TRACE, "bar").in_scope(|| span!(parent: foo.id(), Level::TRACE, "baz")) }); @@ -669,12 +669,12 @@ fn explicit_child_regardless_of_ctx() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn contextual_root() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo").with_contextual_parent(None)) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "foo"); }); @@ -684,7 +684,7 @@ fn contextual_root() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn contextual_child() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span(span::mock().named("foo")) .enter(span::mock().named("foo")) .new_span( @@ -696,7 +696,7 @@ fn contextual_child() { .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "foo").in_scope(|| { span!(Level::TRACE, "bar"); }) @@ -708,7 +708,7 @@ fn contextual_child() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn display_shorthand() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("my_span").with_field( field::mock("my_field") @@ -718,7 +718,7 @@ fn display_shorthand() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "my_span", my_field = %"hello world"); }); @@ -728,7 +728,7 @@ fn display_shorthand() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn debug_shorthand() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("my_span").with_field( field::mock("my_field") @@ -738,7 +738,7 @@ fn debug_shorthand() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "my_span", my_field = ?"hello world"); }); @@ -748,7 +748,7 @@ fn debug_shorthand() { #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[test] fn both_shorthands() { - let (subscriber, handle) = subscriber::mock() + let (collector, handle) = collector::mock() .new_span( span::mock().named("my_span").with_field( field::mock("display_field") @@ -759,7 +759,7 @@ fn both_shorthands() { ) .done() .run_with_handle(); - with_default(subscriber, || { + with_default(collector, || { span!(Level::TRACE, "my_span", display_field = %"hello world", debug_field = ?"hello world"); }); diff --git a/tracing/tests/support/subscriber.rs b/tracing/tests/support/collector.rs similarity index 96% rename from tracing/tests/support/subscriber.rs rename to tracing/tests/support/collector.rs index 17527948c4..0f59a4fc9a 100644 --- a/tracing/tests/support/subscriber.rs +++ b/tracing/tests/support/collector.rs @@ -16,10 +16,10 @@ use std::{ thread, }; use tracing::{ + collect::Interest, level_filters::LevelFilter, span::{self, Attributes, Id}, - subscriber::Interest, - Event, Metadata, Subscriber, + Collect, Event, Metadata, }; #[derive(Debug, Eq, PartialEq)] @@ -49,7 +49,7 @@ struct Running) -> bool> { name: String, } -pub struct MockSubscriber) -> bool> { +pub struct MockCollector) -> bool> { expected: VecDeque, max_level: Option, filter: F, @@ -58,8 +58,8 @@ pub struct MockSubscriber) -> bool> { pub struct MockHandle(Arc>>, String); -pub fn mock() -> MockSubscriber) -> bool> { - MockSubscriber { +pub fn mock() -> MockCollector) -> bool> { + MockCollector { expected: VecDeque::new(), filter: (|_: &Metadata<'_>| true) as for<'r, 's> fn(&'r Metadata<'s>) -> _, max_level: None, @@ -70,7 +70,7 @@ pub fn mock() -> MockSubscriber) -> bool> { } } -impl MockSubscriber +impl MockCollector where F: Fn(&Metadata<'_>) -> bool + 'static, { @@ -141,11 +141,11 @@ where self } - pub fn with_filter(self, filter: G) -> MockSubscriber + pub fn with_filter(self, filter: G) -> MockCollector where G: Fn(&Metadata<'_>) -> bool + 'static, { - MockSubscriber { + MockCollector { expected: self.expected, filter, max_level: self.max_level, @@ -160,15 +160,15 @@ where } } - pub fn run(self) -> impl Subscriber { - let (subscriber, _) = self.run_with_handle(); - subscriber + pub fn run(self) -> impl Collect { + let (collector, _) = self.run_with_handle(); + collector } - pub fn run_with_handle(self) -> (impl Subscriber, MockHandle) { + pub fn run_with_handle(self) -> (impl Collect, MockHandle) { let expected = Arc::new(Mutex::new(self.expected)); let handle = MockHandle(expected.clone(), self.name.clone()); - let subscriber = Running { + let collector = Running { spans: Mutex::new(HashMap::new()), expected, current: Mutex::new(Vec::new()), @@ -177,11 +177,11 @@ where max_level: self.max_level, name: self.name, }; - (subscriber, handle) + (collector, handle) } } -impl Subscriber for Running +impl Collect for Running where F: Fn(&Metadata<'_>) -> bool + 'static, { diff --git a/tracing/tests/support/mod.rs b/tracing/tests/support/mod.rs index 7900f38c76..f0bf36a583 100644 --- a/tracing/tests/support/mod.rs +++ b/tracing/tests/support/mod.rs @@ -1,9 +1,9 @@ #![allow(dead_code)] +pub mod collector; pub mod event; pub mod field; mod metadata; pub mod span; -pub mod subscriber; #[derive(Debug, Eq, PartialEq)] pub(in crate::support) enum Parent {