Skip to content

Commit

Permalink
Add a write_log_enable_colors configuration switch
Browse files Browse the repository at this point in the history
This flags controls writing log levels colored in the log.
  • Loading branch information
manio committed Nov 9, 2021
1 parent 1f76fd5 commit feb3458
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
8 changes: 8 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub struct Config {
pub(crate) filter_ignore: Cow<'static, [Cow<'static, str>]>,
#[cfg(feature = "termcolor")]
pub(crate) level_color: [Option<Color>; 6],
pub(crate) write_log_enable_colors: bool,
}

/// Builder for the Logger Configurations (`Config`)
Expand Down Expand Up @@ -194,6 +195,12 @@ impl ConfigBuilder {
self
}

/// set if you want to write colors in the logfile (default is Off)
pub fn set_write_log_enable_colors(&mut self, local: bool) -> &mut ConfigBuilder {
self.0.write_log_enable_colors = local;
self
}

/// Add allowed module filters.
/// If any are specified, only records from modules starting with one of these entries will be printed
///
Expand Down Expand Up @@ -281,6 +288,7 @@ impl Default for Config {
time_local: false,
filter_allow: Cow::Borrowed(&[]),
filter_ignore: Cow::Borrowed(&[]),
write_log_enable_colors: false,

#[cfg(feature = "termcolor")]
level_color: [
Expand Down
8 changes: 7 additions & 1 deletion src/loggers/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,13 @@ where
{
#[cfg(all(feature = "termcolor", feature = "ansi_term"))]
let color = match &config.level_color[record.level() as usize] {
Some(termcolor) => termcolor_to_ansiterm(termcolor),
Some(termcolor) => {
if config.write_log_enable_colors {
termcolor_to_ansiterm(termcolor)
} else {
None
}
}
None => None,
};

Expand Down
8 changes: 6 additions & 2 deletions src/loggers/termlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,16 @@ impl TermLogger {

if self.config.level <= record.level() && self.config.level != LevelFilter::Off {
#[cfg(not(feature = "ansi_term"))]
term_lock.set_color(ColorSpec::new().set_fg(color))?;
if !self.config.write_log_enable_colors {
term_lock.set_color(ColorSpec::new().set_fg(color))?;
}

write_level(record, term_lock, &self.config)?;

#[cfg(not(feature = "ansi_term"))]
term_lock.reset()?;
if !self.config.write_log_enable_colors {
term_lock.reset()?;
}
}

if self.config.thread <= record.level() && self.config.thread != LevelFilter::Off {
Expand Down

0 comments on commit feb3458

Please sign in to comment.