Skip to content

Commit

Permalink
Merge pull request #88 from twiby/main
Browse files Browse the repository at this point in the history
add configure method, to enable users to own a valid configured instance before calling `set_boxed_logger`
  • Loading branch information
borntyping authored Nov 23, 2023
2 parents 76d2107 + b8c149b commit 4e55405
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,27 @@ Multiple features can be combined.
features = ["colors", "threads", "timestamps", "nightly", "stderr"]
```

Wrapping with another logger
----------------------------

Users that might want to wrap this logger to be able to catch log events for various
reasons can setup the logger as follows:

On windows machines:
```rust
let logger = SimpleLogger::new();
set_up_color_terminal();
let max_level = logger.max_level();
```

Otherwise:
```rust
let logger = SimpleLogger::new();
let max_level = logger.max_level();
```

The user can then themselves call `log::set_max_level` and `log::set_boxed_logger` or equivalent as they wish.

Licence
-------

Expand Down
26 changes: 15 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,24 +341,28 @@ impl SimpleLogger {
self
}

/// 'Init' the actual logger, instantiate it and configure it,
/// this method MUST be called in order for the logger to be effective.
pub fn init(mut self) -> Result<(), SetLoggerError> {
#[cfg(all(windows, feature = "colored"))]
set_up_color_terminal();

/// Configure the logger
pub fn max_level(&mut self) -> LevelFilter {
/* Sort all module levels from most specific to least specific. The length of the module
* name is used instead of its actual depth to avoid module name parsing.
*/
self.module_levels
.sort_by_key(|(name, _level)| name.len().wrapping_neg());
let max_level = self.module_levels.iter().map(|(_name, level)| level).copied().max();
let max_level = max_level
max_level
.map(|lvl| lvl.max(self.default_level))
.unwrap_or(self.default_level);
.unwrap_or(self.default_level)
}

/// 'Init' the actual logger and instantiate it,
/// this method MUST be called in order for the logger to be effective.
pub fn init(mut self) -> Result<(), SetLoggerError> {
#[cfg(all(windows, feature = "colored"))]
set_up_color_terminal();

let max_level = self.max_level();
log::set_max_level(max_level);
log::set_boxed_logger(Box::new(self))?;
Ok(())
log::set_boxed_logger(Box::new(self))
}
}

Expand Down Expand Up @@ -488,7 +492,7 @@ impl Log for SimpleLogger {
}

#[cfg(all(windows, feature = "colored"))]
fn set_up_color_terminal() {
pub fn set_up_color_terminal() {
use std::io::{stdout, IsTerminal};

if stdout().is_terminal() {
Expand Down

0 comments on commit 4e55405

Please sign in to comment.