Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/master' into dp-always-pass-di…
Browse files Browse the repository at this point in the history
…spatch-as-owned-tokio-rs#455

* upstream/master:
  subscriber: update sharded-slab to 0.1, pool hashmap allocations (tokio-rs#1062)
  subscriber: remove deprecated type, structs, and methods tokio-rs#1030
  core: rename Subscriber to Collect (tokio-rs#1015)
  chore: fix rustdoc warning in tracing-subscriber (tokio-rs#1061)
  • Loading branch information
dvdplm committed Oct 23, 2020
2 parents bd22923 + 1bf9da2 commit 65a3c2b
Show file tree
Hide file tree
Showing 117 changed files with 2,528 additions and 2,221 deletions.
36 changes: 18 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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;
Expand All @@ -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.

Expand All @@ -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/
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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.
Expand Down
16 changes: 8 additions & 8 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/all-levels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
2 changes: 1 addition & 1 deletion examples/examples/attrs-args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/attrs-basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/attrs-literal-field-names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
27 changes: 13 additions & 14 deletions examples/examples/counters.rs
Original file line number Diff line number Diff line change
@@ -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::{
Expand All @@ -19,7 +18,7 @@ use std::{
#[derive(Clone)]
struct Counters(Arc<RwLock<HashMap<String, AtomicUsize>>>);

struct CounterSubscriber {
struct CounterCollector {
ids: AtomicUsize,
counters: Counters,
}
Expand Down Expand Up @@ -50,17 +49,17 @@ 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(),
}
}
}

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") {
Expand All @@ -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
Expand Down Expand Up @@ -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(|| {
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/custom-error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/fmt-stderr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.");
});
}
2 changes: 1 addition & 1 deletion examples/examples/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/hyper-echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.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);
Expand Down
6 changes: 3 additions & 3 deletions examples/examples/inferno-flame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/instrumented-error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
10 changes: 5 additions & 5 deletions examples/examples/journald.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions examples/examples/opentelemetry-remote-context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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());

Expand Down
Loading

0 comments on commit 65a3c2b

Please sign in to comment.