1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
//! # Minimal logger with color support
//!
//! ```
//! # #[macro_use] extern crate log;
//! # extern crate mowl;
//! #
//! # fn main() {
//! mowl::init().unwrap();
//! warn!("Warning");
//! # }
//! ```
#![deny(missing_docs)]
extern crate log;
extern crate term;

#[macro_use]
extern crate error_chain;

pub mod error;
use error::*;

use log::{Log, LogRecord, LogLevel, LogMetadata};
use term::stderr;
use term::color::*;

/// Initializes the global logger with a specific `max_log_level`.
///
/// ```
/// # #[macro_use] extern crate log;
/// # extern crate mowl;
/// #
/// # fn main() {
/// mowl::init_with_level(log::LogLevel::Warn).unwrap();
///
/// warn!("A warning");
/// info!("A info message");
/// # }
/// ```
pub fn init_with_level(log_level: LogLevel) -> Result<()> {
    log::set_logger(|max_log_level| {
        max_log_level.set(log_level.to_log_level_filter());
        Box::new(Logger { level: log_level, enable_colors: true })
    })?;
    Ok(())
}

/// Initializes the global logger with a specific `max_log_level` and
/// without any coloring.
///
/// ```
/// # #[macro_use] extern crate log;
/// # extern crate mowl;
/// #
/// # fn main() {
/// mowl::init_with_level_and_without_colors(log::LogLevel::Warn).unwrap();
///
/// warn!("A warning");
/// info!("A info message");
/// # }
/// ```
pub fn init_with_level_and_without_colors(log_level: LogLevel) -> Result<()> {
    log::set_logger(|max_log_level| {
        max_log_level.set(log_level.to_log_level_filter());
        Box::new(Logger { level: log_level, enable_colors: false })
    })?;
    Ok(())
}

/// Initializes the global logger with `max_log_level` set to `LogLevel::Trace`.
///
/// # Examples
/// ```
/// # #[macro_use] extern crate log;
/// # extern crate mowl;
/// #
/// # fn main() {
/// mowl::init().unwrap();
/// warn!("Warning");
/// # }
/// ```
pub fn init() -> Result<()> {
    init_with_level(LogLevel::Trace)
}

/// The logging structure
pub struct Logger {
    level: LogLevel,
    enable_colors: bool,
}

impl Log for Logger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= self.level
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            if let Err(e) = self.log_result(record) {
                println!("Logging failed: {}", e);
            }
        }
    }
}

impl Logger {
    fn log_result(&self, record: &LogRecord) -> Result<()> {
        // We have to create a new terminal on each log because Send is not fulfilled
        let mut t = stderr().ok_or_else(|| "Could not create terminal.")?;
        if self.enable_colors {
            t.fg(BRIGHT_BLUE)?;
        }
        write!(t, "[{}] ", record.location().module_path())?;
        if self.enable_colors {
            match record.level() {
                LogLevel::Error => t.fg(BRIGHT_RED)?,
                LogLevel::Warn => t.fg(BRIGHT_YELLOW)?,
                LogLevel::Info => t.fg(BRIGHT_GREEN)?,
                LogLevel::Debug => t.fg(BRIGHT_CYAN)?,
                LogLevel::Trace => t.fg(BRIGHT_WHITE)?,
            };
        }
        write!(t, "[{}] ", record.level())?;
        if self.enable_colors {
            t.reset()?;
        }
        writeln!(t, "{}", record.args())?;
        Ok(())
    }

    /// Disable coloring output
    pub fn disable_colors(&mut self) {
        self.enable_colors = false;
    }
}