Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce colored log levels using ansi_term #88

Merged
merged 4 commits into from Nov 11, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -26,4 +26,5 @@ default = ["termcolor"]
log = { version = "0.4.*", features = ["std"] }
termcolor = { version = "1.1.*", optional = true }
paris = { version = "1.5.7", optional = true }
ansi_term = { version = "0.12", optional = true }
chrono = "0.4.1"
8 changes: 8 additions & 0 deletions src/config.rs
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 {
manio marked this conversation as resolved.
Show resolved Hide resolved
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
47 changes: 43 additions & 4 deletions src/loggers/logging.rs
Expand Up @@ -3,6 +3,23 @@ use crate::{Config, LevelPadding, ThreadLogMode, ThreadPadding};
use log::{LevelFilter, Record};
use std::io::{Error, Write};
use std::thread;
#[cfg(all(feature = "termcolor", feature = "ansi_term"))]
use termcolor::Color;

#[cfg(all(feature = "termcolor", feature = "ansi_term"))]
pub fn termcolor_to_ansiterm(color: &Color) -> Option<ansi_term::Color> {
match color {
Color::Black => Some(ansi_term::Color::Black),
Color::Red => Some(ansi_term::Color::Red),
Color::Green => Some(ansi_term::Color::Green),
Color::Yellow => Some(ansi_term::Color::Yellow),
Color::Blue => Some(ansi_term::Color::Blue),
Color::Magenta => Some(ansi_term::Color::Purple),
Color::Cyan => Some(ansi_term::Color::Cyan),
Color::White => Some(ansi_term::Color::White),
_ => None,
}
}

#[inline(always)]
pub fn try_log<W>(config: &Config, record: &Record<'_>, write: &mut W) -> Result<(), Error>
Expand Down Expand Up @@ -63,11 +80,33 @@ pub fn write_level<W>(record: &Record<'_>, write: &mut W, config: &Config) -> Re
where
W: Write + Sized,
{
match config.level_padding {
LevelPadding::Left => write!(write, "[{: >5}] ", record.level())?,
LevelPadding::Right => write!(write, "[{: <5}] ", record.level())?,
LevelPadding::Off => write!(write, "[{}] ", record.level())?,
#[cfg(all(feature = "termcolor", feature = "ansi_term"))]
let color = match &config.level_color[record.level() as usize] {
Some(termcolor) => {
if config.write_log_enable_colors {
termcolor_to_ansiterm(termcolor)
} else {
None
}
}
None => None,
};

let level = match config.level_padding {
LevelPadding::Left => format!("[{: >5}]", record.level()),
LevelPadding::Right => format!("[{: <5}]", record.level()),
LevelPadding::Off => format!("[{}]", record.level()),
};

#[cfg(all(feature = "termcolor", feature = "ansi_term"))]
match color {
Some(c) => write!(write, "{} ", c.paint(level))?,
None => write!(write, "{} ", level)?,
};

#[cfg(not(feature = "ansi_term"))]
write!(write, "{} ", level)?;

Ok(())
}

Expand Down
17 changes: 14 additions & 3 deletions src/loggers/termlog.rs
Expand Up @@ -5,7 +5,9 @@ use log::{
};
use std::io::{Error, Write};
use std::sync::Mutex;
use termcolor::{BufferedStandardStream, ColorChoice, ColorSpec, WriteColor};
use termcolor::{BufferedStandardStream, ColorChoice};
#[cfg(not(feature = "ansi_term"))]
use termcolor::{ColorSpec, WriteColor};

use super::logging::*;

Expand Down Expand Up @@ -128,16 +130,25 @@ impl TermLogger {
record: &Record<'_>,
term_lock: &mut BufferedStandardStream,
) -> Result<(), Error> {
#[cfg(not(feature = "ansi_term"))]
let color = self.config.level_color[record.level() as usize];

if self.config.time <= record.level() && self.config.time != LevelFilter::Off {
write_time(term_lock, &self.config)?;
}

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

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

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

if self.config.thread <= record.level() && self.config.thread != LevelFilter::Off {
Expand Down
10 changes: 5 additions & 5 deletions src/paris_macros/mod.rs
Expand Up @@ -2,7 +2,7 @@
///
/// Passed data uses a colorize_string formatter from a `paris` crate, so it can
/// contains special tags for controlling ANSI colors and styles
/// More info: https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html
/// More info: <https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html>
///
/// # Examples
///
Expand All @@ -29,7 +29,7 @@ macro_rules! info {
///
/// Passed data uses a colorize_string formatter from a `paris` crate, so it can
/// contains special tags for controlling ANSI colors and styles
/// More info: https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html
/// More info: <https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html>
///
/// # Examples
///
Expand All @@ -55,7 +55,7 @@ macro_rules! debug {
///
/// Passed data uses a colorize_string formatter from a `paris` crate, so it can
/// contains special tags for controlling ANSI colors and styles
/// More info: https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html
/// More info: <https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html>
///
/// # Examples
///
Expand Down Expand Up @@ -83,7 +83,7 @@ macro_rules! trace {
///
/// Passed data uses a colorize_string formatter from a `paris` crate, so it can
/// contains special tags for controlling ANSI colors and styles
/// More info: https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html
/// More info: <https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html>
///
/// # Examples
///
Expand All @@ -108,7 +108,7 @@ macro_rules! warn {
///
/// Passed data uses a colorize_string formatter from a `paris` crate, so it can
/// contains special tags for controlling ANSI colors and styles
/// More info: https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html
/// More info: <https://docs.rs/paris/1.5.7/paris/formatter/fn.colorize_string.html>
///
/// # Examples
///
Expand Down