summaryrefslogtreecommitdiffstats
path: root/src/logging.rs
blob: 15008be89595b6aa20d0ff1a5b134988993417d7 (plain)
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
use figment::Provider;
use std::{fs::File, ops::Deref, sync::Arc};
use tracing::metadata::LevelFilter;
use tracing_subscriber::{prelude::*, Layer};

pub use config::Config;
pub use error::{Error, Result};
pub use level::Level;

mod config;
mod error;
mod level;

pub struct Logging(Config);

impl Logging {
    pub fn new() -> Result<Self> {
        Self::from_provider(Config::figment())
    }

    /// Extract `Config` from `provider` to construct new `Finder`
    pub fn from_provider<T: Provider>(provider: T) -> Result<Self> {
        Config::extract(&provider)
            .map_err(Into::into)
            .map(Into::into)
    }

    pub fn init(&self) -> Result<()> {
        let stdout_layer = tracing_subscriber::fmt::layer()
            .pretty()
            .with_filter(LevelFilter::from(self.level));

        let log_layer = if self.level.is_some() {
            let file = File::create(&self.path)?;
            tracing_subscriber::fmt::layer()
                .with_writer(Arc::new(file))
                .with_filter(LevelFilter::from(self.level))
                .into()
        } else {
            None
        };

        tracing_subscriber::registry()
            .with(stdout_layer)
            .with(log_layer)
            .init();

        Ok(())
    }
}

impl Deref for Logging {
    type Target = Config;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<Config> for Logging {
    fn from(value: Config) -> Self {
        Self(value)
    }
}