move EnvFilter into its own layer

`tracing` at the time of writing has a feature (?) in its Filter
implementation, so that filters like EnvFilter are consulted for status
of a span or event and whether it is marked as interesting for logging.
Combining a Filter with another layer through the `with_filter`
combinator produces a filtered layer that enables an event unless it is
statically determined that the event is uninteresting.
However, if the filter is dynamic, because of filtering on span names or
field values as an example, events are **always** enabled.
There is an `event_enabled` predicate on `EnvFilter` implementation but
it falls back to default and, thus, the dynamic filters are **unused**.

This patch re-enables span- and field-based filters.
This commit is contained in:
Xiangfei Ding
2025-10-12 18:29:46 +00:00
parent ff6dc928c5
commit 1e382a172f
+5 -4
View File
@@ -39,11 +39,11 @@
use tracing::dispatcher::SetGlobalDefaultError;
use tracing::{Event, Subscriber};
use tracing_subscriber::Registry;
use tracing_subscriber::filter::{Directive, EnvFilter, LevelFilter};
use tracing_subscriber::fmt::FmtContext;
use tracing_subscriber::fmt::format::{self, FormatEvent, FormatFields};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::{Layer, Registry};
/// The values of all the environment variables that matter for configuring a logger.
/// Errors are explicitly preserved so that we can share error handling.
@@ -155,18 +155,19 @@ pub fn init_logger_with_additional_layer<F, T>(
Err(_) => {} // no wraptree
}
let subscriber = build_subscriber().with(layer.with_filter(filter));
let subscriber = build_subscriber();
// NOTE: It is important to make sure that the filter is applied on the last layer
match cfg.backtrace {
Ok(backtrace_target) => {
let fmt_layer = tracing_subscriber::fmt::layer()
.with_writer(io::stderr)
.without_time()
.event_format(BacktraceFormatter { backtrace_target });
let subscriber = subscriber.with(fmt_layer);
let subscriber = subscriber.with(layer).with(fmt_layer).with(filter);
tracing::subscriber::set_global_default(subscriber)?;
}
Err(_) => {
tracing::subscriber::set_global_default(subscriber)?;
tracing::subscriber::set_global_default(subscriber.with(layer).with(filter))?;
}
};