Skip to content

Commit

Permalink
subscriber: use Targets as the default filter if env-filter is no…
Browse files Browse the repository at this point in the history
…t enabled(#1781)

The removal of `env-filter` from the default features in 0.3.0 has
caused a lot of developer frustration. This PR changes
`tracing_subscriber::fmt::init()` and `try_init` to fall back to adding
a `Targets` filter parsed from the `RUST_LOG` environment variable,
rather than a `LevelFilter` with the default max level.

This way, `RUST_LOG`-based filtering will still "just work" out of the
box with the default initialization functions, regardless of whether or
not `EnvFilter` is enabled.

Closes #1697

Co-authored-by: Eliza Weisman <[email protected]>
  • Loading branch information
ishitatsuyuki and hawkw authored Dec 29, 2021
1 parent f8be43b commit c60c530
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion tracing-subscriber/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ pub mod writer;
pub use fmt_layer::{FmtContext, FormattedFields, Layer};

use crate::layer::Layer as _;
use crate::util::SubscriberInitExt;
use crate::{
filter::LevelFilter,
layer,
Expand Down Expand Up @@ -1131,7 +1132,37 @@ pub fn try_init() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
#[cfg(feature = "env-filter")]
let builder = builder.with_env_filter(crate::EnvFilter::from_default_env());

builder.try_init()
// If `env-filter` is disabled, remove the default max level filter from the
// subscriber; it will be added to the `Targets` filter instead if no filter
// is set in `RUST_LOG`.
// Replacing the default `LevelFilter` with an `EnvFilter` would imply this,
// but we can't replace the builder's filter with a `Targets` filter yet.
#[cfg(not(feature = "env-filter"))]
let builder = builder.with_max_level(LevelFilter::TRACE);

let subscriber = builder.finish();
#[cfg(not(feature = "env-filter"))]
let subscriber = {
use crate::{filter::Targets, layer::SubscriberExt};
use std::{env, str::FromStr};
let targets = match env::var("RUST_LOG") {
Ok(var) => Targets::from_str(&var)
.map_err(|e| {
eprintln!("Ignoring `RUST_LOG={:?}`: {}", var, e);
})
.unwrap_or_default(),
Err(env::VarError::NotPresent) => {
Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL)
}
Err(e) => {
eprintln!("Ignoring `RUST_LOG`: {}", e);
Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL)
}
};
subscriber.with(targets)
};

subscriber.try_init().map_err(Into::into)
}

/// Install a global tracing subscriber that listens for events and
Expand Down

0 comments on commit c60c530

Please sign in to comment.