Skip to content

Commit

Permalink
refactor: unify level and target filter to env filter (#65)
Browse files Browse the repository at this point in the history
Signed-off-by: tison <[email protected]>
  • Loading branch information
tisonkun authored Oct 26, 2024
1 parent f8cfddd commit 2da9c7d
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 170 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@ jobs:
- name: Run examples
run: |
cargo run --example simple_stdio
cargo run --example fn_layout_filter
cargo run --example env_filter
cargo run --features="no-color" --example simple_stdio
cargo run --features="json" --example json_stdio
cargo run --features="json,rolling_file" --example rolling_file
cargo run --example fn_layout_filter
cargo run --features="env-filter" --example env_filter
required:
name: Required
Expand Down
18 changes: 6 additions & 12 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ all-features = true
rustdoc-args = ["--cfg", "docsrs"]

[features]
env-filter = ["dep:env_filter"]
fastrace = ["dep:fastrace"]
json = ["dep:serde_json", "dep:serde", "jiff/serde"]
no-color = ["colored/no-color"]
Expand All @@ -46,18 +45,14 @@ rolling_file = ["dep:crossbeam-channel", "dep:parking_lot"]
[dependencies]
anyhow = { version = "1.0" }
colored = { version = "2.1" }
jiff = { version = "0.1.10" }
env_filter = { version = "0.1" }
jiff = { version = "0.1.13" }
log = { version = "0.4", features = ["std", "kv_unstable"] }
paste = { version = "1.0" }

[dev-dependencies]
rand = "0.8"
tempfile = "3.12"

## Env filter dependencies
[dependencies.env_filter]
optional = true
version = "0.1"
tempfile = "3.13"

## Serde dependencies
[dependencies.serde]
Expand Down Expand Up @@ -87,17 +82,17 @@ version = "0.7"
[dependencies.opentelemetry]
features = ["logs"]
optional = true
version = "0.25"
version = "0.26"

[dependencies.opentelemetry-otlp]
features = ["logs", "grpc-tonic", "http-json", "http-proto"]
optional = true
version = "0.25"
version = "0.26"

[dependencies.opentelemetry_sdk]
features = ["logs", "rt-tokio"]
optional = true
version = "0.25"
version = "0.26"

## Examples
[[example]]
Expand All @@ -121,4 +116,3 @@ path = "examples/fn_layout_filter.rs"
[[example]]
name = "env_filter"
path = "examples/env_filter.rs"
required-features = ["env-filter"]
3 changes: 1 addition & 2 deletions examples/rolling_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use log::LevelFilter;
use logforth::append::rolling_file::NonBlockingBuilder;
use logforth::append::rolling_file::RollingFile;
use logforth::append::rolling_file::RollingFileWriter;
Expand All @@ -36,7 +35,7 @@ fn main() {
Logger::new()
.dispatch(
Dispatch::new()
.filter(LevelFilter::Trace)
.filter("trace")
.append(RollingFile::new(writer).with_layout(JsonLayout::default()))
.append(Stdout::default()),
)
Expand Down
42 changes: 35 additions & 7 deletions src/filter/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

use std::borrow::Cow;
use std::str::FromStr;

use log::LevelFilter;
use log::Metadata;
Expand All @@ -23,13 +24,25 @@ use crate::Filter;
/// The default name for the environment variable to read filters from.
pub const DEFAULT_FILTER_ENV: &str = "RUST_LOG";

/// A filter that respects the `RUST_LOG` environment variable.
/// A filter consists of one or more comma-separated directives which match on [`log::Record`].
///
/// Read more from [the `env_logger` documentation](https://docs.rs/env_logger/#enabling-logging).
/// Each directive may have a corresponding maximum verbosity [`level`][log::Level] which enables
/// records that match.
///
/// Less exclusive levels (like `trace` or `info`) are considered to be more verbose than more
/// exclusive levels (like `error` or `warn`).
///
/// The directive syntax is similar to that of [`env_logger`](https://crates.io/crates/env_logger)'s.
/// Read more from [the `env_logger` documentation](https://docs.rs/env_logger/#enabling-logging)
#[derive(Debug)]
pub struct EnvFilter(env_filter::Filter);

impl EnvFilter {
/// Initializes the filter builder from the [EnvFilterBuilder].
pub fn new(mut builder: EnvFilterBuilder) -> Self {
EnvFilter(builder.0.build())
}

/// Initializes the filter builder from the environment using default variable name `RUST_LOG`.
///
/// # Examples
Expand Down Expand Up @@ -115,11 +128,6 @@ impl EnvFilter {
}
}

/// Initializes the filter builder from the [EnvFilterBuilder].
pub fn new(mut builder: EnvFilterBuilder) -> Self {
EnvFilter(builder.0.build())
}

pub(crate) fn enabled(&self, metadata: &Metadata) -> FilterResult {
if self.0.enabled(metadata) {
FilterResult::Neutral
Expand All @@ -143,6 +151,26 @@ impl From<EnvFilter> for Filter {
}
}

impl From<LevelFilter> for EnvFilter {
fn from(filter: LevelFilter) -> Self {
EnvFilter::new(EnvFilterBuilder::new().filter_level(filter))
}
}

impl<'a> From<&'a str> for EnvFilter {
fn from(filter: &'a str) -> Self {
EnvFilter::new(EnvFilterBuilder::new().parse(filter))
}
}

impl FromStr for EnvFilter {
type Err = anyhow::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
EnvFilterBuilder::new().try_parse(s).map(EnvFilter::new)
}
}

/// A builder for the env log filter.
///
/// It can be used to parse a set of directives from a string before building a [EnvFilter]
Expand Down
61 changes: 0 additions & 61 deletions src/filter/level.rs

This file was deleted.

39 changes: 24 additions & 15 deletions src/filter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,15 @@

//! Determinate whether a log record should be processed.

use std::str::FromStr;

use log::LevelFilter;

pub use self::custom::CustomFilter;
#[cfg(feature = "env-filter")]
pub use self::env::EnvFilter;
pub use self::level::LevelFilter;
pub use self::target::TargetFilter;

mod custom;
#[cfg(feature = "env-filter")]
pub mod env;
mod level;
mod target;

/// The result of a filter may return.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand All @@ -39,31 +37,42 @@ pub enum FilterResult {

#[derive(Debug)]
pub enum Filter {
#[cfg(feature = "env-filter")]
Env(EnvFilter),
Level(LevelFilter),
Target(TargetFilter),
Custom(CustomFilter),
}

impl Filter {
pub(crate) fn enabled(&self, metadata: &log::Metadata) -> FilterResult {
match self {
#[cfg(feature = "env-filter")]
Filter::Env(filter) => filter.enabled(metadata),
Filter::Level(filter) => filter.enabled(metadata),
Filter::Target(filter) => filter.enabled(metadata),
Filter::Custom(filter) => filter.enabled(metadata),
}
}

pub(crate) fn matches(&self, record: &log::Record) -> FilterResult {
match self {
#[cfg(feature = "env-filter")]
Filter::Env(filter) => filter.matches(record),
Filter::Level(filter) => filter.enabled(record.metadata()),
Filter::Target(filter) => filter.enabled(record.metadata()),
Filter::Custom(filter) => filter.enabled(record.metadata()),
}
}
}

impl From<LevelFilter> for Filter {
fn from(filter: LevelFilter) -> Self {
EnvFilter::from(filter).into()
}
}

impl<'a> From<&'a str> for Filter {
fn from(filter: &'a str) -> Self {
EnvFilter::from(filter).into()
}
}

impl FromStr for Filter {
type Err = anyhow::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
EnvFilter::from_str(s).map(Into::into)
}
}
71 changes: 0 additions & 71 deletions src/filter/target.rs

This file was deleted.

0 comments on commit 2da9c7d

Please sign in to comment.