mirror of
https://github.com/tokio-rs/tokio.git
synced 2025-10-01 12:20:39 +00:00

## Motivation Currently, the primary way to use a span is to use `.enter` and pass a closure to be executed under the span. While that is convenient in many settings, it also comes with two decently inconvenient drawbacks: - It breaks control flow statements like `return`, `?`, `break`, and `continue` - It require re-indenting a potentially large chunk of code if you wish it to appear under a span ## Solution This branch changes the `Span::enter` function to return a scope guard that exits the span when dropped, as in: ```rust let guard = span.enter(); // code here is within the span drop(guard); // code here is no longer within the span ``` The method previously called `enter`, which takes a closure and executes it in the span's context, is now called `Span::in_scope`, and was reimplemented on top of the new `enter` method. This is a breaking change to `tokio-trace` that will be part of the upcoming 0.2 release. Closes #1075 Signed-off-by: Eliza Weisman <eliza@buoyant.io>
54 lines
2.0 KiB
Rust
54 lines
2.0 KiB
Rust
//! A simple example demonstrating how one might implement a custom
|
|
//! subscriber.
|
|
//!
|
|
//! This subscriber implements a tree-structured logger similar to
|
|
//! the "compact" formatter in [`slog-term`]. The demo mimicks the
|
|
//! example output in the screenshot in the [`slog` README].
|
|
//!
|
|
//! Note that this logger isn't ready for actual production use.
|
|
//! Several corners were cut to make the example simple.
|
|
//!
|
|
//! [`slog-term`]: https://docs.rs/slog-term/2.4.0/slog_term/
|
|
//! [`slog` README]: https://github.com/slog-rs/slog#terminal-output-example
|
|
#[macro_use]
|
|
extern crate tokio_trace;
|
|
|
|
use tokio_trace::{field, Level};
|
|
|
|
mod sloggish_subscriber;
|
|
use self::sloggish_subscriber::SloggishSubscriber;
|
|
|
|
fn main() {
|
|
let subscriber = SloggishSubscriber::new(2);
|
|
|
|
tokio_trace::subscriber::with_default(subscriber, || {
|
|
span!(Level::TRACE, "", version = &field::display(5.0)).in_scope(|| {
|
|
span!(Level::TRACE, "server", host = "localhost", port = 8080).in_scope(|| {
|
|
info!("starting");
|
|
info!("listening");
|
|
let peer1 = span!(Level::TRACE, "conn", peer_addr = "82.9.9.9", port = 42381);
|
|
peer1.in_scope(|| {
|
|
debug!("connected");
|
|
debug!({ length = 2 }, "message received");
|
|
});
|
|
let peer2 = span!(Level::TRACE, "conn", peer_addr = "8.8.8.8", port = 18230);
|
|
peer2.in_scope(|| {
|
|
debug!("connected");
|
|
});
|
|
peer1.in_scope(|| {
|
|
warn!({ algo = "xor" }, "weak encryption requested");
|
|
debug!({ length = 8 }, "response sent");
|
|
debug!("disconnected");
|
|
});
|
|
peer2.in_scope(|| {
|
|
debug!({ length = 5 }, "message received");
|
|
debug!({ length = 8 }, "response sent");
|
|
debug!("disconnected");
|
|
});
|
|
warn!("internal error");
|
|
info!("exit");
|
|
})
|
|
});
|
|
});
|
|
}
|