Skip to content

Commit c60c530

Browse files
ishitatsuyukihawkw
andauthored
subscriber: use Targets as the default filter if env-filter is not 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 <eliza@buoyant.io>
1 parent f8be43b commit c60c530

File tree

1 file changed

+32
-1
lines changed
  • tracing-subscriber/src/fmt

1 file changed

+32
-1
lines changed

tracing-subscriber/src/fmt/mod.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@ pub mod writer;
311311
pub use fmt_layer::{FmtContext, FormattedFields, Layer};
312312

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

1134-
builder.try_init()
1135+
// If `env-filter` is disabled, remove the default max level filter from the
1136+
// subscriber; it will be added to the `Targets` filter instead if no filter
1137+
// is set in `RUST_LOG`.
1138+
// Replacing the default `LevelFilter` with an `EnvFilter` would imply this,
1139+
// but we can't replace the builder's filter with a `Targets` filter yet.
1140+
#[cfg(not(feature = "env-filter"))]
1141+
let builder = builder.with_max_level(LevelFilter::TRACE);
1142+
1143+
let subscriber = builder.finish();
1144+
#[cfg(not(feature = "env-filter"))]
1145+
let subscriber = {
1146+
use crate::{filter::Targets, layer::SubscriberExt};
1147+
use std::{env, str::FromStr};
1148+
let targets = match env::var("RUST_LOG") {
1149+
Ok(var) => Targets::from_str(&var)
1150+
.map_err(|e| {
1151+
eprintln!("Ignoring `RUST_LOG={:?}`: {}", var, e);
1152+
})
1153+
.unwrap_or_default(),
1154+
Err(env::VarError::NotPresent) => {
1155+
Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL)
1156+
}
1157+
Err(e) => {
1158+
eprintln!("Ignoring `RUST_LOG`: {}", e);
1159+
Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL)
1160+
}
1161+
};
1162+
subscriber.with(targets)
1163+
};
1164+
1165+
subscriber.try_init().map_err(Into::into)
11351166
}
11361167

11371168
/// Install a global tracing subscriber that listens for events and

0 commit comments

Comments
 (0)