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
// Copyright 2017-2021 Lukas Pustina <lukas@pustina.de>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use std::ffi::OsString;

use anyhow::Result;
use tracing::subscriber::set_global_default;
use tracing_log::LogTracer;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::fmt::{self, format::FmtSpan};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::EnvFilter;

pub struct Logging {
    verbosity: u64,
    rust_log: Option<OsString>,
    color: bool,
    debug: bool,
}

impl Logging {
    pub fn new(verbosity: u64, rust_log: Option<OsString>, color: bool, debug: bool) -> Logging {
        Logging {
            verbosity,
            rust_log,
            color,
            debug,
        }
    }

    fn log_level(verbosity: u64) -> LevelFilter {
        match verbosity {
            0 => LevelFilter::WARN,
            1 => LevelFilter::INFO,
            2 => LevelFilter::DEBUG,
            _ => LevelFilter::TRACE,
        }
    }

    pub fn start(self) -> Result<()> {
        // Subscribe to all log crate log messages and transform them to a tracing events
        LogTracer::init()?;

        let log_level = Logging::log_level(self.verbosity);
        let filter = if self.rust_log.is_some() {
            // This is controlled by the env variable RUST_LOG and overrides the max level, if set
            EnvFilter::from_default_env()
        } else {
            // If RUST_LOG is not set, use `-` arg to determine log level
            EnvFilter::from(format!("{}={}", env!("CARGO_CRATE_NAME"), log_level))
        };

        let fmt = if self.debug {
            fmt::layer()
                .with_ansi(self.color)
                .with_thread_ids(true)
                .with_thread_names(true)
                .with_target(true)
                .with_span_events(FmtSpan::FULL)
        } else {
            fmt::layer()
                .with_ansi(self.color)
                .with_thread_ids(true)
                .with_thread_names(true)
                .with_target(false)
        };

        let registry = tracing_subscriber::registry().with(filter).with(fmt);
        set_global_default(registry)?;

        Ok(())
    }
}