Skip to content

Commit

Permalink
core: Implement Default trait for Dispatch (#411)
Browse files Browse the repository at this point in the history
## Motivation 

As outlined in #172, we can improve the use of default dispatch by
implementing `Default` to create `Dispatch::default`, thus making 
the default dispatcher easier to use.

## Solution 

This PR adds an implementation of `Default` trait from the standard
library that calls `get_default` and returns a clone of the default
dispatcher.

Closes #172

Signed-off-by: Adityo Pratomo <[email protected]>
  • Loading branch information
lunchboxav authored and hawkw committed Oct 31, 2019
1 parent e0132f8 commit 8720792
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions tracing-core/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,13 @@ impl Dispatch {
}
}

impl Default for Dispatch {
/// Returns the current default dispatcher
fn default() -> Self {
get_default(|default| default.clone())
}
}

impl fmt::Debug for Dispatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Dispatch(...)")
Expand Down Expand Up @@ -800,4 +807,42 @@ mod test {

with_default(&Dispatch::new(TestSubscriber), || mk_span())
}

#[test]
fn default_no_subscriber() {
let default_dispatcher = Dispatch::default();
assert!(default_dispatcher.is::<NoSubscriber>());
}

#[cfg(feature = "std")]
#[test]
fn default_dispatch() {
struct TestSubscriber;
impl Subscriber for TestSubscriber {
fn enabled(&self, _: &Metadata<'_>) -> bool {
true
}

fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {
span::Id::from_u64(0xAAAA)
}

fn record(&self, _: &span::Id, _: &span::Record<'_>) {}

fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}

fn event(&self, _: &Event<'_>) {}

fn enter(&self, _: &span::Id) {}

fn exit(&self, _: &span::Id) {}
}
let guard = set_default(&Dispatch::new(TestSubscriber));
let default_dispatcher = Dispatch::default();
assert!(default_dispatcher.is::<TestSubscriber>());

drop(guard);
let default_dispatcher = Dispatch::default();
assert!(default_dispatcher.is::<NoSubscriber>());
}
}

0 comments on commit 8720792

Please sign in to comment.