Skip to content

Commit

Permalink
Added support for module level filtering
Browse files Browse the repository at this point in the history
Added support for `RUST_LOG`-based module/target level filtering like in env_logger crate
  • Loading branch information
userffx committed Dec 7, 2023
1 parent 50729f3 commit f224f70
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,18 +149,49 @@ impl SimpleLogger {
/// [`with_level`] if `RUST_LOG` is not set or can't be parsed as a
/// standard log level.
///
/// module/target level filtering is supported
///
/// the following format is expected:
/// ```
/// RUST_LOG=[default-level][,][target][=][level][,...]
/// ```
/// example:
/// ```
/// RUST_LOG=warn,data=debug,hardware=debug
/// ```
///
/// This must be called after [`with_level`]. If called before
/// [`with_level`], it will have no effect.
///
/// [`with_level`]: #method.with_level
#[must_use = "You must call init() to begin logging"]
pub fn env(mut self) -> SimpleLogger {
self.default_level = std::env::var("RUST_LOG")
.ok()
.as_deref()
.map(log::LevelFilter::from_str)
.and_then(Result::ok)
.unwrap_or(self.default_level);
if let Ok(modules) = std::env::var("RUST_LOG").as_deref() {
let mut iter = modules.split(',');
iter.next()
.map(|pair| match log::LevelFilter::from_str(pair) {
Ok(level) => {
self.default_level = level;
None
},
Err(_) => Some(pair),
})
.and_then(|x| x).map(|pair| pair.split_once('='))
.and_then(|x| x).map(|(module, level)| {
let level = log::LevelFilter::from_str(level)
.unwrap_or(self.default_level);
self.module_levels.push((module.to_string(), level));
});

for (module, level) in iter
.map(|x| x.split_once('='))
.flat_map(|x| x)
{
let level = log::LevelFilter::from_str(level)
.unwrap_or(self.default_level);
self.module_levels.push((module.to_string(), level));
}
}

self
}
Expand Down

0 comments on commit f224f70

Please sign in to comment.