Skip to content

Commit

Permalink
feat: support setting global max_level
Browse files Browse the repository at this point in the history
Signed-off-by: tison <[email protected]>
  • Loading branch information
tisonkun committed Oct 9, 2024
1 parent 0bbf050 commit 3007fde
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ impl Dispatch {
#[derive(Debug)]
pub struct Logger {
dispatches: Vec<Dispatch>,
max_level: LevelFilter,
}

impl Default for Logger {
Expand All @@ -146,14 +147,24 @@ impl Logger {
/// Create a new [`Logger`] instance.
#[must_use = "call `dispatch` to add a dispatch to the logger and `apply` to set the global logger"]
pub fn new() -> Logger {
Self { dispatches: vec![] }
Self {
dispatches: vec![],
max_level: LevelFilter::Trace,
}
}

/// Set the global maximum log level.
///
/// This will be passed to [`log::set_max_level`] on [`Logger::apply`].
#[must_use = "call `apply` to set the global logger"]
pub fn max_level(mut self, max_level: LevelFilter) -> Self {
self.max_level = max_level;
self
}
}

impl Logger {
/// Add a [`Dispatch`] to the [`Logger`].
#[must_use = "call `apply` to set the global logger"]
pub fn dispatch(mut self, dispatch: Dispatch) -> Logger {
pub fn dispatch(mut self, dispatch: Dispatch) -> Self {
self.dispatches.push(dispatch);
self
}
Expand All @@ -164,8 +175,9 @@ impl Logger {
///
/// An error is returned if the global logger has already been set.
pub fn apply(self) -> Result<(), log::SetLoggerError> {
let max_level = self.max_level;
log::set_boxed_logger(Box::new(self))?;
log::set_max_level(LevelFilter::Trace);
log::set_max_level(max_level);
Ok(())
}
}
Expand All @@ -192,7 +204,6 @@ impl log::Log for Logger {
}
}

// TODO(tisonkun): logback and log4j2 support custom error handling (status listener).
fn handle_error(record: &Record, error: anyhow::Error) {
let Err(fallback_error) = write!(
std::io::stderr(),
Expand Down

0 comments on commit 3007fde

Please sign in to comment.