outlog 0.1.0

A simple logging system based on the log crate.
Documentation
//! Color support using [SGR] sequences.
//!
//! Note that these are statically generated and not configurable,
//! as terminal sequences are notoriously difficult to sanitize.
//!
//! [SGR]: https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters

use crate::config::{Color, Config};

/// Convenience macro to generate SGR sequences from a parameter string.
macro_rules! sgr_const {
    (
        $(
            $(#[$meta:meta])*
            $vis:vis $ident:ident = $sgr:expr
        ),* $(,)?
    ) => {
        $(
            $(#[$meta])*
            $vis const $ident: &'static str = std::concat!("\x1b[", $sgr, "m");
        )*
    }
}

sgr_const! {
    COLOR_ERROR = "1;31",
    COLOR_WARN  = "1;33",
    COLOR_INFO  = "1;36",
    COLOR_DEBUG = "35",
    COLOR_TRACE = "32",
    COLOR_NONE  = "0"
}

/// Returns whether stdout is a TTY.\
/// This is to prevent writing color sequences when stdout is redirected to a file or piped.
pub fn stdout_isatty() -> bool {
    atty::is(atty::Stream::Stdout)
}

/// Returns whether color output is enabled for the current configuration.
pub fn color_enabled(config: &Config) -> bool {
    match config.color {
        Color::Off  => false,
        Color::On   => true,
        Color::Auto => stdout_isatty()
    }
}

/// Returns a pair of SGR sequences appropriate for printing `level`.
pub fn get_colors(level: log::Level) -> (&'static str, &'static str) {
    let color = match level {
        log::Level::Error => COLOR_ERROR,
        log::Level::Warn  => COLOR_WARN,
        log::Level::Info  => COLOR_INFO,
        log::Level::Debug => COLOR_DEBUG,
        log::Level::Trace => COLOR_TRACE,
    };

    (color, COLOR_NONE)
}