reups_lib/
logger.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
4* Copyright Nate Lust 2018*/
5
6use crate::argparse;
7use log;
8use std::boxed::Box;
9
10/// Structure which is responsible processing input from the std log
11/// api. It's members are the highest log level to output, and if
12/// the output should be sent to stdandard error instead of standard out.
13pub struct Logger {
14    log_level: log::LevelFilter,
15    stderr: bool,
16}
17
18impl Logger {
19    /// Creates a new logger object. Arguments are the maximum level to log,
20    /// and if the output should go to standard out or standard error.
21    pub fn new(log_level: log::LevelFilter, stderr: bool) -> Box<Logger> {
22        Box::new(Logger { log_level, stderr })
23    }
24}
25
26impl log::Log for Logger {
27    fn enabled(&self, metadata: &log::Metadata) -> bool {
28        metadata.level() <= self.log_level
29    }
30
31    fn log(&self, record: &log::Record) {
32        if self.enabled(record.metadata()) {
33            let message = format!("{}: {}", record.level(), record.args());
34            match self.stderr {
35                true => {
36                    eprintln!("{}", message);
37                }
38                false => {
39                    println!("{}", message);
40                }
41            }
42        }
43    }
44
45    fn flush(&self) {}
46}
47
48/// Builds and initializes a logging object with options from the command line
49/// and the stderr boolean which is governed by the context of the subcommand
50/// that initiates the logger.
51pub fn build_logger(args: &argparse::ArgMatches, stderr: bool) {
52    let level = match args.occurrences_of("verbose") {
53        0 => log::LevelFilter::Warn,
54        1 => log::LevelFilter::Info,
55        2 => log::LevelFilter::Debug,
56        _ => log::LevelFilter::Trace,
57    };
58    log::set_boxed_logger(Logger::new(level, stderr)).unwrap();
59    log::set_max_level(level)
60}