Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

subscriber: add more ergonomic subscriber configuration APIs #660

Merged
merged 14 commits into from
Apr 4, 2020
15 changes: 6 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,16 @@ The simplest way to use a subscriber is to call the `set_global_default` functio

```rust
use tracing::{info, Level};
use tracing_subscriber::FmtSubscriber;
use tracing_subscriber;

fn main() {
// a builder for `FmtSubscriber`.
let subscriber = FmtSubscriber::builder()
let subscriber = tracing_subscriber::fmt()
// all spans/events with a level higher than TRACE (e.g, debug, info, warn, etc.)
// will be written to stdout.
.with_max_level(Level::TRACE)
// completes the builder.
.finish();

tracing::subscriber::set_global_default(subscriber)
.expect("setting default subscriber failed");
// completes the builder and sets the constructed `Subscriber` as the default.
.init();

let number_of_yaks = 3;
// this creates a new event, outside of any spans.
Expand All @@ -88,10 +85,10 @@ In addition, you can locally override the default subscriber. For example:

```rust
use tracing::{info, Level};
use tracing_subscriber::FmtSubscriber;
use tracing_subscriber;

fn main() {
let subscriber = tracing_subscriber::FmtSubscriber::builder()
let subscriber = tracing_subscriber::fmt()
// all spans/events with a level higher than TRACE (e.g, debug, info, warn, etc.)
// will be written to stdout.
.with_max_level(Level::TRACE)
Expand Down
4 changes: 4 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ This directory contains a collection of examples that demonstrate the use of the
which provides a subscriber 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
fields on spans and events.
+ `fmt-custom-event`: Demonstrates overriding how the `fmt` subscriber formats
events.
+ `subscriber-filter`: Demonstrates the `tracing-subscriber::filter` module,
which provides a layer which adds configurable filtering to a subscriber
implementation.
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 @@ -2,7 +2,7 @@ use tracing::Level;
use tracing_subscriber;

fn main() {
tracing_subscriber::FmtSubscriber::builder()
tracing_subscriber::fmt()
// all spans/events with a level higher than TRACE (e.g, info, warn, etc.)
// will be written to stdout.
.with_max_level(Level::TRACE)
Expand Down
7 changes: 3 additions & 4 deletions examples/examples/async_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,12 @@ async fn write(stream: &mut TcpStream) -> io::Result<usize> {
}

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn Error>> {
pub async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let addr = "127.0.0.1:6142".parse()?;

let subscriber = tracing_subscriber::fmt::Subscriber::builder()
tracing_subscriber::fmt()
.with_env_filter("async_fn=trace")
.finish();
tracing::subscriber::set_global_default(subscriber).unwrap();
.try_init()?;

// Open a TCP stream to the socket address.
//
Expand Down
3 changes: 1 addition & 2 deletions examples/examples/attrs-args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ fn fibonacci_seq(to: u64) -> Vec<u64> {
}

fn main() {
use tracing_subscriber::fmt;
let subscriber = fmt::Subscriber::builder()
let subscriber = tracing_subscriber::fmt()
.with_env_filter("attrs_args=trace")
.finish();

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 @@ -11,7 +11,7 @@ fn suggest_band() -> String {
}

fn main() {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
let subscriber = tracing_subscriber::fmt()
.with_env_filter("attrs_basic=trace")
.finish();
tracing::subscriber::with_default(subscriber, || {
Expand Down
10 changes: 5 additions & 5 deletions examples/examples/custom_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::error::Error;
use std::fmt;
use tracing_error::{ErrorLayer, SpanTrace};
use tracing_subscriber::{fmt::Layer as FmtLayer, prelude::*, registry::Registry};
use tracing_subscriber::prelude::*;
#[derive(Debug)]
struct FooError {
message: &'static str,
Expand Down Expand Up @@ -50,11 +50,11 @@ fn do_another_thing(

#[tracing::instrument]
fn main() {
let subscriber = Registry::default()
.with(FmtLayer::default())
tracing_subscriber::registry()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wish there was a way to replace this expr with something like tracing_subscriber::fmt(), aka some sort of conversion fn for a fmt builder to a registry + layer

.with(tracing_subscriber::fmt::layer())
// The `ErrorLayer` subscriber layer enables the use of `SpanTrace`.
.with(ErrorLayer::default());
tracing::subscriber::set_global_default(subscriber).expect("Could not set global default");
.with(ErrorLayer::default())
.init();
match do_something("hello world") {
Ok(result) => println!("did something successfully: {}", result),
Err(e) => eprintln!("error: {}", e),
Expand Down
9 changes: 4 additions & 5 deletions examples/examples/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,12 @@ use tracing::{debug, info, info_span, trace_span, warn};
use tracing_futures::Instrument;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::{EnvFilter, FmtSubscriber};
async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
use tracing_subscriber::EnvFilter;

let subscriber = FmtSubscriber::builder()
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env().add_directive("echo=trace".parse()?))
.finish();
tracing::subscriber::set_global_default(subscriber)?;
.try_init()?;

// Allow passing an address to listen on as the first argument of this
// program, but otherwise we'll just set up our TCP listener on
Expand Down
29 changes: 29 additions & 0 deletions examples/examples/fmt-custom-event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#![deny(rust_2018_idioms)]
use tracing_subscriber;
#[path = "fmt/yak_shave.rs"]
mod yak_shave;

fn main() {
use tracing_subscriber::fmt;

// Configure a custom event formatter
let format = fmt::format()
.compact() // use an abbreviated format for logging spans
.with_level(false) // don't include levels in formatted output
.with_target(false); // don't include targets

// Create a `fmt` subscriber that uses our custom event format, and set it
// as the default.
tracing_subscriber::fmt().event_format(format).init();

// Shave some yaks!
let number_of_yaks = 3;
// this creates a new event, outside of any spans.
tracing::info!(number_of_yaks, "preparing to shave yaks");

let number_shaved = yak_shave::shave_all(number_of_yaks);
tracing::info!(
all_yaks_shaved = number_shaved == number_of_yaks,
"yak shaving completed."
);
}
53 changes: 53 additions & 0 deletions examples/examples/fmt-custom-field.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//! This example demonstrates overriding the way `tracing-subscriber`'s
//! `FmtSubscriber` formats fields on spans and events, using a closure.
//!
//! We'll create a custom format that prints key-value pairs separated by
//! colons rather than equals signs, and separates fields with commas.
//!
//! For an event like
//! ```rust
//! tracing::info!(hello = "world", answer = 42);
//! ```
//!
//! the default formatter will format the fields like this:
//! ```not_rust
//! hello="world" answer=42
//! ```
//! while our custom formatter will output
//! ```not_rust
//! hello: "world", answer: 42
//! ```
#![deny(rust_2018_idioms)]
use tracing_subscriber;

#[path = "fmt/yak_shave.rs"]
mod yak_shave;

fn main() {
use tracing_subscriber::{fmt::format, prelude::*};

// Format fields using the provided closure.
let format = format::debug_fn(|writer, field, value| {
// We'll format the field name and value separated with a colon.
write!(writer, "{}: {:?}", field, value)
})
// Separate each field with a comma.
// This method is provided by an extension trait in the
// `tracing-subscriber` prelude.
.delimited(", ");
hawkw marked this conversation as resolved.
Show resolved Hide resolved

// Create a `fmt` subscriber that uses our custom event format, and set it
// as the default.
tracing_subscriber::fmt().fmt_fields(format).init();

// Shave some yaks!
let number_of_yaks = 3;
// this creates a new event, outside of any spans.
tracing::info!(number_of_yaks, "preparing to shave yaks");

let number_shaved = yak_shave::shave_all(number_of_yaks);
tracing::info!(
all_yaks_shaved = number_shaved == number_of_yaks,
"yak shaving completed."
);
}
4 changes: 1 addition & 3 deletions examples/examples/fmt-stderr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ use std::io;
use tracing::error;

fn main() {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
.with_writer(io::stderr)
.finish();
let subscriber = tracing_subscriber::fmt().with_writer(io::stderr).finish();

tracing::subscriber::with_default(subscriber, || {
error!("This event will be printed to `stderr`.");
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tracing_subscriber;
mod yak_shave;

fn main() {
tracing_subscriber::fmt::Subscriber::builder()
tracing_subscriber::fmt()
// all spans/events with a level higher than DEBUG (e.g, info, warn, etc.)
// will be written to stdout.
.with_max_level(Level::DEBUG)
Expand Down
30 changes: 10 additions & 20 deletions examples/examples/futures-proxy-server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ use tracing::{debug, debug_span, info, warn};
use tracing_attributes::instrument;
use tracing_futures::Instrument;

type Error = Box<dyn std::error::Error + Send + Sync + 'static>;

#[instrument]
async fn transfer(
mut inbound: TcpStream,
proxy_addr: SocketAddr,
) -> Result<(), Box<dyn std::error::Error>> {
async fn transfer(mut inbound: TcpStream, proxy_addr: SocketAddr) -> Result<(), Error> {
let mut outbound = TcpStream::connect(&proxy_addr).await?;

let (mut ri, mut wi) = inbound.split();
Expand Down Expand Up @@ -82,7 +81,7 @@ arg_enum! {
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn main() -> Result<(), Error> {
let matches = App::new("Proxy Server Example")
.version("1.0")
.arg(
Expand Down Expand Up @@ -140,25 +139,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

fn set_global_default(matches: &ArgMatches<'_>) -> Result<(), Box<dyn std::error::Error>> {
use tracing_subscriber::{filter::EnvFilter, FmtSubscriber};
fn set_global_default(matches: &ArgMatches<'_>) -> Result<(), Error> {
let filter = tracing_subscriber::EnvFilter::from_default_env()
.add_directive("proxy_server=trace".parse()?);
let subscriber = tracing_subscriber::fmt().with_env_filter(filter);
match value_t!(matches, "log_format", LogFormat).unwrap_or(LogFormat::Plain) {
LogFormat::Json => {
let subscriber = FmtSubscriber::builder()
.json()
.with_env_filter(
EnvFilter::from_default_env().add_directive("proxy_server=trace".parse()?),
)
.finish();
tracing::subscriber::set_global_default(subscriber)?;
subscriber.json().try_init()?;
}
LogFormat::Plain => {
let subscriber = FmtSubscriber::builder()
.with_env_filter(
EnvFilter::from_default_env().add_directive("proxy_server=trace".parse()?),
)
.finish();
tracing::subscriber::set_global_default(subscriber)?;
subscriber.try_init()?;
}
}
Ok(())
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 @@ -95,7 +95,7 @@ async fn echo(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
async fn main() -> Result<(), Box<dyn std::error::Error>> {
use tracing_log::env_logger::BuilderExt;

let subscriber = tracing_subscriber::FmtSubscriber::builder()
let subscriber = tracing_subscriber::fmt()
.with_max_level(Level::TRACE)
.finish();
let mut builder = env_logger::Builder::new();
Expand Down
11 changes: 6 additions & 5 deletions examples/examples/instrumented_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::error::Error;
use std::fmt;
use tracing_error::{prelude::*, ErrorLayer};
use tracing_subscriber::{prelude::*, registry::Registry};
use tracing_subscriber::prelude::*;

#[derive(Debug)]
struct FooError {
Expand Down Expand Up @@ -43,11 +43,12 @@ fn do_another_thing(

#[tracing::instrument]
fn main() {
let subscriber = Registry::default()
.with(tracing_subscriber::fmt::Layer::default())
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer())
// The `ErrorLayer` subscriber layer enables the use of `SpanTrace`.
.with(ErrorLayer::default());
tracing::subscriber::set_global_default(subscriber).expect("Could not set global default");
.with(ErrorLayer::default())
.init();

match do_something("hello world") {
Ok(result) => println!("did something successfully: {}", result),
Err(e) => {
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/log.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
fn main() {
tracing_subscriber::fmt::Subscriber::builder()
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.init();

Expand Down
8 changes: 4 additions & 4 deletions examples/examples/spawny_thing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use tokio;

use futures::future::join_all;
use std::error::Error;
use tracing::{debug, info};
use tracing_attributes::instrument;

Expand Down Expand Up @@ -37,11 +38,10 @@ async fn subtask(number: usize) -> usize {
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.finish();
tracing::subscriber::set_global_default(subscriber)?;
.try_init()?;
parent_task(10).await;
Ok(())
}
5 changes: 2 additions & 3 deletions examples/examples/tower-client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,9 @@ fn req_span<A>(req: &Request<A>) -> tracing::Span {

#[tokio::main]
async fn main() -> Result<(), Err> {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
tracing_subscriber::fmt()
.with_env_filter("tower=trace")
.finish();
tracing::subscriber::set_global_default(subscriber)?;
.try_init()?;

let mut svc = ServiceBuilder::new()
.timeout(Duration::from_millis(250))
Expand Down
7 changes: 3 additions & 4 deletions examples/examples/tower-load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,18 @@ use tokio::{time, try_join};
use tower::{Service, ServiceBuilder, ServiceExt};
use tracing::{self, debug, error, info, span, trace, warn, Level, Span};
use tracing_futures::Instrument;
use tracing_subscriber::{filter::EnvFilter, reload::Handle, FmtSubscriber};
use tracing_subscriber::{filter::EnvFilter, reload::Handle};
use tracing_tower::{request_span, request_span::make};

type Err = Box<dyn Error + Send + Sync + 'static>;

#[tokio::main]
async fn main() -> Result<(), Err> {
let builder = FmtSubscriber::builder()
let builder = tracing_subscriber::fmt()
.with_env_filter("info,tower_load=debug")
.with_filter_reloading();
let handle = builder.reload_handle();

let _ = tracing::subscriber::set_global_default(builder.finish());
builder.try_init()?;

let addr = "[::1]:3000".parse::<SocketAddr>()?;
let admin_addr = "[::1]:3001".parse::<SocketAddr>()?;
Expand Down
Loading