Skip to content

Commit

Permalink
feat: add Span::into_scope()
Browse files Browse the repository at this point in the history
A way to conveniently auto-drop a span after executing a closure.
  • Loading branch information
Byron committed Jun 17, 2023
1 parent 2b37e25 commit aa9dc8f
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 4 deletions.
5 changes: 3 additions & 2 deletions gix-trace/src/disabled.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
/// A workaround for a clippy warning
#[doc(hidden)]
pub struct Unit;
#[derive(Clone)]
pub struct Span;

/// A macro to create a span.
#[macro_export]
macro_rules! span {
(target: $target:expr, $lvl:expr, $name:expr, $($fields:tt)*) => {
$crate::Unit
$crate::Span
};
(target: $target:expr, $lvl:expr, $name:expr) => {
$crate::span!(target: $target, $lvl, $name,)
Expand Down
1 change: 1 addition & 0 deletions gix-trace/src/enabled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use tracing_core::{dispatcher::get_default as with_dispatcher, span::Id, Dispatc
pub use tracing_core::{field, metadata, Metadata};

/// An entered span which will exit on drop.
#[derive(Clone)]
pub struct Span {
id: Option<(Id, Dispatch)>,
}
Expand Down
9 changes: 8 additions & 1 deletion gix-trace/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,21 @@ mod enabled;
#[cfg(feature = "tracing")]
pub use enabled::Span;

impl Span {
/// Execute `f` in with this span active, consuming it.
pub fn into_scope<T>(self, f: impl FnOnce() -> T) -> T {
f()
}
}

#[cfg(feature = "tracing")]
#[doc(hidden)]
pub use enabled::{field, metadata, MetaOnlyCallsite, Metadata};

#[cfg(not(feature = "tracing"))]
mod disabled;
#[cfg(not(feature = "tracing"))]
pub use disabled::Unit;
pub use disabled::Span;

/// Create a new [coarse][Level::Coarse] span.
#[macro_export]
Expand Down
3 changes: 2 additions & 1 deletion gix-trace/tests/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use gix_trace::{coarse, detail, span};
#[test]
fn span() {
let _x = span!(gix_trace::Level::Coarse, "hello");
span!(gix_trace::Level::Coarse, "hello", x = "value", y = 42);
let fourty_two = span!(gix_trace::Level::Coarse, "hello", x = "value", y = 42).into_scope(|| 42);
assert_eq!(fourty_two, 42);
span!(target: "other", gix_trace::Level::Coarse, "hello", x = "value", y = 42);
}

Expand Down

0 comments on commit aa9dc8f

Please sign in to comment.