Skip to content

Commit 717086e

Browse files
committed
Added support for module level filtering
Added support for `RUST_LOG`-based module/target level filtering like in env_logger crate
1 parent 50729f3 commit 717086e

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

src/lib.rs

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,18 +149,48 @@ impl SimpleLogger {
149149
/// [`with_level`] if `RUST_LOG` is not set or can't be parsed as a
150150
/// standard log level.
151151
///
152+
/// module/target level filtering is supported
153+
///
154+
/// the following format is expected:
155+
/// ```text
156+
/// RUST_LOG=[default-level][,][target][=][level][,...]
157+
/// ```
158+
/// example:
159+
/// ```text
160+
/// RUST_LOG=warn,data=debug,hardware=debug
161+
/// ```
162+
///
152163
/// This must be called after [`with_level`]. If called before
153164
/// [`with_level`], it will have no effect.
154165
///
155166
/// [`with_level`]: #method.with_level
156167
#[must_use = "You must call init() to begin logging"]
157168
pub fn env(mut self) -> SimpleLogger {
158-
self.default_level = std::env::var("RUST_LOG")
159-
.ok()
160-
.as_deref()
161-
.map(log::LevelFilter::from_str)
162-
.and_then(Result::ok)
163-
.unwrap_or(self.default_level);
169+
if let Ok(modules) = std::env::var("RUST_LOG").as_deref() {
170+
let mut iter = modules.split(',');
171+
172+
if let Some((module, level)) = iter
173+
.next()
174+
.map(|pair| match log::LevelFilter::from_str(pair) {
175+
Ok(level) => {
176+
self.default_level = level;
177+
None
178+
}
179+
Err(_) => Some(pair),
180+
})
181+
.and_then(|x| x)
182+
.map(|pair| pair.split_once('='))
183+
.and_then(|x| x)
184+
{
185+
let level = log::LevelFilter::from_str(level).unwrap_or(self.default_level);
186+
self.module_levels.push((module.to_string(), level));
187+
}
188+
189+
for (module, level) in iter.flat_map(|x| x.split_once('=')) {
190+
let level = log::LevelFilter::from_str(level).unwrap_or(self.default_level);
191+
self.module_levels.push((module.to_string(), level));
192+
}
193+
}
164194

165195
self
166196
}

0 commit comments

Comments
 (0)