feat(logger): allow ignoring context with glob matching

This commit is contained in:
Lucas Colombo 2024-05-26 03:57:55 -03:00
parent a9dc3faf4c
commit 5dc42a6f80
Signed by: lucas
GPG Key ID: EF34786CFEFFAE35
3 changed files with 35 additions and 17 deletions

7
Cargo.lock generated
View File

@ -122,6 +122,12 @@ version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
[[package]]
name = "glob-match"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d"
[[package]] [[package]]
name = "iana-time-zone" name = "iana-time-zone"
version = "0.1.60" version = "0.1.60"
@ -180,6 +186,7 @@ dependencies = [
"chrono", "chrono",
"croner", "croner",
"eyre", "eyre",
"glob-match",
"log", "log",
"num-traits", "num-traits",
"tokio", "tokio",

View File

@ -57,6 +57,7 @@ tokio = { version = "1.37.0", optional = true }
croner = { version = "2.0.4", optional = true } croner = { version = "2.0.4", optional = true }
num-traits = { version = "0.2.18", optional = true } num-traits = { version = "0.2.18", optional = true }
tokio_schedule = "0.3.1" tokio_schedule = "0.3.1"
glob-match = "0.2.1"
[[example]] [[example]]

View File

@ -1,4 +1,5 @@
pub mod datetime; pub mod datetime;
use glob_match::glob_match;
pub use log::{ pub use log::{
debug, error, info, set_max_level, trace, warn, Level, LevelFilter, Log, Metadata, Record, debug, error, info, set_max_level, trace, warn, Level, LevelFilter, Log, Metadata, Record,
}; };
@ -70,7 +71,7 @@ impl StyledRecord {
pub struct ConsoleLogger { pub struct ConsoleLogger {
name: String, name: String,
time_fn: fn() -> String, time_fn: fn() -> String,
ignored_ctx: Vec<String>, ctx_ignore_globs: Vec<String>,
} }
impl ConsoleLogger { impl ConsoleLogger {
@ -81,7 +82,7 @@ impl ConsoleLogger {
let logger = Box::new(ConsoleLogger { let logger = Box::new(ConsoleLogger {
name: context.as_ref().to_string(), name: context.as_ref().to_string(),
time_fn: datetime::utc_current_time, time_fn: datetime::utc_current_time,
ignored_ctx: vec![], ctx_ignore_globs: vec![],
}); });
log::set_logger(Box::leak(logger) as &'static dyn Log) log::set_logger(Box::leak(logger) as &'static dyn Log)
.map(|()| log::set_max_level(max_level.to_level_filter())) .map(|()| log::set_max_level(max_level.to_level_filter()))
@ -102,7 +103,7 @@ impl ConsoleLogger {
let logger = Box::new(ConsoleLogger { let logger = Box::new(ConsoleLogger {
name: context.as_ref().to_string(), name: context.as_ref().to_string(),
time_fn, time_fn,
ignored_ctx: vec![], ctx_ignore_globs: vec![],
}); });
log::set_logger(Box::leak(logger) as &'static dyn Log) log::set_logger(Box::leak(logger) as &'static dyn Log)
.map(|()| log::set_max_level(max_level.to_level_filter())) .map(|()| log::set_max_level(max_level.to_level_filter()))
@ -120,7 +121,12 @@ impl ConsoleLogger {
/// returns true if the context should be ignored /// returns true if the context should be ignored
fn should_ignore(&self, ctx: &String) -> bool { fn should_ignore(&self, ctx: &String) -> bool {
self.ignored_ctx.contains(ctx) for glob in &self.ctx_ignore_globs {
if glob_match(glob, ctx) {
return true;
}
}
false
} }
} }
@ -168,8 +174,8 @@ impl Log for ConsoleLogger {
/// ///
/// this struct is used to set up the logger with more flexibility. /// this struct is used to set up the logger with more flexibility.
/// ///
/// It allows for setting the logger name, the time function, the ignored contexts, and the max /// It allows for setting the logger name, the time function, the ignored contexts/globs, and the
/// level. /// max level.
/// ///
/// The `install` method is used to build and install the logger. Should be called at the end of the /// The `install` method is used to build and install the logger. Should be called at the end of the
/// builder chain. /// builder chain.
@ -193,7 +199,7 @@ impl Log for ConsoleLogger {
pub struct SetupBuilder { pub struct SetupBuilder {
name: Option<String>, name: Option<String>,
time_fn: Option<fn() -> String>, time_fn: Option<fn() -> String>,
ignored_ctx: Option<Vec<String>>, ctx_ignore_globs: Option<Vec<String>>,
max_level: Option<Level>, max_level: Option<Level>,
} }
@ -202,7 +208,7 @@ impl Default for SetupBuilder {
Self { Self {
name: Some("".to_string()), name: Some("".to_string()),
time_fn: Some(datetime::utc_current_time), time_fn: Some(datetime::utc_current_time),
ignored_ctx: Some(vec![]), ctx_ignore_globs: Some(vec![]),
max_level: Some(Level::Info), max_level: Some(Level::Info),
} }
} }
@ -235,21 +241,25 @@ impl SetupBuilder {
/// **🧉 » `ignore_all`** /// **🧉 » `ignore_all`**
/// ///
/// Sets the ignored contexts from a list of strings /// Sets the ignored contexts/context globs from a list of strings.
pub fn ignore_all(mut self, ignored_ctx: Vec<String>) -> Self { ///
self.ignored_ctx = Some(ignored_ctx); /// Globs are allowed.
pub fn ignore_all(mut self, ctx_ignored_globs: Vec<String>) -> Self {
self.ctx_ignore_globs = Some(ctx_ignored_globs);
self self
} }
/// **🧉 » `ignore`** /// **🧉 » `ignore`**
/// ///
/// Adds a context to the ignored list. /// Adds a context/context glob to the ignored list.
/// ///
/// Unlike `ignore_all`, this method allows for adding a single ignored context at a time. /// Unlike `ignore_all`, this method allows for adding a single ignored context at a time.
pub fn ignore<Str: AsRef<str>>(mut self, ctx: Str) -> Self { ///
let mut ignored_ctx = self.ignored_ctx.unwrap(); /// Globs are allowed.
ignored_ctx.push(ctx.as_ref().to_string()); pub fn ignore<Str: AsRef<str>>(mut self, glob: Str) -> Self {
self.ignored_ctx = Some(ignored_ctx); let mut ignored_ctx = self.ctx_ignore_globs.unwrap();
ignored_ctx.push(glob.as_ref().to_string());
self.ctx_ignore_globs = Some(ignored_ctx);
self self
} }
@ -260,7 +270,7 @@ impl SetupBuilder {
let logger = Box::new(ConsoleLogger { let logger = Box::new(ConsoleLogger {
name: self.name.unwrap_or("".to_string()), name: self.name.unwrap_or("".to_string()),
time_fn: self.time_fn.unwrap_or(datetime::utc_current_time), time_fn: self.time_fn.unwrap_or(datetime::utc_current_time),
ignored_ctx: self.ignored_ctx.unwrap_or(vec![]), ctx_ignore_globs: self.ctx_ignore_globs.unwrap_or(vec![]),
}); });
log::set_logger(Box::leak(logger) as &'static dyn Log) log::set_logger(Box::leak(logger) as &'static dyn Log)
.map(|()| log::set_max_level(self.max_level.unwrap().to_level_filter())) .map(|()| log::set_max_level(self.max_level.unwrap().to_level_filter()))