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
//! This module lets us be more flexible with logging.
//! It provides different types of loggers for different purposes, if run in tui or
//! somewhere (maybe a syslog log).
use env_logger;
use flexi_logger;
use syslog::{self, Facility, Formatter3164};

pub enum Log {
    Console,
    File,
    System,
}

/// The logger for all log-types: warn, info, trace, error, debug
pub struct Logit {}

/// The very practical logger. It can use 3 types of logging yet.
///  - system logger
///  - console logging
///  - file logging (used)
impl Logit {
    pub fn init(which: Log) {
        match which {
            Log::System => {
                let formatter = Formatter3164 {
                    facility: Facility::LOG_USER,
                    hostname: None,
                    process: env!("CARGO_PKG_NAME").into(),
                    pid: 42,
                };

                match syslog::unix(formatter) {
                    Err(e) => {
                        env_logger::init();
                        error!("impossible to connect to syslog: {:?}", e);
                    }
                    Ok(mut writer) => {
                        writer
                            .err("Logit init and test!")
                            .expect("could not write error message");
                    }
                }
            }
            Log::Console => {
                env_logger::init();
            }
            Log::File => {
                // now only from console, good is now:
                //       RUST_LOG=audiobookfinder=trace,adbflib=trace
                //       or
                //         RUST_LOG=adbfbinlib=trace
                //         RUST_LOG=adbfbinlib::net=trace
                //         RUST_LOG=audiobookfinder=trace,adbfbinlib=trace
                //
                //       and
                //         ADBF_LOG=file (or console,system)
                // see:
                // https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log.html
                flexi_logger::Logger::with_env()
                    .log_to_file()
                    .directory(".")
                    .format(flexi_logger::with_thread) // colored_with_thread
                    .suppress_timestamp()
                    .suffix("log")
                    .start()
                    .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e));
            }
        }
    }
}

/// Read env level given e.g. by command-line, environment variable
pub fn read_env_level(level: &str) -> Log {
    match level {
        "console" => Log::Console,
        "file" => Log::File,
        "system" => Log::System,
        _ => Log::System,
    }
}