Skip to content

Commit c4eef43

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 c4eef43

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

src/lib.rs

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,18 +149,51 @@ 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.next()
173+
.map(|pair| match log::LevelFilter::from_str(pair) {
174+
Ok(level) => {
175+
self.default_level = level;
176+
None
177+
},
178+
Err(_) => Some(pair),
179+
})
180+
.and_then(|x| x)
181+
.map(|pair| pair.split_once('='))
182+
.and_then(|x| x)
183+
{
184+
let level = log::LevelFilter::from_str(level)
185+
.unwrap_or(self.default_level);
186+
self.module_levels.push((module.to_string(), level));
187+
}
188+
189+
for (module, level) in iter
190+
.flat_map(|x| x.split_once('='))
191+
{
192+
let level = log::LevelFilter::from_str(level)
193+
.unwrap_or(self.default_level);
194+
self.module_levels.push((module.to_string(), level));
195+
}
196+
}
164197

165198
self
166199
}

0 commit comments

Comments
 (0)