about summary refs log tree commit diff
path: root/src/settings.rs
blob: 1f205814d1dd1e350a24a526aceb62e10102116e (plain) (blame)
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
use config::{Config, ConfigError};
use log::LevelFilter;
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Root};
use log4rs::encode::pattern::PatternEncoder;

#[derive(Debug, Deserialize, Clone)]
pub struct Logging {
    #[serde(default = "Logging::default_level")]
    pub level: LevelFilter,

    #[serde(default = "Logging::default_file")]
    pub file: String,

    #[serde(default = "Logging::default_print_backtrace")]
    pub print_backtrace: bool,
}

impl Default for Logging {
    fn default() -> Self {
        Logging {
            level: LevelFilter::Off,
            file: "debug.log".to_string(),
            print_backtrace: true,
        }
    }
}

impl Logging {
    pub fn init_log(&self) {
        let logfile = FileAppender::builder()
            .encoder(Box::new(PatternEncoder::new("{d} {l} - {m}\n")))
            .build(self.file.clone())
            .unwrap();

        let config = log4rs::config::Config::builder()
            .appender(Appender::builder().build("logfile", Box::new(logfile)))
            .build(Root::builder().appender("logfile").build(self.level))
            .unwrap();

        log4rs::init_config(config).unwrap();
    }

    fn default_level() -> LevelFilter {
        Logging::default().level
    }

    fn default_file() -> String {
        Logging::default().file
    }

    fn default_print_backtrace() -> bool {
        Logging::default().print_backtrace
    }
}

#[derive(Debug, Deserialize, Clone)]
pub struct Settings {
    pub seed: Option<u64>,
    pub logging: Logging,
}

impl Settings {
    pub fn load() -> Result<Self, ConfigError> {
        let mut s = Config::new();
        s.merge(config::File::with_name("Config").required(false))?;
        s.merge(config::Environment::with_prefix("XAN"))?;
        s.try_into()
    }
}