Skip to content

Commit

Permalink
subscriber: rename Filter to EnvFilter (#339)
Browse files Browse the repository at this point in the history
This branch renames `Filter` to `EnvFilter` and deprecates the previous
name, as suggested in #336 (review).
This should make the difference between an `EnvFilter` and a
`LevelFilter` clearer.
The `filter` feature has also been deprecated in favor of `env-filter`.

Co-Authored-By: Benjamin Saunders <ben.e.saunders@gmail.com>
Signed-off-by: Eliza Weisman <eliza@buoyant.io>
  • Loading branch information
hawkw and Ralith committed Sep 12, 2019
1 parent 5c0fe77 commit fec24bf
Show file tree
Hide file tree
Showing 19 changed files with 146 additions and 101 deletions.
2 changes: 1 addition & 1 deletion examples/examples/attrs-args.rs
Expand Up @@ -29,7 +29,7 @@ fn fibonacci_seq(to: u64) -> Vec<u64> {
fn main() {
use tracing_subscriber::fmt;
let subscriber = fmt::Subscriber::builder()
.with_filter("attrs_args=trace")
.with_env_filter("attrs_args=trace")
.finish();

tracing::subscriber::with_default(subscriber, || {
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/attrs-basic.rs
Expand Up @@ -12,7 +12,7 @@ fn suggest_band() -> String {

fn main() {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
.with_filter("attrs_basic=trace")
.with_env_filter("attrs_basic=trace")
.finish();
tracing::subscriber::with_default(subscriber, || {
let num_recs = 1;
Expand Down
4 changes: 2 additions & 2 deletions examples/examples/futures-proxy-server.rs
Expand Up @@ -17,10 +17,10 @@ use tokio::net::{TcpListener, TcpStream};
use tokio::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
use tracing_subscriber::{fmt, Filter};
use tracing_subscriber::{fmt, EnvFilter};

let subscriber = fmt::Subscriber::builder()
.with_filter(Filter::from_default_env())
.with_env_filter(EnvFilter::from_default_env())
.finish();
tracing::subscriber::set_global_default(subscriber)?;

Expand Down
4 changes: 2 additions & 2 deletions examples/examples/subscriber-filter.rs
Expand Up @@ -3,10 +3,10 @@
mod yak_shave;

fn main() {
use tracing_subscriber::{fmt, Filter};
use tracing_subscriber::{fmt, EnvFilter};

let subscriber = fmt::Subscriber::builder()
.with_filter(Filter::from_default_env())
.with_env_filter(EnvFilter::from_default_env())
.finish();

tracing::subscriber::with_default(subscriber, || {
Expand Down
6 changes: 3 additions & 3 deletions examples/examples/tower-h2-client.rs
Expand Up @@ -18,14 +18,14 @@ use tracing_tower::InstrumentableService;
pub struct Conn(SocketAddr);

fn main() {
use tracing_subscriber::filter::Filter;
use tracing_subscriber::filter::EnvFilter;
// Set the default subscriber to record all traces emitted by this example
// and by the `tracing_tower` library's helpers.
let filter = Filter::from_default_env()
let filter = EnvFilter::from_default_env()
.add_directive("tower_h2_client=trace".parse().unwrap())
.add_directive("tracing_tower=trace".parse().unwrap());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_filter(filter)
.with_env_filter(filter)
.finish();
let _ = tracing::subscriber::set_global_default(subscriber);

Expand Down
6 changes: 3 additions & 3 deletions examples/examples/tower-h2-server.rs
Expand Up @@ -95,12 +95,12 @@ impl tower_service::Service<()> for NewSvc {
fn main() {
// Set the default subscriber to record all traces emitted by this example
// and by the `tracing_tower` library's helpers.
use tracing_subscriber::filter::Filter;
let filter = Filter::from_default_env()
use tracing_subscriber::filter::EnvFilter;
let filter = EnvFilter::from_default_env()
.add_directive("tower_h2_server=trace".parse().unwrap())
.add_directive("tracing_tower=trace".parse().unwrap());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_filter(filter)
.with_env_filter(filter)
.finish();
let _ = tracing::subscriber::set_global_default(subscriber);

Expand Down
6 changes: 3 additions & 3 deletions examples/examples/tower-load.rs
Expand Up @@ -36,7 +36,7 @@ use tracing_subscriber::FmtSubscriber;

fn main() {
let builder = FmtSubscriber::builder()
.with_filter("info,tower_load=debug")
.with_env_filter("info,tower_load=debug")
.with_filter_reloading();
let handle = builder.reload_handle();

Expand Down Expand Up @@ -224,7 +224,7 @@ impl Service<()> for MakeSvc {
}

struct AdminSvc<S> {
handle: tracing_subscriber::reload::Handle<tracing_subscriber::filter::Filter, S>,
handle: tracing_subscriber::reload::Handle<tracing_subscriber::filter::EnvFilter, S>,
}

impl<S> Clone for AdminSvc<S> {
Expand Down Expand Up @@ -296,7 +296,7 @@ where
let body = str::from_utf8(&bytes.as_ref()).map_err(|e| format!("{}", e))?;
tracing::trace!(request.body = ?body);
let new_filter = body
.parse::<tracing_subscriber::filter::Filter>()
.parse::<tracing_subscriber::filter::EnvFilter>()
.map_err(|e| format!("{}", e))?;
self.handle.reload(new_filter).map_err(|e| format!("{}", e))
}
Expand Down
2 changes: 1 addition & 1 deletion nightly-examples/examples/async_fn.rs
Expand Up @@ -44,7 +44,7 @@ pub async fn main() -> Result<(), Box<dyn Error>> {
let addr = "127.0.0.1:6142".parse()?;

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

Expand Down
4 changes: 2 additions & 2 deletions nightly-examples/examples/echo.rs
Expand Up @@ -37,10 +37,10 @@ use tracing_futures::Instrument;

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

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

Expand Down
4 changes: 2 additions & 2 deletions nightly-examples/examples/proxy_server.rs
Expand Up @@ -86,10 +86,10 @@ async fn transfer(

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
use tracing_subscriber::{Filter, FmtSubscriber};
use tracing_subscriber::{EnvFilter, FmtSubscriber};

let subscriber = FmtSubscriber::builder()
.with_filter(Filter::from_default_env().add_directive("proxy_server=trace".parse()?))
.with_env_filter(EnvFilter::from_default_env().add_directive("proxy_server=trace".parse()?))
.finish();
tracing::subscriber::set_global_default(subscriber)?;

Expand Down
9 changes: 6 additions & 3 deletions tracing-subscriber/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "tracing-subscriber"
version = "0.1.1"
version = "0.1.2"
authors = ["Eliza Weisman <eliza@buoyant.io>", "Tokio Contributors <team@tokio.rs>"]
edition = "2018"
license = "MIT"
Expand All @@ -20,11 +20,14 @@ keywords = ["logging", "tracing", "metrics", "subscriber"]

[features]

default = ["filter", "smallvec", "fmt", "ansi", "chrono", "tracing-log"]
filter = ["matchers", "regex", "lazy_static"]
default = ["env-filter", "smallvec", "fmt", "ansi", "chrono", "tracing-log"]
env-filter = ["matchers", "regex", "lazy_static"]
fmt = ["owning_ref", "parking_lot"]
ansi = ["fmt", "ansi_term"]

# Alias for `env-filter`; renamed in version 0.1.2, and will be removed in 0.2.
filter = ["env-filter"]

[dependencies]
tracing-core = "0.1.2"
crossbeam-utils = "0.6"
Expand Down
67 changes: 37 additions & 30 deletions tracing-subscriber/src/filter/env/mod.rs
Expand Up @@ -29,8 +29,15 @@ use tracing_core::{
/// A `Layer` which filters spans and events based on a set of filter
/// directives.
// TODO(eliza): document filter directive syntax?
#[cfg_attr(
feature = "filter",
deprecated(
since = "0.1.2",
note = "the `filter` feature flag was renamed to `env-filter` and will be removed in 0.2",
)
)]
#[derive(Debug)]
pub struct Filter {
pub struct EnvFilter {
// TODO: eventually, this should be exposed by the registry.
scope: thread::Local<Vec<LevelFilter>>,

Expand All @@ -48,7 +55,7 @@ type FilterVec<T> = smallvec::SmallVec<[T; 8]>;
#[cfg(not(feature = "smallvec"))]
type FilterVec<T> = Vec<T>;

/// Indicates that an error occurred while parsing a `Filter` from an
/// Indicates that an error occurred while parsing a `EnvFilter` from an
/// environment variable.
#[derive(Debug)]
pub struct FromEnvError {
Expand All @@ -61,27 +68,27 @@ enum ErrorKind {
Env(env::VarError),
}

impl Filter {
/// The default environment variable used by [`Filter::from_default_env`]
/// and [`Filter::try_from_default_env`].
impl EnvFilter {
/// The default environment variable used by [`EnvFilter::from_default_env`]
/// and [`EnvFilter::try_from_default_env`].
///
/// [`Filter::from_default_env`]: #method.from_default_env
/// [`Filter::try_from_default_env`]: #method.try_from_default_env
/// [`EnvFilter::from_default_env`]: #method.from_default_env
/// [`EnvFilter::try_from_default_env`]: #method.try_from_default_env
pub const DEFAULT_ENV: &'static str = "RUST_LOG";

/// Returns a new `Filter` from the value of the `RUST_LOG` environment
/// Returns a new `EnvFilter` from the value of the `RUST_LOG` environment
/// variable, ignoring any invalid filter directives.
pub fn from_default_env() -> Self {
Self::from_env(Self::DEFAULT_ENV)
}

/// Returns a new `Filter` from the value of the given environment
/// Returns a new `EnvFilter` from the value of the given environment
/// variable, ignoring any invalid filter directives.
pub fn from_env<A: AsRef<str>>(env: A) -> Self {
env::var(env.as_ref()).map(Self::new).unwrap_or_default()
}

/// Returns a new `Filter` from the directives in the given string,
/// Returns a new `EnvFilter` from the directives in the given string,
/// ignoring any that are invalid.
pub fn new<S: AsRef<str>>(dirs: S) -> Self {
let directives = dirs.as_ref().split(',').filter_map(|s| match s.parse() {
Expand All @@ -94,7 +101,7 @@ impl Filter {
Self::from_directives(directives)
}

/// Returns a new `Filter` from the directives in the given string,
/// Returns a new `EnvFilter` from the directives in the given string,
/// or an error if any are invalid.
pub fn try_new<S: AsRef<str>>(dirs: S) -> Result<Self, ParseError> {
let directives = dirs
Expand All @@ -105,21 +112,21 @@ impl Filter {
Ok(Self::from_directives(directives))
}

/// Returns a new `Filter` from the value of the `RUST_LOG` environment
/// Returns a new `EnvFilter` from the value of the `RUST_LOG` environment
/// variable, or an error if the environment variable contains any invalid
/// filter directives.
pub fn try_from_default_env() -> Result<Self, FromEnvError> {
Self::try_from_env(Self::DEFAULT_ENV)
}

/// Returns a new `Filter` from the value of the given environment
/// Returns a new `EnvFilter` from the value of the given environment
/// variable, or an error if the environment variable is unset or contains
/// any invalid filter directives.
pub fn try_from_env<A: AsRef<str>>(env: A) -> Result<Self, FromEnvError> {
env::var(env.as_ref())?.parse().map_err(Into::into)
}

/// Add a filtering directive to this `Filter`.
/// Add a filtering directive to this `EnvFilter`.
///
/// The added directive will be used in addition to any previously set
/// directives, either added using this method or provided when the filter
Expand All @@ -137,17 +144,17 @@ impl Filter {
///
/// # Examples
/// ```rust
/// use tracing_subscriber::filter::{Filter, LevelFilter};
/// use tracing_subscriber::filter::{EnvFilter, LevelFilter};
/// # fn main() {
/// let mut filter = Filter::from_default_env()
/// let mut filter = EnvFilter::from_default_env()
/// .add_directive(LevelFilter::INFO.into());
/// # }
/// ```
/// ```rust
/// use tracing_subscriber::filter::{Filter, Directive};
/// use tracing_subscriber::filter::{EnvFilter, Directive};
///
/// # fn try_mk_filter() -> Result<(), Box<dyn ::std::error::Error>> {
/// let mut filter = Filter::try_from_default_env()?
/// let mut filter = EnvFilter::try_from_default_env()?
/// .add_directive("my_crate::module=trace".parse()?)
/// .add_directive("my_crate::my_other_module::something=info".parse()?);
/// # Ok(())
Expand Down Expand Up @@ -193,7 +200,7 @@ impl Filter {
}
}

impl<S: Subscriber> Layer<S> for Filter {
impl<S: Subscriber> Layer<S> for EnvFilter {
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
if metadata.is_span() {
// If this metadata describes a span, first, check if there is a
Expand Down Expand Up @@ -271,15 +278,15 @@ impl<S: Subscriber> Layer<S> for Filter {
}
}

impl FromStr for Filter {
impl FromStr for EnvFilter {
type Err = ParseError;

fn from_str(spec: &str) -> Result<Self, Self::Err> {
Self::try_new(spec)
}
}

impl<S> From<S> for Filter
impl<S> From<S> for EnvFilter
where
S: AsRef<str>,
{
Expand All @@ -288,13 +295,13 @@ where
}
}

impl Default for Filter {
impl Default for EnvFilter {
fn default() -> Self {
Self::from_directives(std::iter::empty())
}
}

impl fmt::Display for Filter {
impl fmt::Display for EnvFilter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut statics = self.statics.iter();
let wrote_statics = if let Some(next) = statics.next() {
Expand Down Expand Up @@ -401,7 +408,7 @@ mod tests {

#[test]
fn callsite_enabled_no_span_directive() {
let filter = Filter::new("app=debug").with_subscriber(NoSubscriber);
let filter = EnvFilter::new("app=debug").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Expand All @@ -419,7 +426,7 @@ mod tests {

#[test]
fn callsite_off() {
let filter = Filter::new("app=off").with_subscriber(NoSubscriber);
let filter = EnvFilter::new("app=off").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Expand All @@ -437,7 +444,7 @@ mod tests {

#[test]
fn callsite_enabled_includes_span_directive() {
let filter = Filter::new("app[mySpan]=debug").with_subscriber(NoSubscriber);
let filter = EnvFilter::new("app[mySpan]=debug").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Expand All @@ -456,7 +463,7 @@ mod tests {
#[test]
fn callsite_enabled_includes_span_directive_field() {
let filter =
Filter::new("app[mySpan{field=\"value\"}]=debug").with_subscriber(NoSubscriber);
EnvFilter::new("app[mySpan{field=\"value\"}]=debug").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Expand All @@ -474,7 +481,7 @@ mod tests {

#[test]
fn callsite_enabled_includes_span_directive_multiple_fields() {
let filter = Filter::new("app[mySpan{field=\"value\",field2=2}]=debug")
let filter = EnvFilter::new("app[mySpan{field=\"value\",field2=2}]=debug")
.with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
"mySpan",
Expand All @@ -493,11 +500,11 @@ mod tests {

#[test]
fn roundtrip() {
let f1: Filter =
let f1: EnvFilter =
"[span1{foo=1}]=error,[span2{bar=2 baz=false}],crate2[{quux=\"quuux\"}]=debug"
.parse()
.unwrap();
let f2: Filter = format!("{}", f1).parse().unwrap();
let f2: EnvFilter = format!("{}", f1).parse().unwrap();
assert_eq!(f1.statics, f2.statics);
assert_eq!(f1.dynamics, f2.dynamics);
}
Expand Down

0 comments on commit fec24bf

Please sign in to comment.